<?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\Invitation\InvitationService;
use App\Modules\Invitation\InvitationValidator;
use App\Modules\Invitation\EventSessionModel;
use App\Modules\Guest\GuestModel;
use App\Modules\PublicInvitation\PublicInvitationModel;

$db = Database::getConnection();

echo "=== PHASE 4 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";

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

// 1. Fetch current invitation details
$invDetails = $invService->getInvitationDetails($wsId);
$events = $invDetails['events'];

if (empty($events)) {
    echo "No events found.\n";
    exit(1);
}

// Find Holy Matrimony event index
$holyIdx = -1;
foreach ($events as $idx => $evt) {
    if (strtolower($evt['event_name']) === 'holy matrimony') {
        $holyIdx = $idx;
        break;
    }
}
if ($holyIdx === -1) {
    $holyIdx = 0;
}

echo "Targeting Event: '{$events[$holyIdx]['event_name']}' (ID: {$events[$holyIdx]['id']})\n";

// 2. Prepare payload with unsorted & multiple invitation times (e.g. 11:30 and 09:30)
$payloadEvents = [];
foreach ($events as $idx => $evt) {
    $item = [
        'id'               => $evt['id'],
        'event_name'       => $evt['event_name'],
        'event_date'       => !empty($evt['event_date']) ? (new \DateTime($evt['event_date']))->format('Y-m-d') : date('Y-m-d'),
        'event_time'       => '10:00',
        'venue_name'       => $evt['venue_name'] ?: 'Grand Ballroom',
        'venue_address'    => $evt['venue_address'] ?: 'Main Hall Address',
        'maps_url'         => $evt['maps_url'] ?: '',
        'maps_embed_code'  => $evt['maps_embed_url'] ?: '',
        'show_map'         => '1',
        'invitation_times' => ($idx === $holyIdx) ? ['11:30', '09:30'] : ['18:00']
    ];
    $payloadEvents[] = $item;
}

$updatePayload = [
    'groom_display_name' => $invDetails['groom_display_name'] ?: 'Groom',
    'bride_display_name' => $invDetails['bride_display_name'] ?: 'Bride',
    'love_story'         => $invDetails['love_story'] ?: '',
    'theme_version_id'   => $invDetails['theme_version_id'] ?: 1,
    'invitation_status'  => $invDetails['invitation_status'] ?: 'draft',
    'rsvp_enabled'       => 1,
    'wishes_enabled'     => 1,
    'primary_event_id'   => $events[$holyIdx]['id'],
    'events'             => $payloadEvents
];

// 3. Test saving invitation details with Invitation Times
echo "\nSaving invitation details with unsorted times ['11:30', '09:30']...\n";
$invService->updateInvitationDetails($wsId, $updatePayload);

// 4. Verify automatic sorting and default session assignment
$holyId = (int) $events[$holyIdx]['id'];
$sessions = $sessionModel->getSessionsByEventId($wsId, $holyId);

echo "\n--- VERIFYING EVENT_SESSIONS SYNC & AUTOMATIC SORTING ---\n";
echo "Found " . count($sessions) . " session(s) for Holy Matrimony:\n";
foreach ($sessions as $s) {
    $timeStr = (new \DateTime($s['start_time']))->format('H:i');
    $isDefaultStr = $s['is_default'] ? 'YES (Earliest)' : 'NO';
    echo "  - Session #{$s['id']}: Time: {$timeStr} | Name: '{$s['session_name']}' | Default: {$isDefaultStr}\n";
}

if (count($sessions) >= 2 && (new \DateTime($sessions[0]['start_time']))->format('H:i') === '09:30') {
    echo " [PASS] Earliest time 09:30 automatically sorted first and marked as Default!\n";
} else {
    echo " [FAIL] Sorting or default assignment issue.\n";
}

// 5. Test validation rules
echo "\n--- VERIFYING VALIDATION RULES ---\n";
$validator = new InvitationValidator();

// Test Duplicate Times
$badPayload = $updatePayload;
$badPayload['events'][$holyIdx]['invitation_times'] = ['10:00', '10:00'];
$errorsDup = $validator->validate($badPayload);
if (!empty($errorsDup["event_{$holyIdx}_times"])) {
    echo " [PASS] Duplicate times correctly rejected: {$errorsDup["event_{$holyIdx}_times"]}\n";
} else {
    echo " [FAIL] Duplicate times check failed.\n";
}

// Test Invalid Time Format
$badPayload['events'][$holyIdx]['invitation_times'] = ['25:99'];
$errorsFmt = $validator->validate($badPayload);
if (!empty($errorsFmt["event_{$holyIdx}_time"])) {
    echo " [PASS] Invalid time format correctly rejected: {$errorsFmt["event_{$holyIdx}_time"]}\n";
} else {
    echo " [FAIL] Invalid time format check failed.\n";
}

// Test Empty Times
$badPayload['events'][$holyIdx]['invitation_times'] = [];
$errorsEmpty = $validator->validate($badPayload);
if (!empty($errorsEmpty["event_{$holyIdx}_times"])) {
    echo " [PASS] Minimum 1 time rule correctly enforced: {$errorsEmpty["event_{$holyIdx}_times"]}\n";
} else {
    echo " [FAIL] Minimum 1 time check failed.\n";
}

// 6. Test Public Invitation Renderer Data Loading
$guestId = (int) ($db->query("SELECT id FROM guests WHERE workspace_id = {$wsId} AND is_deleted = 0 LIMIT 1")->fetchColumn() ?: 0);
if ($guestId > 0) {
    echo "\n--- VERIFYING PUBLIC INVITATION DATA LOADING ---\n";
    $assignedEvts = $pubModel->getAssignedEvents($wsId, $guestId);
    foreach ($assignedEvts as $ae) {
        if ($ae['id'] == $holyId) {
            echo "Public Invitation Event: '{$ae['event_name']}' | Date/Time: {$ae['event_date']} | Session Name: '{$ae['session_name']}'\n";
            echo " [PASS] Public invitation renderer receives event_date resolved cleanly!\n";
        }
    }
}

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