<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_STRICT ^ E_WARNING ^ E_DEPRECATED );

function __autoload_my_classes( $classname )
{
  $q = explode( '\\', $classname );
  $c = array_pop( $q );
  $f = 'autoload/' . implode( '/', $q ) . '/class.' . $c . '.php';

  if ( file_exists( $f ) )
    require_once( $f );
}
spl_autoload_register( '__autoload_my_classes' );
date_default_timezone_set( 'Europe/Warsaw' );

require_once 'config.php';
require_once 'libraries/medoo/medoo.php';
require_once 'libraries/grid/config.php';
require_once 'libraries/phpmailer/class.phpmailer.php';
require_once 'libraries/phpmailer/class.smtp.php';
require_once 'libraries/rb.php';

session_start();

$mdb = new medoo( [
    'database_type' => 'mysql',
    'database_name' => $database['name'],
    'server'        => $database['host'],
    'username'      => $database['user'],
    'password'      => $database['password'],
    'charset'       => 'utf8'
  ] );

\R::setup( 'mysql:host=' . $database['host'] . ';dbname=' . $database['name'], $database['user'], $database['password'] );
\R::ext( 'xdispense', function( $type )
{
  return R::getRedBean() -> dispense( $type );
} );

// dodawanie domeny przez API
if ( \S::get( 'action' ) == 'domain_tester_add' )
{
  if ( !$mdb -> count( 'domain_tester', [ 'AND' => [ 'url' => \S::get( 'domain' ), 'hidden' => 0 ] ] ) )
  {
    $mdb -> insert( 'domain_tester', [
      'url' => \S::get( 'domain' )
    ] );
  }

  echo json_encode( ['result' => 'ok'] );
  exit;
}

// Open Page Rank - pobieranie domeny
if ( \S::get( 'action' ) == 'domain_opr_check' )
{
  $mdb -> delete( 'domain_tester', [ 'url' => '' ] );

  $domain = $mdb -> get( 'domain_tester', '*', [ 'opr' => null, 'ORDER' => [ 'date_add' => 'DESC' ] ] );
  if ( $domain )
  {
    $result['id'] = $domain['id'];
    $result['url'] = $domain['url'];
    $result['domains_left'] = $mdb -> count( 'domain_tester', [ 'opr' => null ] );
    $result['result'] = 'ok';

    echo json_encode( $result );
  }
  else
    echo json_encode( ['result' => 'bad'] );
  exit;
}

// Dodawanie komentarza do kampanii przez API (z Claude Code)
if ( \S::get( 'action' ) == 'campaign_comment_add' )
{
  $api_key = trim( \S::get( 'api_key' ) );
  $stored_key = $mdb -> get( 'settings', 'setting_value', [ 'setting_key' => 'api_key' ] );

  if ( !$api_key || !$stored_key || $api_key !== $stored_key )
  {
    echo json_encode( [ 'result' => 'error', 'message' => 'Invalid api_key' ] );
    exit;
  }

  $external_campaign_id = trim( \S::get( 'campaign_id' ) );
  $client_id_param = trim( \S::get( 'client_id' ) );
  $comment = trim( \S::get( 'comment' ) );
  $date = \S::get( 'date' ) ?: date( 'Y-m-d' );

  if ( !$external_campaign_id || !$client_id_param || !$comment )
  {
    echo json_encode( [ 'result' => 'error', 'message' => 'Missing required params: campaign_id, client_id, comment' ] );
    exit;
  }

  $client_id_clean = str_replace( '-', '', $client_id_param );

  $local_campaign = $mdb -> query(
    'SELECT c.id
     FROM campaigns c
     JOIN clients cl ON c.client_id = cl.id
     WHERE c.campaign_id = :campaign_id
       AND REPLACE( cl.google_ads_customer_id, \'-\', \'\' ) = :client_id
     LIMIT 1',
    [
      ':campaign_id' => $external_campaign_id,
      ':client_id' => $client_id_clean
    ]
  ) -> fetch( \PDO::FETCH_ASSOC );

  if ( !$local_campaign )
  {
    echo json_encode( [ 'result' => 'error', 'message' => 'Campaign not found' ] );
    exit;
  }

  \factory\Campaigns::add_campaign_comment( $local_campaign['id'], $comment, $date );

  echo json_encode( [ 'result' => 'ok' ] );
  exit;
}

// Zmiana custom_label_4 dla produktu przez API
if ( \S::get( 'action' ) == 'product_custom_label_4_set' )
{
  $api_key = trim( \S::get( 'api_key' ) );
  $stored_key = $mdb -> get( 'settings', 'setting_value', [ 'setting_key' => 'api_key' ] );

  if ( !$api_key || !$stored_key || $api_key !== $stored_key )
  {
    echo json_encode( [ 'result' => 'error', 'message' => 'Invalid api_key' ] );
    exit;
  }

  $offer_id        = trim( \S::get( 'offer_id' ) );
  $client_id_param = trim( \S::get( 'client_id' ) );
  $custom_label_4  = trim( \S::get( 'custom_label_4' ) );

  if ( !$offer_id || !$client_id_param )
  {
    echo json_encode( [ 'result' => 'error', 'message' => 'Missing required params: offer_id, client_id' ] );
    exit;
  }

  $product = $mdb -> query(
    'SELECT p.id
     FROM products p
     JOIN clients cl ON p.client_id = cl.id
     WHERE p.offer_id = :offer_id
       AND cl.id = :client_id
     LIMIT 1',
    [
      ':offer_id'  => $offer_id,
      ':client_id' => (int) $client_id_param
    ]
  ) -> fetch( \PDO::FETCH_ASSOC );

  if ( !$product )
  {
    echo json_encode( [ 'result' => 'error', 'message' => 'Product not found' ] );
    exit;
  }

  \factory\Products::set_product_data( $product['id'], 'custom_label_4', $custom_label_4 );
  \factory\Products::add_product_comment( $product['id'], 'Zmiana etykiety 4 na: ' . $custom_label_4 . ' (API)' );

  echo json_encode( [ 'result' => 'ok' ] );
  exit;
}

// Open Page Rank - zapis
if ( \S::get( 'action' ) == 'domain_opr_save' )
{
  $mdb -> update( 'domain_tester', [
    'opr' => str_replace( ',', '.', \S::get( 'page_rank' ) ),
    'opr_date' => date( 'Y-m-d H:i:s' )
  ], [
    'id' => \S::get( 'domain_id' )
  ] );

  echo json_encode( ['result' => 'ok'] );
  exit;
}