<?php
/* ============================================================
   MARATHON PRAYER HUB RETREAT — Registration Handler
   Same structure as register.php (Recharge 4.0) but for the
   Marathon Prayer Hub Retreat event, 1st August 2026.
   ============================================================ */

$DEBUG_MODE = true;
if ($DEBUG_MODE) { error_reporting(E_ALL); ini_set('display_errors','1'); }

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success'=>false,'error'=>'Method not allowed']);
    exit;
}

require_once __DIR__ . '/ticket_generator_marathon.php';

$fpdfPath = __DIR__ . '/fpdf/fpdf.php';
if (!file_exists($fpdfPath)) {
    http_response_code(500);
    echo json_encode(['success'=>false,'error'=>'FPDF library not found. Upload the fpdf folder next to this file.']);
    exit;
}

/* ------------------------------------------------------------
   1. CONFIG — fill these in
   ------------------------------------------------------------ */
$BREVO_API_KEY    = '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';
$ORGANISER_EMAIL  = 'info@ministeraramide.com';
$ORGANISER_NAME   = 'Recharge Nation';
$SENDER_EMAIL     = 'info@ministeraramide.com';
$SENDER_NAME      = 'Recharge Nation';
$BREVO_LIST_ID    = 6; // Marathon Prayer Hub Brevo list
$CC_EMAILS        = [];
$BCC_EMAILS       = ['melistech2020@gmail.com'];

/* ------------------------------------------------------------
   2. READ & VALIDATE
   ------------------------------------------------------------ */
$raw  = file_get_contents('php://input');
$data = json_decode($raw, true);

$name  = trim($data['name']  ?? '');
$email = trim($data['email'] ?? '');
$phone = trim($data['phone'] ?? '');
$cars  = $data['cars']  ?? [];


if ($name==='') {
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'Name is required.']);
    exit;
}

if ($email==='') {
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'Email is required.']);
    exit;
}

if ($phone==='') {
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'Phone is required.']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'Invalid email address.']);
    exit;
}
$cleanedPhone = preg_replace('/[\s\-\(\)]/','',$phone);
$isValidIntlPhone = preg_match('/^\+\d{8,15}$/',$cleanedPhone);
if (!$isValidIntlPhone) {
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'Please provide a valid phone number with a country code.']);
    exit;
}

/* ------------------------------------------------------------
   3. TICKET LIMIT — max 3 per email/phone
   ------------------------------------------------------------ */
define('MAX_TICKETS_PER_EMAIL', 3);
$existingTicketCount = 0;
$formattedPhone = formatPhoneForBrevo($phone);

if ($BREVO_LIST_ID > 0) {
    $byEmail = getBrevoContact($BREVO_API_KEY, $email);
    if ($byEmail && isset($byEmail['attributes']['TICKET_COUNT'])) {
        $existingTicketCount = max($existingTicketCount, (int)$byEmail['attributes']['TICKET_COUNT']);
    }
    $byPhone = getBrevoContactByPhone($BREVO_API_KEY, $formattedPhone);
    if ($byPhone && isset($byPhone['attributes']['TICKET_COUNT'])) {
        $existingTicketCount = max($existingTicketCount, (int)$byPhone['attributes']['TICKET_COUNT']);
    }
}

if ($existingTicketCount >= MAX_TICKETS_PER_EMAIL) {
    http_response_code(400);
    echo json_encode(['success'=>false,'error'=>'This email or phone number has already registered the maximum of '.MAX_TICKETS_PER_EMAIL.' tickets. Please contact us if you need help.']);
    exit;
}

/* ------------------------------------------------------------
   4. GENERATE TICKET
   ------------------------------------------------------------ */
$ticketId    = 'MPH-'.strtoupper(substr(bin2hex(random_bytes(3)),0,4)).'-'.strtoupper(substr(bin2hex(random_bytes(3)),0,4));
$orderNumber = str_pad(random_int(1,99999999),8,'0',STR_PAD_LEFT);
$orderDate   = date('Y-m-d\TH:i:s');

