<?php
/**
 * Checkout Automation Cron
 * Run daily at 12:00 PM: 0 12 * * * php /path/to/cron/checkout_automation.php
 */
require __DIR__ . '/../api/bootstrap.php';
require __DIR__ . '/../api/services/WhatsAppService.php';

$pdo = db();
$config = $GLOBALS['CONFIG'];

echo date('Y-m-d H:i:s') . " — Running checkout automation...\n";

// Find bookings checking out today
$stmt = $pdo->query("
    SELECT b.*, g.name AS guest_name, g.phone AS guest_phone, p.name AS property_name, p.google_review_url
    FROM bookings b
    JOIN guests g ON g.id = b.guest_id
    JOIN properties p ON p.id = b.property_id
    WHERE b.check_out = CURDATE() AND b.status = 'checked_in'
");

$checkouts = $stmt->fetchAll(PDO::FETCH_ASSOC);
$processed = 0;

foreach ($checkouts as $booking) {
    // Close WhatsApp session
    $wa = new WhatsAppService($pdo, $config, $booking['property_id']);
    $wa->closeGuestSession($booking['id']);

    // Send thank you message
    if ($booking['guest_phone']) {
        $reviewLink = $booking['google_review_url'] ?: 'https://gethostiva.com';
        $wa->sendCheckout($booking['guest_phone'], $booking['guest_name'], $booking['property_name'], $reviewLink);
    }

    // Close open tickets for this guest
    $pdo->prepare("UPDATE service_tickets SET status='cancelled' WHERE booking_id=? AND status IN ('pending','assigned')")->execute([$booking['id']]);

    $processed++;
    echo "  Processed checkout: {$booking['guest_name']}\n";
}

echo "Done. Processed {$processed} checkouts.\n";
