<?php
/**
 * mailer.php — SkyClaim Email Sender
 * 
 * Három küldési mód:
 *   'php_mail' — a szerver saját mail() függvényével küld (cPanel/SMTP)
 *   'brevo'    — Brevo (Sendinblue) API v3-mal küld
 *   'resend'   — Resend API-val küld
 * 
 * VÁLTÁS: Csak a MAIL_METHOD konstanst írd át.
 */

// ===== KÜLDÉSI MÓD — EZT VÁLTSD =====
define('MAIL_METHOD', 'resend');  // 'php_mail' | 'brevo' | 'resend'

// ===== KÖZÖS BEÁLLÍTÁSOK =====
define('MAIL_FROM_EMAIL', 'easyjet@support.eu261compensation.com');
define('MAIL_FROM_NAME', 'SkyClaim');
define('MAIL_REPLY_TO', 'support@eu261compensation.com');
define('CLAIM_FORM_BASE_URL', 'https://eu261compensation.com/easyjet-claim-funnel.html');

// ===== BREVO BEÁLLÍTÁSOK (csak ha MAIL_METHOD = 'brevo') =====
define('BREVO_API_KEY', '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');

// ===== RESEND BEÁLLÍTÁSOK (csak ha MAIL_METHOD = 'resend') =====
define('RESEND_API_KEY', 're_VidV7kJA_AhchQu4fwvsg66vgrTyCH7kQ');


// =====================================================================
// KÜLDŐ FUNKCIÓK — NE MÓDOSÍTSD EZEKET
// =====================================================================

/**
 * Sends an email notification to a customer.
 */
function sendCustomerEmail($pdo, $customerId, $templateSlug) {
    $stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ?");
    $stmt->execute([$customerId]);
    $customer = $stmt->fetch();
    
    if (!$customer) {
        return ['ok' => false, 'message' => 'Customer not found'];
    }
    
    // Get email — fall back to main passenger's email
    $email = $customer['email'];
    if (!$email && !$customer['is_main']) {
        $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 address for customer ' . $customer['first_name'] . ' ' . $customer['last_name']];
    }
    
    // Get all passengers in this booking
    $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();
    
    $claimLink = buildClaimLink($customer, $allPax);
    
    // Get mail template from DB
    $tplStmt = $pdo->prepare("SELECT * FROM mail_templates WHERE slug = ?");
    $tplStmt->execute([$templateSlug]);
    $template = $tplStmt->fetch();
    
    // Build email content
    if ($templateSlug === 'claim_submit') {
        // Personalized HTML notification email
        $depIata = ''; $arrIata = '';
        if (preg_match('/\(([A-Z]{3})\)/', $customer['departure'], $m)) $depIata = $m[1];
        if (preg_match('/\(([A-Z]{3})\)/', $customer['arrival'], $m)) $arrIata = $m[1];
        $routeStr = ($depIata && $arrIata) ? " {$depIata}-{$arrIata}" : '';
        $airlineName = $customer['airline'] ?? 'easyJet';
        $subject = "Claim up to €600 for your {$airlineName} flight{$routeStr}";
        $htmlBody = buildNotificationEmail($customer, $claimLink, $allPax);
    } else {
        if (!$template) {
            return ['ok' => false, 'message' => 'Template not found: ' . $templateSlug];
        }
        $subject = replacePlaceholders($template['subject'], $customer, $claimLink, $allPax);
        $textBody = replacePlaceholders($template['body'], $customer, $claimLink, $allPax);
        $htmlBody = buildSimpleEmail($textBody, $customer);
    }
    
    // Send via configured method
    $toName = $customer['first_name'] . ' ' . $customer['last_name'];
    
    if (MAIL_METHOD === 'brevo') {
        return sendViaBrevo($email, $toName, $subject, $htmlBody);
    } elseif (MAIL_METHOD === 'resend') {
        return sendViaResend($email, $toName, $subject, $htmlBody);
    } else {
        return sendViaPhpMail($email, $toName, $subject, $htmlBody);
    }
}

