<?php
/**
 * sendgrid_mailer.php — SendGrid Email Sender for SkyClaim
 * 
 * Ez a modul küldi ki az email notification-öket az ügyfeleknek.
 * A dashboard.php include-olja és a send_mail / bulk_send_mail action-ök hívják.
 * 
 * BEÁLLÍTÁS:
 * 1. SendGrid API key: írd be a SENDGRID_API_KEY konstansba
 * 2. Feladó email + név: írd be a SENDGRID_FROM_EMAIL és SENDGRID_FROM_NAME konstansokba
 * 3. Claim form URL: írd be a CLAIM_FORM_BASE_URL konstansba (a szervered domain-je)
 */

// ===== BEÁLLÍTÁSOK — EZEKET ÍRD ÁT! =====
define('SENDGRID_API_KEY', 'SG.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
define('SENDGRID_FROM_EMAIL', 'easyjet@eu261compensation.com');
define('SENDGRID_FROM_NAME', 'EasyJet Compensation Support');
define('CLAIM_FORM_BASE_URL', 'https://eu261compensation.com/easyjet-claim-funnel.html');

/**
 * Sends an email notification to a customer using SendGrid API.
 * 
 * @param PDO $pdo Database connection
 * @param int $customerId The customer's DB id
 * @param string $templateSlug Which mail template to use (e.g. 'claim_submit', 'hibas_id', 'kis_turelmet')
 * @return array ['ok' => bool, 'message' => string]
 */
function sendCustomerEmail($pdo, $customerId, $templateSlug) {
    // Get customer data
    $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 - check main passenger if sub-passenger has no 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 (for the claim link)
    $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 the claim form URL with all passenger names
    $claimLink = buildClaimLink($customer, $allPax);
    
    // Get the mail template from DB
    $tplStmt = $pdo->prepare("SELECT * FROM mail_templates WHERE slug = ?");
    $tplStmt->execute([$templateSlug]);
    $template = $tplStmt->fetch();
    
    // Determine which email to send
    if ($templateSlug === 'claim_submit') {
        // Use the beautiful HTML notification email from file
        $subject = 'Flight Disruption Notification — Booking ' . $customer['booking_ref'];
        $htmlBody = buildNotificationEmail($customer, $claimLink);
    } else {
        // Simple text email — no claim link, no parameterization
        if (!$template) {
            return ['ok' => false, 'message' => 'Template not found: ' . $templateSlug];
        }
        $subject = replacePlaceholders($template['subject'], $customer, $claimLink);
        $textBody = replacePlaceholders($template['body'], $customer, $claimLink);
        $htmlBody = buildSimpleEmail($textBody, $customer);
    }
    
    // Send via SendGrid API
    $result = sendViaSendGrid($email, $customer['first_name'] . ' ' . $customer['last_name'], $subject, $htmlBody);
    
    return $result;
}

/**
 * Build the claim form URL for a customer.
 */
function buildClaimLink($customer, $allPax = []) {
    // Extract IATA codes from departure/arrival strings like "Budapest (BUD)"
    $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']));
    }
    
    // Build pax string: "John_Doe,Jane_Doe"
    $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']);
    }
    
    // Format reason
    $reason = $customer['reason'] ?? '';
    if (is_numeric($reason)) {
        $reason = 'Delayed (' . $reason . ' min)';
    } elseif (strtolower($reason) === 'cancelled' || strtolower($reason) === 'canceled') {
        $reason = 'Cancelled';
    }
    
    $params = [
        '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),
    ];
    
    return CLAIM_FORM_BASE_URL . '?' . http_build_query($params);
}

/**
 * Replace {{PLACEHOLDERS}} in template text.
 */