/* ------------------------------------------------------------
   5. CAR TEXT
   ------------------------------------------------------------ */
$carsPlain = '';
foreach ($cars as $car) {
    $mk=$car['make_model']??''; $pl=$car['plate']??''; $co=$car['colour']??'';
    if ($mk!==''||$pl!==''||$co!=='') $carsPlain .= "- {$mk} | {$pl} | {$co}\n";
}
$carDetailsText = '';
if (!empty($cars)) {
    $carLines=[];
    foreach ($cars as $car) {
        $mk=$car['make_model']??''; $pl=$car['plate']??''; $co=$car['colour']??'';
        if ($mk!==''||$pl!==''||$co!=='') $carLines[]=trim("{$mk} | {$pl} | {$co}",' |');
    }
    $carDetailsText=implode('; ',$carLines);
}
$carsHtml='';
if (!empty($cars)) {
    $carsHtml='<div style="margin-top:16px;"><strong>Registered vehicle(s):</strong><ul style="margin:8px 0 0 18px; color:#444; font-size:13px;">';
    foreach ($cars as $car) {
        $mk=htmlspecialchars($car['make_model']??''); $pl=htmlspecialchars($car['plate']??''); $co=htmlspecialchars($car['colour']??'');
        $carsHtml.="<li>{$mk} — {$pl} ({$co})</li>";
    }
    $carsHtml.='</ul></div>';
}

/* ------------------------------------------------------------
   6. GENERATE PDF TICKET
   ------------------------------------------------------------ */
$nameParts = preg_split('/\s+/',trim($name),2);
$firstName = $nameParts[0]??'';
$lastName  = $nameParts[1]??'';

try {
    $ticketPdfContent = generateMarathonTicketPDF($name, $ticketId, $orderNumber, $orderDate);
    $ticketPdfBase64  = base64_encode($ticketPdfContent);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success'=>false,'error'=>'Failed to generate PDF ticket: '.$e->getMessage()]);
    exit;
}

/* ------------------------------------------------------------
   7. SEND TICKET EMAIL
   ------------------------------------------------------------ */
$firstName = explode(' ',trim($name))[0];
$ticketHtml = "
<div style='font-family:Arial,sans-serif; max-width:560px; margin:0 auto; color:#222;'>
  <p style='font-size:14px;'>Hi {$firstName},</p>
  <p style='font-size:14px;'>You're confirmed for the Marathon Prayer Hub Retreat! Here's your order summary.</p>
  <h2 style='font-size:20px; color:#222; margin-top:28px;'>Order Summary</h2>
  <p style='font-size:13px; color:#555;'>Order <span style='color:#C9A84C;'>#{$orderNumber}</span> &mdash; ".date('F j, Y')."</p>
  <p style='font-size:13px; color:#555; margin-top:16px;'>Free registration</p>
  <table style='width:100%; margin-top:18px; border-top:1px solid #eee; padding-top:14px;'>
    <tr>
      <td style='font-size:14px; color:#222;'>".htmlspecialchars($name)."</td>
      <td style='font-size:14px; color:#222; text-align:center;'><strong>1 &times; General Admission</strong></td>
      <td style='font-size:14px; color:#222; text-align:right;'>&pound;0.00</td>
    </tr>
  </table>
  <p style='font-size:13px; margin-top:20px;'><strong>Your PDF ticket is attached to this email.</strong> Bring it printed or on your phone.</p>
  {$carsHtml}
  <div style='margin-top:28px; padding-top:18px; border-top:1px solid #eee; font-size:12px; color:#888;'>
    <p>114–126 Westmoor Street, Charlton, London SE7 8NQ</p>
    <p>Saturday, 1st August 2026 &middot; 10:00 AM – 1:00 PM (UK Time)</p>
    <p style='margin-top:10px;'>Questions? Contact 07449157502</p>
    <p>Follow @aramidefadilepo and @rechargenation on Instagram.</p>
  </div>
