<?php

define('ROOT_PATH', dirname(__DIR__));
require_once ROOT_PATH . '/app/core/Autoloader.php';
\App\Core\Autoloader::register();

$bootstrap = new \App\Core\Bootstrap();
$bootstrap->init();

use App\Modules\Guest\GuestModel;
use App\Modules\Operation\OperationModel;
use App\Core\Database;

function run_assert(string $name, bool $assertion) {
    if ($assertion) {
        echo "✅ PASS: $name\n";
    } else {
        echo "❌ FAIL: $name\n";
        exit(1);
    }
}

try {
    $db = Database::getConnection();
    $workspaceId = 83; // Target workspace ID from check_events.php
    $operatorId = 1008;   // Test operator user ID (couple user)

    $guestModel = new GuestModel();
    $opModel = new OperationModel();

    // 1. Ensure pilot events exist
    $opModel->ensurePilotEventsExist($workspaceId);
    $opModel->migrateExistingGuestsEvents($workspaceId);

    // Fetch active events
    $stmt = $db->prepare('SELECT id, event_name FROM wedding_events WHERE workspace_id = :workspace_id AND is_deleted = 0 ORDER BY sort_order ASC');
    $stmt->execute(['workspace_id' => $workspaceId]);
    $events = $stmt->fetchAll(PDO::FETCH_ASSOC);

    run_assert("Should have exactly 3 active pilot events", count($events) === 3);

    $holyMatrimonyId = null;
    $teaPaiId = null;
    $receptionId = null;

    foreach ($events as $evt) {
        if ($evt['event_name'] === 'Holy Matrimony') $holyMatrimonyId = (int) $evt['id'];
        if ($evt['event_name'] === 'Tea Pai') $teaPaiId = (int) $evt['id'];
        if ($evt['event_name'] === 'Reception') $receptionId = (int) $evt['id'];
    }

    run_assert("Holy Matrimony event found", $holyMatrimonyId !== null);
    run_assert("Tea Pai event found", $teaPaiId !== null);
    run_assert("Reception event found", $receptionId !== null);

    // 2. Clean up previous test guest if exists
    $db->prepare('DELETE FROM checkins WHERE guest_id IN (SELECT id FROM guests WHERE full_name = "Test Charlie Override")')->execute();
    $db->prepare('DELETE FROM guest_events WHERE guest_id IN (SELECT id FROM guests WHERE full_name = "Test Charlie Override")')->execute();
    $db->prepare('DELETE FROM guests WHERE full_name = "Test Charlie Override"')->execute();

    // Generate unique code
    $testGuestCode = 'charlieoverride83';

    // Insert guest
    $guestId = $guestModel->insertGuest($workspaceId, [
        'guest_code'   => $testGuestCode,
        'full_name'    => 'Test Charlie Override',
        'side'         => 'couple',
        'guest_group'  => 'vip',
        'invited_pax'  => 2,
        'phone_number' => '123456789',
        'notes'        => 'Test notes'
    ]);

    run_assert("Guest created successfully", $guestId > 0);

    // Save event access: Holy Matrimony & Reception (NOT Tea Pai)
    $guestModel->saveGuestEvents($workspaceId, $guestId, [$holyMatrimonyId, $receptionId]);

    // Check allowed event IDs
    $allowedEventIds = $guestModel->getGuestEventIds($workspaceId, $guestId);
    run_assert("Should have access to Holy Matrimony", in_array($holyMatrimonyId, $allowedEventIds));
    run_assert("Should have access to Reception", in_array($receptionId, $allowedEventIds));
    run_assert("Should NOT have access to Tea Pai", !in_array($teaPaiId, $allowedEventIds));

    // 3. Test check-in simulation
    // Let's clear previous checkins if any for this guest
    $db->prepare('DELETE FROM checkins WHERE guest_id = :guest_id')->execute(['guest_id' => $guestId]);

    // Check-in to Holy Matrimony (Invited)
    $success = $opModel->checkInGuestForEvent($workspaceId, $guestId, $holyMatrimonyId, $operatorId, 'manual', 'Standard arrival at Table 4');
    run_assert("Standard check-in for invited event should succeed", $success === true);

    // Verify checkin record
    $checkin = $opModel->getCheckinRecord($workspaceId, $guestId, $holyMatrimonyId);
    run_assert("Check-in record should exist", $checkin !== null);
    run_assert("Checkin method should be manual", $checkin['checkin_method'] === 'manual');
    run_assert("Checkin notes match", $checkin['notes'] === 'Standard arrival at Table 4');

    // 4. Test checking in to Tea Pai (Not Invited)
    // First, verify is guest invited to Tea Pai
    $isInvitedToTeaPai = false;
    $guestAllowedEvents = $opModel->getAssignedEvents($workspaceId, $guestId);
    foreach ($guestAllowedEvents as $gae) {
        if ((int) $gae['id'] === $teaPaiId) {
            $isInvitedToTeaPai = true;
        }
    }
    run_assert("Guest is not invited to Tea Pai according to assigned events list", $isInvitedToTeaPai === false);

    // Perform manual override check-in
    $overrideNotes = '[OVERRIDE] Reason: VIP | Notes: Bride requested override';
    $overrideSuccess = $opModel->checkInGuestForEvent($workspaceId, $guestId, $teaPaiId, $operatorId, 'manual', $overrideNotes);
    run_assert("Override check-in should succeed when explicitly forced", $overrideSuccess === true);

    $teaPaiCheckin = $opModel->getCheckinRecord($workspaceId, $guestId, $teaPaiId);
    run_assert("Tea Pai override check-in record exists", $teaPaiCheckin !== null);
    run_assert("Tea Pai checkin notes contain override details", strpos($teaPaiCheckin['notes'], '[OVERRIDE]') !== false);

    // Verify statistics calculations
    $stats = $opModel->getEventAttendanceStats($workspaceId, $teaPaiId);
    run_assert("Tea Pai overrides stat count is 1", $stats['overrides_count'] === 1);
    run_assert("Tea Pai expected guests count is >= 0", $stats['expected_guests'] >= 0);

    $holyStats = $opModel->getEventAttendanceStats($workspaceId, $holyMatrimonyId);
    run_assert("Holy Matrimony overrides stat count is 0 (standard invite check-in)", $holyStats['overrides_count'] === 0);
    run_assert("Holy Matrimony checked-in count is at least 1", $holyStats['checked_in_count'] >= 1);

    // Clean up test guest data
    $db->prepare('DELETE FROM checkins WHERE guest_id = :guest_id')->execute(['guest_id' => $guestId]);
    $db->prepare('DELETE FROM guest_events WHERE guest_id = :guest_id')->execute(['guest_id' => $guestId]);
    $db->prepare('DELETE FROM guests WHERE id = :guest_id')->execute(['guest_id' => $guestId]);

    echo "\n🎉 ALL LOGIC AND AUDIT VERIFICATIONS PASSED SUCCESSFULLY!\n";

} catch (Throwable $e) {
    echo "❌ EXCEPTION: " . $e->getMessage() . " at " . $e->getFile() . ":" . $e->getLine() . "\n";
    exit(1);
}