// =====================================================================
// SEND VIA PHP mail() — szerver saját email küldés
// =====================================================================
function sendViaPhpMail($toEmail, $toName, $subject, $htmlContent) {
    $fromEmail = MAIL_FROM_EMAIL;
    $fromName  = MAIL_FROM_NAME;
    
    // Generate boundary for MIME
    $boundary = md5(time() . rand());
    
    $headers  = "From: {$fromName} <{$fromEmail}>\r\n";
    $headers .= "Reply-To: {$fromEmail}\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: multipart/alternative; boundary=\"{$boundary}\"\r\n";
    $headers .= "X-Mailer: SkyClaim/1.0\r\n";
    
    // Plain text fallback
    $textContent = strip_tags(str_replace(['<br>', '<br/>', '<br />', '</p>', '</div>', '</td>'], "\n", $htmlContent));
    $textContent = html_entity_decode($textContent, ENT_QUOTES, 'UTF-8');
    $textContent = preg_replace('/\n{3,}/', "\n\n", trim($textContent));
    
    // Build MIME body
    $body  = "--{$boundary}\r\n";
    $body .= "Content-Type: text/plain; charset=UTF-8\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($textContent)) . "\r\n";
    $body .= "--{$boundary}\r\n";
    $body .= "Content-Type: text/html; charset=UTF-8\r\n";
    $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
    $body .= chunk_split(base64_encode($htmlContent)) . "\r\n";
    $body .= "--{$boundary}--\r\n";
    
    // Encode subject for UTF-8
    $encodedSubject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
    
    // Format To header
    $to = $toName ? "{$toName} <{$toEmail}>" : $toEmail;
    
    $result = @mail($to, $encodedSubject, $body, $headers);
    
    if ($result) {
        return ['ok' => true, 'message' => 'Email sent to ' . $toEmail . ' (via PHP mail)'];
    } else {
        $lastError = error_get_last();
        $errorMsg = $lastError ? $lastError['message'] : 'Unknown error';
        return ['ok' => false, 'message' => 'PHP mail() failed for ' . $toEmail . ': ' . $errorMsg];
    }
}

// =====================================================================
// SEND VIA BREVO API
// =====================================================================
function sendViaBrevo($toEmail, $toName, $subject, $htmlContent) {
    $apiKey = BREVO_API_KEY;
    
    if (empty($apiKey) || $apiKey === 'YOUR_BREVO_API_KEY') {
        return ['ok' => false, 'message' => 'Brevo API key not configured.'];
    }
    
    $payload = [
        'sender' => [
            'name'  => MAIL_FROM_NAME,
            'email' => MAIL_FROM_EMAIL,
        ],
        'to' => [[
            'email' => $toEmail,
            'name'  => $toName,
        ]],
        'subject'     => $subject,
        'htmlContent' => $htmlContent,
    ];
    
    $ch = curl_init('https://api.brevo.com/v3/smtp/email');
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => [
            'api-key: ' . $apiKey,
            'Content-Type: application/json',
            'Accept: application/json',
        ],
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    if ($curlError) {
        return ['ok' => false, 'message' => 'cURL error: ' . $curlError];
    }
    
    $body = json_decode($response, true);
    
    if ($httpCode === 201 || $httpCode === 200) {
        $msgId = $body['messageId'] ?? '';
        return ['ok' => true, 'message' => 'Email sent to ' . $toEmail . ' (via Brevo' . ($msgId ? ', ID: ' . $msgId : '') . ')'];
    }
    
    $errorMsg = 'Brevo error (HTTP ' . $httpCode . ')';
    if (isset($body['message'])) $errorMsg .= ': ' . $body['message'];
    if (isset($body['code'])) $errorMsg .= ' [' . $body['code'] . ']';
    
    return ['ok' => false, 'message' => $errorMsg];
}

