<?php
/**
 * remarketing_cron.php — Napi remarketing email küldő (cron job)
 * 
 * HASZNÁLAT:
 *   Crontab-ba (naponta 1x, pl. reggel 9-kor):
 *   0 9 * * * php /home/deeldabr/public_html/remarketing_cron.php >> /home/deeldabr/logs/remarketing.log 2>&1
 * 
 * MIT CSINÁL:
 *   1. Megkeresi az összes remarketing_active = 1 main customert (easyJet: customers tábla)
 *   2. Megkeresi az összes remarketing_active = 1 holder passengert (Wizz Air: wz_passengers tábla)
 *   3. Kiszámolja hány nap telt el a claim_mail_sent_at óta
 *   4. Ha elérte a megfelelő napot ÉS az adott step-et még nem kapta meg → elküldi
 *   5. Ha az ügyfél feltöltötte az ID-t → leállítja a remarketinget
 *   6. Ha mind az 5 email elment → leállítja a remarketinget
 */

// ===== KONFIGURÁCIÓ =====
define('REMARKETING_SCHEDULE', [
    1 => ['days' => 1,  'template' => 'remarketing-day1.html'],
    2 => ['days' => 3,  'template' => 'remarketing-day3.html'],
    3 => ['days' => 6,  'template' => 'remarketing-day6.html'],
    4 => ['days' => 9,  'template' => 'remarketing-day9.html'],
    5 => ['days' => 12, 'template' => 'remarketing-day12.html'],
]);

// Wizz Air uses separate templates (same schedule, different branding)
define('REMARKETING_SCHEDULE_WZ', [
    1 => ['days' => 1,  'template' => 'remarketing-wz-day1.html'],
    2 => ['days' => 3,  'template' => 'remarketing-wz-day3.html'],
    3 => ['days' => 6,  'template' => 'remarketing-wz-day6.html'],
    4 => ['days' => 9,  'template' => 'remarketing-wz-day9.html'],
    5 => ['days' => 12, 'template' => 'remarketing-wz-day12.html'],
]);

// ===== DB KAPCSOLAT =====
$DB_HOST = 'localhost';
$DB_NAME = 'deeldabr_eu261';
$DB_USER = 'deeldabr_eu261';
$DB_PASS = 'ASDjaS(DCWEFHjewke3we4f@#';