</div>
";

$ticketEmailPayload = [
    'sender'      => ['name'=>$SENDER_NAME,'email'=>$SENDER_EMAIL],
    'to'          => [['email'=>$email,'name'=>$name]],
    'subject'     => 'Your ticket for Marathon Prayer Hub Retreat',
    'htmlContent' => $ticketHtml,
    'attachment'  => [['content'=>$ticketPdfBase64,'name'=>'MarathonPrayerHub-Ticket-'.$ticketId.'.pdf']],
];

try {
    $ticketResult = sendBrevoEmail($BREVO_API_KEY, $ticketEmailPayload);
    if ($ticketResult['code'] >= 400) {
        http_response_code(500);
        echo json_encode(['success'=>false,'error'=>'Brevo rejected the email request: '.$ticketResult['body']]);
        exit;
    }
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success'=>false,'error'=>'Failed to send ticket email: '.$e->getMessage()]);
    exit;
}

/* ------------------------------------------------------------
   8. SAVE TO BREVO
   ------------------------------------------------------------ */
if ($BREVO_LIST_ID > 0) {
    $contactPayload = [
        'email'      => $email,
        'attributes' => [
            'FIRSTNAME'    => $firstName,
            'LASTNAME'     => $lastName,
            'SMS'          => $formattedPhone,
            'CAR_DETAILS'  => $carDetailsText,
            'HAS_CAR'      => $carDetailsText!==''?'Yes':'No',
            'TICKET_COUNT' => $existingTicketCount+1,
        ],
        'listIds'       => [(int)$BREVO_LIST_ID],
        'updateEnabled' => true,
    ];
    $contactResult = addBrevoContact($BREVO_API_KEY, $contactPayload);

    $isDuplicatePhone = false;
    if ($contactResult['code'] >= 400) {
        $decodedError = json_decode($contactResult['body'],true);
        if (is_array($decodedError)&&($decodedError['code']??'')==='duplicate_parameter'&&in_array('SMS',$decodedError['metadata']['duplicate_identifiers']??[],true)) {
            $isDuplicatePhone = true;
        }
    }

    if ($isDuplicatePhone) {
        $existingByPhone = getBrevoContactByPhone($BREVO_API_KEY, $formattedPhone);
        if ($existingByPhone!==null) {
            $realCount=(int)($existingByPhone['attributes']['TICKET_COUNT']??0);
            $listIds=$existingByPhone['listIds']??[];
            if (!in_array((int)$BREVO_LIST_ID,$listIds,true)) $listIds[]=(int)$BREVO_LIST_ID;
            $updatePayload=['attributes'=>['CAR_DETAILS'=>$carDetailsText,'HAS_CAR'=>$carDetailsText!==''?'Yes':'No','TICKET_COUNT'=>$realCount+1],'listIds'=>$listIds];
            if (empty($existingByPhone['attributes']['FIRSTNAME']??'')) $updatePayload['attributes']['FIRSTNAME']=$firstName;
            if (empty($existingByPhone['attributes']['LASTNAME']??''))  $updatePayload['attributes']['LASTNAME']=$lastName;
            $updateResult = updateBrevoContactByPhone($BREVO_API_KEY, $formattedPhone, $updatePayload);
            if ($updateResult['code']>=400) error_log('[Marathon register.php] Update-by-phone FAILED: '.$updateResult['body']);
        }
    } elseif ($contactResult['code']>=400) {
        error_log('[Marathon register.php] Brevo contact add FAILED for '.$email.' — HTTP '.$contactResult['code'].' — '.$contactResult['body']);
    }
}

/* ------------------------------------------------------------
   9. NOTIFY ORGANISER
   ------------------------------------------------------------ */