// =====================================================================
// SEND VIA RESEND API
// =====================================================================
function sendViaResend($toEmail, $toName, $subject, $htmlContent, $fromEmail = null, $fromName = null, $replyTo = null) {
    $apiKey = RESEND_API_KEY;
    
    if (empty($apiKey) || $apiKey === 'YOUR_RESEND_API_KEY') {
        return ['ok' => false, 'message' => 'Resend API key not configured.'];
    }
    
    $senderEmail = $fromEmail ?: MAIL_FROM_EMAIL;
    $senderName  = $fromName  ?: MAIL_FROM_NAME;
    
    $payload = [
        'from' => $senderName . ' <' . $senderEmail . '>',
        'to'   => [$toEmail],
        'subject'     => $subject,
        'html' => $htmlContent,
        'reply_to' => $replyTo ?: MAIL_REPLY_TO,
    ];
    
    $ch = curl_init('https://api.resend.com/emails');
    curl_setopt_array($ch, [
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json',
        ],
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);
    
    if ($curlError) {
        return ['ok' => false, 'message' => 'cURL error: ' . $curlError];
    }
    
    $body = json_decode($response, true);
    
    // Resend returns 200 on success with { id: "..." }
    if ($httpCode === 200 && isset($body['id'])) {
        return ['ok' => true, 'message' => 'Email sent to ' . $toEmail . ' (via Resend, ID: ' . $body['id'] . ')'];
    }
    
    $errorMsg = 'Resend error (HTTP ' . $httpCode . ')';
    if (isset($body['message'])) $errorMsg .= ': ' . $body['message'];
    if (isset($body['name'])) $errorMsg .= ' [' . $body['name'] . ']';
    
    return ['ok' => false, 'message' => $errorMsg];
}

// =====================================================================
// HELPER FUNCTIONS
// =====================================================================

function buildClaimLink($customer, $allPax = []) {
    $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 CLAIM_FORM_BASE_URL . '?' . 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),
    ]);
}

function replacePlaceholders($text, $customer, $claimLink, $allPax = []) {
    $name = $customer['first_name'] . ' ' . $customer['last_name'];
    
    // Build passengers list
    $passengerNames = [];
    if (!empty($allPax)) {
        foreach ($allPax as $p) {
            $passengerNames[] = $p['first_name'] . ' ' . $p['last_name'];
        }
    } else {
        $passengerNames[] = $name;
    }
    $passengersText = implode(', ', $passengerNames);
    $passengersHtml = implode('<br>', array_map('htmlspecialchars', $passengerNames));
    
    $reason = $customer['reason'] ?? '';
    $disruptionStatus = 'Disrupted';
    $disruptionIcon = '&#9888;';
    if (is_numeric(trim($reason))) {
        $disruptionStatus = 'Delayed (' . trim($reason) . ' min)';
        $disruptionIcon = '&#128337;';
    } elseif (stripos($reason, 'cancel') !== false) {
        $disruptionStatus = 'Cancelled';
        $disruptionIcon = '&#10060;';
    } elseif ($reason) {
        $disruptionStatus = $reason;
    }
    
    $flightNum = $customer['flight_number'] ?? '';
    $flightNumDisplay = preg_replace('/^([A-Z]{2,3})(\d+)$/', '$1 $2', strtoupper($flightNum));
    
    $depIataCode = ''; $arrIataCode = '';
    if (preg_match('/\(([A-Z]{3})\)/', $customer['departure'], $m)) $depIataCode = $m[1];
    if (preg_match('/\(([A-Z]{3})\)/', $customer['arrival'], $m)) $arrIataCode = $m[1];
    
    return str_replace(
        ['{{NAME}}','{{FIRST_NAME}}','{{LAST_NAME}}','{{PASSENGERS}}','{{PASSENGERS_HTML}}','{{FLIGHT}}','{{FLIGHT_NUMBER}}','{{DATE}}','{{DEP}}','{{ARR}}','{{DEP_IATA}}','{{ARR_IATA}}','{{BOOKING}}','{{CLAIM_LINK}}','{{CUSTOMER_ID}}','{{REASON}}','{{DISRUPTION_STATUS}}','{{DISRUPTION_ICON}}','{{BOOKING_REF}}','{{FLIGHT_DATE}}','{{DEPARTURE}}','{{ARRIVAL}}'],
        [$name,$customer['first_name'],$customer['last_name'],$passengersText,$passengersHtml,$customer['flight_number'],$flightNumDisplay,formatEmailDate($customer['flight_date']),$customer['departure'],$customer['arrival'],$depIataCode,$arrIataCode,$customer['booking_ref'],$claimLink,$customer['customer_id'],$reason,$disruptionStatus,$disruptionIcon,$customer['booking_ref'],formatEmailDate($customer['flight_date']),$customer['departure'],$customer['arrival']],
        $text
    );
}

