<?php
// api/wa_send.php — send a guest's invite via WhatsApp Cloud API (admin only)
require_once __DIR__ . '/../config.php';
adminGuard();
requireCsrf();

$db      = db();
$adminId = (int)$_SESSION['admin_id'];

$body    = json_decode(file_get_contents('php://input'), true) ?? [];
$eventId = (int)($body['event_id'] ?? 0);
$guestId = (int)($body['guest_id'] ?? 0);

// Load admin (WhatsApp creds) + verify event ownership
$adminRow = $db->prepare('SELECT * FROM admins WHERE id=?');
$adminRow->execute([$adminId]);
$admin = $adminRow->fetch();

if (($admin['wa_provider'] ?? 'manual') === 'manual') {
    jsonOut(['ok' => false, 'error' => 'WhatsApp provider is set to manual. Enable Cloud API or Twilio in Account settings.'], 400);
}

$evStmt = $db->prepare('SELECT * FROM events WHERE id=? AND admin_id=?');
$evStmt->execute([$eventId, $adminId]);
$event = $evStmt->fetch();
if (!$event) jsonOut(['ok' => false, 'error' => 'Event not found.'], 404);

$gStmt = $db->prepare('SELECT * FROM guests WHERE id=? AND event_id=?');
$gStmt->execute([$guestId, $eventId]);
$guest = $gStmt->fetch();
if (!$guest) jsonOut(['ok' => false, 'error' => 'Guest not found.'], 404);
if (empty($guest['phone'])) jsonOut(['ok' => false, 'error' => 'Guest has no phone number.'], 400);

// Compose message from the event's WhatsApp template
$tpl = $event['wa_message'] ?: "Hello {name}, here is your invitation to {event}. Please present the attached ticket at the entrance.";
$msg = strtr($tpl, [
    '{name}'  => $guest['name'],
    '{event}' => $event['title'],
    '{venue}' => $event['venue'] ?? '',
]);

// Public ticket image URL (if generated)
$imageUrl = !empty($guest['invite_path']) ? BASE_URL . '/' . ltrim($guest['invite_path'], '/') : '';

$result = sendWhatsApp($admin, $guest['phone'], $msg, $imageUrl);

// Log to wa_send_log (used by guest exports & "WA failed" filters). Best-effort.
try {
    $db->prepare('INSERT INTO wa_send_log
        (guest_id,event_id,admin_id,phone,guest_name,method,status,twilio_sid,error_msg,ticket_url,sent_at)
        VALUES (?,?,?,?,?,?,?,?,?,?,NOW())')
       ->execute([
           $guestId, $eventId, $adminId, $guest['phone'], $guest['name'],
           'api', $result['ok'] ? 'sent' : 'failed',
           $result['sid'] ?? null,
           $result['ok'] ? null : $result['error'], $imageUrl ?: null,
       ]);
} catch (\PDOException $e) { /* table optional */ }

if ($result['ok']) {
    $db->prepare('UPDATE guests SET invite_sent=1, invite_sent_at=NOW(), invite_sent_by=? WHERE id=?')
       ->execute([$adminId, $guestId]);
    adminLog('whatsapp.send', 'guest', $guestId, $result['method'] ?? 'api');
    jsonOut(['ok' => true]);
}
jsonOut(['ok' => false, 'error' => $result['error']]);