try {
    $pdo = new PDO("mysql:host={$DB_HOST};dbname={$DB_NAME};charset=utf8mb4", $DB_USER, $DB_PASS, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (PDOException $e) {
    die('[ERROR] DB connection failed: ' . $e->getMessage() . PHP_EOL);
}

// ===== MAILER =====
require_once __DIR__ . '/mailer.php';

// ===== MAIN =====
$startTime = microtime(true);
$log = function($msg) {
    echo '[' . date('Y-m-d H:i:s') . '] ' . $msg . PHP_EOL;
};

$log('=== Remarketing cron start ===');

$sentCount = 0;
$stoppedCount = 0;
$errorCount = 0;

// =====================================================================
// PART 1: easyJet — customers tábla (eredeti logika)
// =====================================================================
$log('--- easyJet (customers table) ---');

$stmt = $pdo->query("
    SELECT c.*, 
           DATEDIFF(NOW(), c.claim_mail_sent_at) AS days_since_claim
    FROM customers c
    WHERE c.remarketing_active = 1
      AND c.claim_mail_sent_at IS NOT NULL
      AND c.is_main = 1
    ORDER BY c.claim_mail_sent_at ASC
");
$customers = $stmt->fetchAll();
$log('Active easyJet remarketing customers: ' . count($customers));

foreach ($customers as $customer) {
    $customerId   = $customer['id'];
    $daysSince    = (int)$customer['days_since_claim'];
    $customerName = $customer['first_name'] . ' ' . $customer['last_name'];
    
    // Feltöltötte az ID-t?
    if (!empty($customer['id_doc_path'])) {
        $pdo->prepare("UPDATE customers SET remarketing_active = 0, remarketing_stopped_at = NOW(), remarketing_stopped_reason = 'ID uploaded' WHERE id = ?")->execute([$customerId]);
        $log("  STOP [{$customerId}] {$customerName} — ID uploaded");
        $stoppedCount++;
        continue;
    }
    
    // Melyik step-eket kapta már meg
    $logStmt = $pdo->prepare("SELECT step FROM remarketing_logs WHERE customer_id = ? AND send_ok = 1");
    $logStmt->execute([$customerId]);
    $sentSteps = $logStmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Ha mind elment → STOP
    if (count($sentSteps) >= count(REMARKETING_SCHEDULE)) {
        $pdo->prepare("UPDATE customers SET remarketing_active = 0, remarketing_stopped_at = NOW(), remarketing_stopped_reason = 'All 5 emails sent' WHERE id = ?")->execute([$customerId]);
        $log("  STOP [{$customerId}] {$customerName} — All emails sent");
        $stoppedCount++;
        continue;
    }
    
    // Végigmegyünk az ütemezésen
    foreach (REMARKETING_SCHEDULE as $step => $config) {
        if (in_array($step, $sentSteps)) continue;
        if ($daysSince < $config['days']) continue;
        
        $log("  SEND [{$customerId}] {$customerName} — Step {$step} (Day {$config['days']}, elapsed: {$daysSince} days)");
        
        $result = sendRemarketingEmail($pdo, $customer, $step, $config, 'easyjet');
        
        // Log DB-be
        $pdo->prepare("INSERT INTO remarketing_logs (customer_id, step, day_offset, template_file, sent_at, send_ok, error_message, source) VALUES (?, ?, ?, ?, NOW(), ?, ?, 'customers')")
            ->execute([$customerId, $step, $config['days'], $config['template'], $result['ok'] ? 1 : 0, $result['ok'] ? null : $result['message']]);
        
        if ($result['ok']) {
            $sentCount++;
            $log("    OK: " . $result['message']);
        } else {
            $errorCount++;
            $log("    ERROR: " . $result['message']);
        }
    }
}

// =====================================================================
// PART 2: Wizz Air — wz_passengers tábla
// =====================================================================
$log('--- Wizz Air (wz_passengers table) ---');

$wzStmt = $pdo->query("
    SELECT p.*, 
           b.pnr, b.flight_number, b.flight_date, b.origin, b.origin_iata,
           b.destination, b.destination_iata, b.distance_km AS bk_distance_km, b.reason AS bk_reason,
           a.email AS acc_email, a.holder_name,
           DATEDIFF(NOW(), p.claim_mail_sent_at) AS days_since_claim
    FROM wz_passengers p
    JOIN wz_bookings b ON p.booking_id = b.id
    JOIN wz_accounts a ON p.account_id = a.id
    WHERE p.remarketing_active = 1
      AND p.claim_mail_sent_at IS NOT NULL
      AND p.is_holder = 1
    ORDER BY p.claim_mail_sent_at ASC
");
$wzPassengers = $wzStmt->fetchAll();
$log('Active Wizz Air remarketing passengers: ' . count($wzPassengers));

foreach ($wzPassengers as $pax) {
    $paxId      = $pax['id'];
    $daysSince  = (int)$pax['days_since_claim'];
    $paxName    = $pax['first_name'] . ' ' . $pax['last_name'];
    
    // Feltöltötte az ID-t?
    if (!empty($pax['id_doc_path'])) {
        $pdo->prepare("UPDATE wz_passengers SET remarketing_active = 0, remarketing_stopped_at = NOW(), remarketing_stopped_reason = 'ID uploaded' WHERE id = ?")->execute([$paxId]);
        $log("  STOP [WZ-{$paxId}] {$paxName} — ID uploaded");
        $stoppedCount++;
        continue;
    }
    
    // Melyik step-eket kapta már meg
    // Wizz Air remarketing logs — filter by source to avoid ID collisions with customers table
    $logStmt = $pdo->prepare("SELECT step FROM remarketing_logs WHERE customer_id = ? AND send_ok = 1 AND source = 'wz_passengers'");
    $logStmt->execute([$paxId]);
    $sentSteps = $logStmt->fetchAll(PDO::FETCH_COLUMN);
    
    // Ha mind elment → STOP
    if (count($sentSteps) >= count(REMARKETING_SCHEDULE_WZ)) {
        $pdo->prepare("UPDATE wz_passengers SET remarketing_active = 0, remarketing_stopped_at = NOW(), remarketing_stopped_reason = 'All 5 emails sent' WHERE id = ?")->execute([$paxId]);
        $log("  STOP [WZ-{$paxId}] {$paxName} — All emails sent");
        $stoppedCount++;
        continue;
    }
    
    // Build fake customer array for mailer compatibility
    $fakeCustomer = [
        'id'            => $paxId,
        'first_name'    => $pax['first_name'] ?: $pax['passenger_name'],
        'last_name'     => $pax['last_name'] ?? '',
        'email'         => $pax['email'] ?: $pax['acc_email'],
        'booking_ref'   => $pax['pnr'],
        'flight_number' => $pax['flight_number'],
        'flight_date'   => $pax['flight_date'],
        'departure'     => $pax['origin'],
        'arrival'       => $pax['destination'],
        'airline'       => 'Wizz Air',
        'distance_km'   => $pax['bk_distance_km'],
        'reason'        => $pax['bk_reason'],
        'customer_id'   => 'WZ-' . $paxId,
        'is_main'       => $pax['is_holder'],
        'id_doc_path'   => $pax['id_doc_path'] ?? null,
    ];
    
    // Determine which schedule to use — try WZ templates first, fall back to standard
    $schedule = REMARKETING_SCHEDULE_WZ;
    
    foreach ($schedule as $step => $config) {
        if (in_array($step, $sentSteps)) continue;
        if ($daysSince < $config['days']) continue;
        
        $log("  SEND [WZ-{$paxId}] {$paxName} — Step {$step} (Day {$config['days']}, elapsed: {$daysSince} days)");
        
        $result = sendRemarketingEmail($pdo, $fakeCustomer, $step, $config, 'wizzair');
        
        // Log DB-be
        $pdo->prepare("INSERT INTO remarketing_logs (customer_id, step, day_offset, template_file, sent_at, send_ok, error_message, source) VALUES (?, ?, ?, ?, NOW(), ?, ?, 'wz_passengers')")
            ->execute([$paxId, $step, $config['days'], $config['template'], $result['ok'] ? 1 : 0, $result['ok'] ? null : $result['message']]);
        
        if ($result['ok']) {
            $sentCount++;
            $log("    OK: " . $result['message']);
        } else {
            $errorCount++;
            $log("    ERROR: " . $result['message']);
        }
    }
}

$elapsed = round(microtime(true) - $startTime, 2);
$log("=== Remarketing cron DONE === Sent: {$sentCount}, Stopped: {$stoppedCount}, Errors: {$errorCount}, Time: {$elapsed}s");


// ===================================================================
// SEGÉDFÜGGVÉNY — közös küldő mindkét airline-hoz
// ===================================================================
function sendRemarketingEmail($pdo, $customer, $step, $config, $airline = 'easyjet') {
    // Email cím
    $email = $customer['email'];
    if (!$email && !$customer['is_main']) {
        if ($airline === 'wizzair') {
            // For Wizz Air, try account email
            // (already set in fakeCustomer from acc_email)
        } else {
            $mainStmt = $pdo->prepare("SELECT email FROM customers WHERE booking_ref = ? AND is_main = 1 LIMIT 1");
            $mainStmt->execute([$customer['booking_ref']]);
            $mainRow = $mainStmt->fetch();
            if ($mainRow) $email = $mainRow['email'];
        }
    }
    if (!$email) {
        return ['ok' => false, 'message' => 'No email: ' . $customer['first_name'] . ' ' . $customer['last_name']];
    }
    
    // Utasok (claim link-hez)
    if ($airline === 'wizzair') {
        // Get passengers from wz_passengers via booking
        $bkStmt = $pdo->prepare("SELECT id FROM wz_bookings WHERE pnr = ? LIMIT 1");
        $bkStmt->execute([$customer['booking_ref']]);
        $bk = $bkStmt->fetch();
        if ($bk) {
            $paxStmt = $pdo->prepare("SELECT first_name, last_name, passenger_name FROM wz_passengers WHERE booking_id = ? ORDER BY is_holder DESC, id ASC");
            $paxStmt->execute([$bk['id']]);
            $allPax = array_map(function($p) {
                return [
                    'first_name' => $p['first_name'] ?: explode(' ', $p['passenger_name'])[0] ?? '',
                    'last_name'  => $p['last_name'] ?: implode(' ', array_slice(explode(' ', $p['passenger_name']), 1))
                ];
            }, $paxStmt->fetchAll());
        } else {
            $allPax = [['first_name' => $customer['first_name'], 'last_name' => $customer['last_name']]];
        }
    } else {
        $paxStmt = $pdo->prepare("SELECT first_name, last_name FROM customers WHERE booking_ref = ? ORDER BY is_main DESC, id ASC");
        $paxStmt->execute([$customer['booking_ref']]);
        $allPax = $paxStmt->fetchAll();
    }
    
    // Build claim link based on airline
    if ($airline === 'wizzair') {
        // Use the WZ claim form URL
        $wzClaimFormUrl = 'https://eu261compensation.com/wizzair-claim-funnel.html';
        $claimLink = buildRemarketingClaimLink($customer, $allPax, $wzClaimFormUrl);
    } else {
        $claimLink = buildClaimLink($customer, $allPax);
    }
    
    // Template betöltés — try WZ template first, then fallback to standard
    $templatePath = __DIR__ . '/' . $config['template'];
    
    // If WZ template doesn't exist, fall back to standard template
    if (!file_exists($templatePath) && $airline === 'wizzair') {
        $fallbackTemplate = str_replace('remarketing-wz-', 'remarketing-', $config['template']);
        $templatePath = __DIR__ . '/' . $fallbackTemplate;
    }
    
    if (!file_exists($templatePath)) {
        return ['ok' => false, 'message' => 'Template not found: ' . $config['template']];
    }
    
    $htmlBody = file_get_contents($templatePath);
    $htmlBody = replacePlaceholders($htmlBody, $customer, $claimLink, $allPax);
    $htmlBody = str_replace(['{{STEP}}', '{{DAYS_SINCE}}'], [$step, $config['days']], $htmlBody);
    
    // Subject
    $subjects = [
        1 => 'Quick reminder: Upload your ID — ' . ($customer['flight_number'] ?? ''),
        2 => 'Reminder: Complete your claim — ' . ($customer['flight_number'] ?? ''),
        3 => 'Don\'t miss out — your compensation is waiting',
        4 => 'Still time to claim your flight compensation',
        5 => 'Final reminder — claim your €600 compensation',
    ];
    $subject = $subjects[$step] ?? 'Reminder: Complete Your Claim';
    
    // Küldés
    $toName = $customer['first_name'] . ' ' . $customer['last_name'];
    $wzFrom = ($airline === 'wizzair') ? 'support@support.eu261compensation.com' : null;
    $wzName = ($airline === 'wizzair') ? 'SkyClaim — Wizz Air' : null;
    if (MAIL_METHOD === 'brevo') {
        return sendViaBrevo($email, $toName, $subject, $htmlBody);
    } elseif (MAIL_METHOD === 'resend') {
        return sendViaResend($email, $toName, $subject, $htmlBody, $wzFrom, $wzName);
    } else {
        return sendViaPhpMail($email, $toName, $subject, $htmlBody);
    }
}


/**
 * Build claim link for remarketing — supports custom base URL
 */
function buildRemarketingClaimLink($customer, $allPax, $baseUrl) {
    $depIata = ''; $arrIata = '';
    $depCity = $customer['departure']; $arrCity = $customer['arrival'];
    
    if (preg_match('/\(([A-Z]{3})\)/', $customer['departure'], $m)) {
        $depIata = $m[1];
        $depCity = trim(preg_replace('/\s*\([A-Z]{3}\)\s*/', '', $customer['departure']));
    }
    if (preg_match('/\(([A-Z]{3})\)/', $customer['arrival'], $m)) {
        $arrIata = $m[1];
        $arrCity = trim(preg_replace('/\s*\([A-Z]{3}\)\s*/', '', $customer['arrival']));
    }
    
    $paxNames = [];
    if (!empty($allPax)) {
        foreach ($allPax as $p) {
            $paxNames[] = str_replace(' ', '_', $p['first_name']) . '_' . str_replace(' ', '_', $p['last_name']);
        }
    } else {
        $paxNames[] = str_replace(' ', '_', $customer['first_name']) . '_' . str_replace(' ', '_', $customer['last_name']);
    }
    
    $reason = $customer['reason'] ?? '';
    if (is_numeric($reason)) $reason = 'Delayed (' . $reason . ' min)';
    elseif (strtolower($reason) === 'cancelled' || strtolower($reason) === 'canceled') $reason = 'Cancelled';
    
    return $baseUrl . '?' . http_build_query([
        'booking' => $customer['booking_ref'],
        'flight'  => $customer['flight_number'],
        'date'    => $customer['flight_date'],
        'from'    => $depIata,
        'fromCity'=> $depCity,
        'to'      => $arrIata,
        'toCity'  => $arrCity,
        'reason'  => $reason,
        'pax'     => implode(',', $paxNames),
    ]);
}