function formatEmailDate($date) {
    if (!$date) return '';
    $ts = strtotime($date);
    return $ts ? date('j F Y', $ts) : $date;
}

function buildNotificationEmail($customer, $claimLink, $allPax = [], $preview = false) {
    $templatePath = __DIR__ . '/email-notification.html';
    $customerId = intval($customer['id'] ?? 0);
    
    if (file_exists($templatePath)) {
        $html = replacePlaceholders(file_get_contents($templatePath), $customer, $claimLink, $allPax);
    } else {
        $text = "Dear " . $customer['first_name'] . " " . $customer['last_name'] . ",\n\nYour flight " . $customer['flight_number'] . " on " . formatEmailDate($customer['flight_date']) . " was disrupted.\n\nSubmit your claim: " . $claimLink . "\n\nBooking: " . $customer['booking_ref'] . "\n\nKind regards,\nSkyClaim Team";
        $html = buildSimpleEmail($text, $customer);
    }
    
    // Only add tracking for real sends, not previews
    if ($customerId && !$preview) {
        $trackBase = 'https://eu261compensation.com/track.php';
        
        // 1) Replace claim link with click-tracked redirect (src=ej for easyJet)
        $trackedLink = $trackBase . '?t=c&id=' . $customerId . '&src=ej&url=' . urlencode($claimLink);
        // Try both raw & and HTML-encoded &amp; versions (email clients may encode)
        $claimLinkHtmlEncoded = str_replace('&', '&amp;', $claimLink);
        $html = str_replace($claimLink, $trackedLink, $html);
        $html = str_replace($claimLinkHtmlEncoded, $trackedLink, $html);
        
        // 2) Add open tracking pixel before </body>
        $pixel = '<img src="' . $trackBase . '?t=o&id=' . $customerId . '&src=ej" width="1" height="1" style="display:none;width:1px;height:1px;border:0" alt="">';
        if (stripos($html, '</body>') !== false) {
            $html = str_ireplace('</body>', $pixel . '</body>', $html);
        } else {
            $html .= $pixel;
        }
    }
    
    return $html;
}

function buildSimpleEmail($textBody, $customer) {
    $bodyHtml = nl2br(htmlspecialchars($textBody));
    return <<<HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="margin:0;padding:0;background-color:#F8F9FB;font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#F8F9FB;">
<tr><td align="center" style="padding:40px 16px;">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;">
  <tr><td style="padding:0 0 24px;"><span style="font-size:22px;font-weight:800;color:#1B2A4A;">Sky<span style="color:#FF6B35;">Claim</span></span></td></tr>
  <tr><td><table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#FFFFFF;border:1px solid #E2E5EA;border-radius:16px;overflow:hidden;"><tr><td style="padding:32px;font-family:'Helvetica Neue',Helvetica,Arial,sans-serif;font-size:14px;color:#3D4552;line-height:1.7;">{$bodyHtml}</td></tr></table></td></tr>
  <tr><td style="padding:24px 0;text-align:center;"><p style="margin:0;font-size:12px;color:#C8CDD5;"><strong style="color:#9BA3B0;">SkyClaim</strong></p></td></tr>
</table>
</td></tr></table>
</body></html>
HTML;
}