<?php

declare(strict_types=1);

define('ROOT_PATH', __DIR__ . '/..');

require_once ROOT_PATH . '/app/Core/Autoloader.php';
\App\Core\Autoloader::register();
require_once ROOT_PATH . '/app/helpers/env.php';
require_once ROOT_PATH . '/app/helpers/config.php';

$envFile = ROOT_PATH . '/.env';
if (file_exists($envFile)) {
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
        $line = trim($line);
        if ($line === '' || $line[0] === '#' || strpos($line, '=') === false) {
            continue;
        }
        list($k, $v) = explode('=', $line, 2);
        $_ENV[trim($k)] = trim($v);
    }
}

use App\Core\Database;
use App\Modules\Guest\GuestModel;
use App\Modules\Invitation\EventSessionModel;
use App\Modules\PublicInvitation\PublicInvitationModel;
use App\Modules\Operation\OperationModel;

$db = Database::getConnection();

echo "=== PHASE 2 VERIFICATION SCRIPT ===\n\n";

$ws = $db->query('SELECT id, slug FROM workspaces LIMIT 1')->fetch(\PDO::FETCH_ASSOC);
if (!$ws) {
    echo "No workspace found.\n";
    exit(1);
}

$wsId = (int) $ws['id'];
echo "Testing on Workspace ID: {$wsId} ({$ws['slug']})\n";

$opModel = new OperationModel();
$opModel->ensurePilotEventsExist($wsId);

$sessionModel = new EventSessionModel();
$guestModel = new GuestModel();
$pubModel = new PublicInvitationModel();

// 1. Get Holy Matrimony event
$holyEvent = $db->query("SELECT id, event_name, event_date FROM wedding_events WHERE workspace_id = {$wsId} AND event_name = 'Holy Matrimony' AND is_deleted = 0 LIMIT 1")->fetch(\PDO::FETCH_ASSOC);

if (!$holyEvent) {
    echo "Holy Matrimony event not found.\n";
    exit(1);
}

$holyEventId = (int) $holyEvent['id'];
echo "\nTarget Event: Holy Matrimony (ID: {$holyEventId})\n";

// 2. Ensure Holy Matrimony has 2 sessions: Session 1 (10:00) & Session 2 (11:00)
$existingSessions = $sessionModel->getSessionsByEventId($wsId, $holyEventId);
$session1Id = null;
$session2Id = null;

if (count($existingSessions) < 2) {
    echo "Creating Session 1 (10:00) and Session 2 (11:00) for Holy Matrimony...\n";
    
    // Update existing default session to Session 1 @ 10:00
    if (!empty($existingSessions[0])) {
        $session1Id = (int) $existingSessions[0]['id'];
        $sessionModel->updateSession($wsId, $session1Id, [
            'session_name' => 'Session 1',
            'start_time'   => '2026-09-12 10:00:00',
            'sort_order'   => 1,
            'is_default'   => 1
        ]);
    } else {
        $session1Id = $sessionModel->insertSession($wsId, [
            'wedding_event_id' => $holyEventId,
            'session_name'     => 'Session 1',
            'start_time'       => '2026-09-12 10:00:00',
            'sort_order'       => 1,
            'is_default'       => 1
        ]);
    }

    // Insert Session 2 @ 11:00
    $session2Id = $sessionModel->insertSession($wsId, [
        'wedding_event_id' => $holyEventId,
        'session_name'     => 'Session 2',
        'start_time'       => '2026-09-12 11:00:00',
        'sort_order'       => 2,
        'is_default'       => 0
    ]);
} else {
    $session1Id = (int) $existingSessions[0]['id'];
    $session2Id = (int) $existingSessions[1]['id'];
}

echo "Session 1 ID: {$session1Id} (10:00)\n";
echo "Session 2 ID: {$session2Id} (11:00)\n";

