<?php
    require __DIR__ . '/config.php';
    require __DIR__ . '/vendor/smtp_mailer.php';
require __DIR__ . '/vendor/aws_ses_mailer.php';
    
    $conf = get_config();
    $pdo  = get_pdo();
    
    // Get campaign ID from CLI argument
    if (php_sapi_name() === 'cli') {
        // Running from command line (via exec)
        $campaign_id = intval($argv[1] ?? 0);
    } else {
        // Running via include or direct web access
        $campaign_id = $campaign_id ?? ($_GET['cid'] ?? 0); 
        $campaign_id = intval($campaign_id);
    }
    
    //  die($campaign_id);
    
    if (!$campaign_id) {
        echo "❌ Missing campaign ID\n";
        exit;
    }
    // $campaign_id = intval($argv[1] ?? 0);
   
    // if (!$campaign_id) {
    //     echo "Usage: php send_worker.php CAMPAIGN_ID\n";
    //     exit;
    // }
    
    // Fetch campaign with template
    $stmt = $pdo->prepare('
        SELECT c.*, t.html AS template_html
        FROM campaigns c
        LEFT JOIN templates t ON t.id = c.template_id
        WHERE c.id = ?
    ');
    $stmt->execute([$campaign_id]);
    $campaign = $stmt->fetch();
    
    if (!$campaign) {
        echo "Campaign not found\n";
        exit;
    }
    
    // Mark campaign as "sending"
    $pdo->prepare('UPDATE campaigns SET status = "sending" WHERE id = ?')
        ->execute([$campaign_id]);
    
    // Fetch contacts for this list
    $stmt = $pdo->prepare('
        SELECT lc.*
        FROM list_contacts lc
        WHERE lc.list_id = ?
          AND lc.unsubscribed = 0
          AND lc.bounced = 0
    ');
    $stmt->execute([$campaign['list_id']]);
    $contacts = $stmt->fetchAll();
    
    foreach ($contacts as $c) {
        $personal_html = $campaign['template_html'];
    
        // Personalize email
        $personal_html = str_replace('[[NAME]]', htmlspecialchars($c['name'] ?? ''), $personal_html);
    
        // Tracking pixel
        $track_url = $conf['base_url'] . '/public/track.php?c=' . $campaign_id . '&cid=' . $c['id'];
    
        // Unsubscribe link with token
        $unsubscribe_token = md5($c['id'] . ($conf['unsubscribe_secret'] ?? 'secret_key'));
        $unsubscribe_url = $conf['base_url'] . '/public/unsubscribe.php?cid=' . $c['id'] . '&token=' . $unsubscribe_token;
    
        // Append tracking + unsubscribe to body
        $personal_html .= '<img src="' . $track_url . '" width="1" height="1" style="display:none;" />';
        $personal_html .= '<p><a href="' . $unsubscribe_url . '">Unsubscribe</a></p>';
    
      // Send email using AWS SES SDK
        $ok = send_ses_mail(
            $conf,
            $c['email'],
            $c['name'],
            $campaign['subject'],
            $personal_html
        );

    
        // Log result
        $stmt = $pdo->prepare('
            INSERT INTO campaign_logs (campaign_id, contact_id, status)
            VALUES (?, ?, ?)
        ');
        $stmt->execute([$campaign_id, $c['id'], $ok ? 'sent' : 'failed']);
    }
    
    // Update campaign as complete
    $total = count($contacts);
    $pdo->prepare('
        UPDATE campaigns
        SET status = "sent", total = ?, sent = ?
        WHERE id = ?
    ')->execute([$total, $total, $campaign_id]);
    
    echo "Done. Sent: $total\n";