$notifyHtml="
<div style='font-family:Arial,sans-serif; font-size:14px; color:#333; max-width:560px;'>
  <h2 style='color:#C9A84C;'>New registration — Marathon Prayer Hub</h2>
  <p><strong>Name:</strong> ".htmlspecialchars($name)."</p>
  <p><strong>Email:</strong> ".htmlspecialchars($email)."</p>
  <p><strong>Phone:</strong> ".htmlspecialchars($formattedPhone)."</p>
  <p><strong>Ticket ID:</strong> {$ticketId}</p>
  <p><strong>Vehicles:</strong><br/><pre style='font-family:Arial,sans-serif;'>".htmlspecialchars($carsPlain?:'None')."</pre></p>
</div>";

$notifyPayload=['sender'=>['name'=>$SENDER_NAME,'email'=>$SENDER_EMAIL],'to'=>[['email'=>$ORGANISER_EMAIL,'name'=>$ORGANISER_NAME]],'subject'=>'New registration: '.$name,'htmlContent'=>$notifyHtml];
if (!empty($CC_EMAILS)) $notifyPayload['cc']=array_map(fn($cc)=>['email'=>$cc],$CC_EMAILS);
if (!empty($BCC_EMAILS)) $notifyPayload['bcc']=array_map(fn($bcc)=>['email'=>$bcc],$BCC_EMAILS);
sendBrevoEmail($BREVO_API_KEY, $notifyPayload);

echo json_encode(['success'=>true,'ticketId'=>$ticketId]);
exit;

/* ============================================================ HELPERS ============================================================ */
function formatPhoneForBrevo($phone){$c=preg_replace('/[\s\-\(\)]/','',$phone);if(strpos($c,'+')===0)return $c;if(strpos($c,'00')===0)return '+'.substr($c,2);if(strpos($c,'0')===0&&strlen($c)===11)return '+44'.substr($c,1);return $c;}
function sendBrevoEmail($k,$p){$ch=curl_init('https://api.brevo.com/v3/smtp/email');curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_POST,true);curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($p));curl_setopt($ch,CURLOPT_HTTPHEADER,['Accept: application/json','Content-Type: application/json','api-key: '.$k]);$r=curl_exec($ch);$c=curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);return['code'=>$c,'body'=>$r];}
function addBrevoContact($k,$p){$ch=curl_init('https://api.brevo.com/v3/contacts');curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_POST,true);curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($p));curl_setopt($ch,CURLOPT_HTTPHEADER,['Accept: application/json','Content-Type: application/json','api-key: '.$k]);$r=curl_exec($ch);$c=curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);return['code'=>$c,'body'=>$r];}
function getBrevoContact($k,$e){$ch=curl_init('https://api.brevo.com/v3/contacts/'.rawurlencode($e));curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_HTTPHEADER,['Accept: application/json','api-key: '.$k]);$r=curl_exec($ch);$c=curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);if($c===200&&$r){$d=json_decode($r,true);if(is_array($d))return $d;}return null;}
function getBrevoContactByPhone($k,$p){$ch=curl_init('https://api.brevo.com/v3/contacts/'.rawurlencode($p).'?identifierType=phone_id');curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_HTTPHEADER,['Accept: application/json','api-key: '.$k]);$r=curl_exec($ch);$c=curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);if($c===200&&$r){$d=json_decode($r,true);if(is_array($d))return $d;}return null;}
function updateBrevoContactByPhone($k,$p,$payload){$ch=curl_init('https://api.brevo.com/v3/contacts/'.rawurlencode($p).'?identifierType=phone_id');curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);curl_setopt($ch,CURLOPT_CUSTOMREQUEST,'PUT');curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($payload));curl_setopt($ch,CURLOPT_HTTPHEADER,['Accept: application/json','Content-Type: application/json','api-key: '.$k]);$r=curl_exec($ch);$c=curl_getinfo($ch,CURLINFO_HTTP_CODE);curl_close($ch);return['code'=>$c,'body'=>$r];}