// 3. Create/Setup Guest A (assigned to Session 1) and Guest B (assigned to Session 2)
$guestAId = (int) ($db->query("SELECT id FROM guests WHERE workspace_id = {$wsId} AND full_name = 'Guest Alpha' AND is_deleted = 0 LIMIT 1")->fetchColumn() ?: 0);
if (!$guestAId) {
    $guestAId = $guestModel->insertGuest($wsId, [
        'guest_code'  => 'TESTA',
        'full_name'   => 'Guest Alpha',
        'side'        => 'couple',
        'guest_group' => 'friends',
        'invited_pax' => 2
    ]);
}

$guestBId = (int) ($db->query("SELECT id FROM guests WHERE workspace_id = {$wsId} AND full_name = 'Guest Beta' AND is_deleted = 0 LIMIT 1")->fetchColumn() ?: 0);
if (!$guestBId) {
    $guestBId = $guestModel->insertGuest($wsId, [
        'guest_code'  => 'TESTB',
        'full_name'   => 'Guest Beta',
        'side'        => 'couple',
        'guest_group' => 'friends',
        'invited_pax' => 2
    ]);
}

// Assign Guest A -> Holy Matrimony Session 1
$guestModel->saveGuestEvents($wsId, $guestAId, [$holyEventId], [$holyEventId => $session1Id]);

// Assign Guest B -> Holy Matrimony Session 2
$guestModel->saveGuestEvents($wsId, $guestBId, [$holyEventId], [$holyEventId => $session2Id]);

echo "\nAssigned Guest Alpha (ID {$guestAId}) to Session 1 ({$session1Id})\n";
echo "Assigned Guest Beta (ID {$guestBId}) to Session 2 ({$session2Id})\n";

// 4. Test Invitation Schedule Data Loading for Guest A
echo "\n--- VERIFYING GUEST ALPHA INVITATION PAYLOAD ---\n";
$eventsA = $pubModel->getAssignedEvents($wsId, $guestAId);
foreach ($eventsA as $evt) {
    echo "Event: '{$evt['event_name']}' | Session: '{$evt['session_name']}' | Time: {$evt['event_date']}\n";
    if ($evt['id'] == $holyEventId) {
        if (strpos($evt['event_date'], '10:00') !== false) {
            echo " [PASS] Guest Alpha received correct Session 1 schedule (10:00).\n";
        } else {
            echo " [FAIL] Guest Alpha expected 10:00, got {$evt['event_date']}\n";
        }
    }
}

// 5. Test Invitation Schedule Data Loading for Guest B
echo "\n--- VERIFYING GUEST BETA INVITATION PAYLOAD ---\n";
$eventsB = $pubModel->getAssignedEvents($wsId, $guestBId);
foreach ($eventsB as $evt) {
    echo "Event: '{$evt['event_name']}' | Session: '{$evt['session_name']}' | Time: {$evt['event_date']}\n";
    if ($evt['id'] == $holyEventId) {
        if (strpos($evt['event_date'], '11:00') !== false) {
            echo " [PASS] Guest Beta received correct Session 2 schedule (11:00).\n";
        } else {
            echo " [FAIL] Guest Beta expected 11:00, got {$evt['event_date']}\n";
        }
    }
}

// 6. Test Fallback (Guest with NULL event_session_id)
$guestModel->saveGuestEvents($wsId, $guestAId, [$holyEventId], []); // No session specified
$eventsFallback = $pubModel->getAssignedEvents($wsId, $guestAId);
echo "\n--- VERIFYING FALLBACK FOR NULL EVENT_SESSION_ID ---\n";
foreach ($eventsFallback as $evt) {
    if ($evt['id'] == $holyEventId) {
        echo "Event: '{$evt['event_name']}' | Session: '{$evt['session_name']}' | Time: {$evt['event_date']}\n";
        if (!empty($evt['session_name'])) {
            echo " [PASS] Fallback resolved default session correctly.\n";
        }
    }
}

// Re-assign Guest Alpha to Session 1 for clean state
$guestModel->saveGuestEvents($wsId, $guestAId, [$holyEventId], [$holyEventId => $session1Id]);

echo "\nPhase 2 Verification Complete.\n";