function replacePlaceholders($text, $customer, $claimLink) {
    $name = $customer['first_name'] . ' ' . $customer['last_name'];
    
    // Format reason for display
    $reason = $customer['reason'] ?? '';
    $disruptionStatus = 'Disrupted';
    $disruptionIcon = '&#9888;';
    if (is_numeric(trim($reason))) {
        $disruptionStatus = 'Delayed (' . trim($reason) . ' min)';
        $disruptionIcon = '&#128337;'; // clock
    } elseif (stripos($reason, 'cancel') !== false) {
        $disruptionStatus = 'Cancelled';
        $disruptionIcon = '&#10060;'; // cross
    } elseif ($reason) {
        $disruptionStatus = $reason;
    }
    
    // Format flight number with space (EZY1234 → EZY 1234)
    $flightNum = $customer['flight_number'] ?? '';
    $flightNumDisplay = preg_replace('/^([A-Z]{2,3})(\d+)$/', '$1 $2', strtoupper($flightNum));
    
    $replacements = [
        '{{NAME}}'        => $name,
        '{{FIRST_NAME}}'  => $customer['first_name'],
        '{{LAST_NAME}}'   => $customer['last_name'],
        '{{FLIGHT}}'      => $customer['flight_number'],
        '{{FLIGHT_NUMBER}}' => $flightNumDisplay,
        '{{DATE}}'        => formatEmailDate($customer['flight_date']),
        '{{DEP}}'         => $customer['departure'],
        '{{ARR}}'         => $customer['arrival'],
        '{{BOOKING}}'     => $customer['booking_ref'],
        '{{CLAIM_LINK}}'  => $claimLink,
        '{{CUSTOMER_ID}}' => $customer['customer_id'],
        '{{REASON}}'      => $reason,
        '{{DISRUPTION_STATUS}}' => $disruptionStatus,
        '{{DISRUPTION_ICON}}'   => $disruptionIcon,
        // Also support the email-notification.html style placeholders
        '{{BOOKING_REF}}' => $customer['booking_ref'],
        '{{FLIGHT_DATE}}' => formatEmailDate($customer['flight_date']),
        '{{DEPARTURE}}'   => $customer['departure'],
        '{{ARRIVAL}}'     => $customer['arrival'],
    ];
    
    return str_replace(array_keys($replacements), array_values($replacements), $text);
}

/**
 * Format date for email display: "15 June 2025"
 */
function formatEmailDate($date) {
    if (!$date) return '';
    $ts = strtotime($date);
    if (!$ts) return $date;
    return date('j F Y', $ts);
}

/**
 * Build the full HTML notification email from the designed template.
 * This is the beautiful HTML email with flight info, compensation tiers, etc.
 */
function buildNotificationEmail($customer, $claimLink) {
    // Read the email template file
    $templatePath = __DIR__ . '/email-notification.html';
    
    if (file_exists($templatePath)) {
        $html = file_get_contents($templatePath);
        // Use the central replacePlaceholders function for all substitutions
        $html = replacePlaceholders($html, $customer, $claimLink);
        return $html;
    }
    
    // Fallback: simple notification if file not found
    $subject = 'Flight Disruption Notification';
    $text = "Dear Valued Customer,\n\nYour flight " . $customer['flight_number'] . " on " . formatEmailDate($customer['flight_date']) . " from " . $customer['departure'] . " to " . $customer['arrival'] . " was disrupted.\n\nPlease submit your claim here: " . $claimLink . "\n\nBooking Reference: " . $customer['booking_ref'] . "\n\nKind regards,\nSkyClaim Team";
    return buildSimpleEmail($text, $customer);
}

/**
 * Wrap a plain text template in simple styled 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;">{$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;
}

/**
 * Send email via SendGrid API (v3).
 * Uses cURL — no composer/vendor dependencies needed.
 */
function sendViaSendGrid($toEmail, $toName, $subject, $htmlContent) {
    $apiKey = SENDGRID_API_KEY;
    
    if (strpos($apiKey, 'XXXXXXX') !== false) {
        return ['ok' => false, 'message' => 'SendGrid API key not configured. Edit sendgrid_mailer.php and set your API key.'];
    }
    
    $payload = [
        'personalizations' => [[
            'to' => [['email' => $toEmail, 'name' => $toName]],
            'subject' => $subject,
        ]],
        'from' => [
            'email' => SENDGRID_FROM_EMAIL,
            'name'  => SENDGRID_FROM_NAME,
        ],
        'content' => [[
            'type'  => 'text/html',
            'value' => $htmlContent,
        ]],
        'tracking_settings' => [
            'click_tracking' => ['enable' => true],
            'open_tracking'  => ['enable' => true],
        ],
    ];
    
    $ch = curl_init('https://api.sendgrid.com/v3/mail/send');
    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];
    }
    
    // SendGrid returns 202 on success
    if ($httpCode === 202 || $httpCode === 200) {
        return ['ok' => true, 'message' => 'Email sent to ' . $toEmail];
    }
    
    // Parse error
    $body = json_decode($response, true);
    $errorMsg = 'SendGrid error (HTTP ' . $httpCode . ')';
    if (isset($body['errors'][0]['message'])) {
        $errorMsg .= ': ' . $body['errors'][0]['message'];
    }
    
    return ['ok' => false, 'message' => $errorMsg];
}
