<?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\Operation\OperationModel;
use App\Modules\Invitation\EventSessionModel;

$db = Database::getConnection();

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

// 1. Fetch workspaces
$workspaces = $db->query('SELECT id, slug FROM workspaces')->fetchAll(\PDO::FETCH_ASSOC);
echo "Found " . count($workspaces) . " workspace(s).\n";

$opModel = new OperationModel();
$sessionModel = new EventSessionModel();

foreach ($workspaces as $ws) {
    $wsId = (int) $ws['id'];
    echo "\nWorkspace ID: {$wsId} (slug: {$ws['slug']})\n";

    // Ensure pilot events and default sessions exist
    $opModel->ensurePilotEventsExist($wsId);

    // Query wedding events
    $events = $db->query("SELECT id, event_name, event_date, venue_name FROM wedding_events WHERE workspace_id = {$wsId} AND is_deleted = 0 ORDER BY sort_order ASC")->fetchAll(\PDO::FETCH_ASSOC);

    echo " Wedding Events (" . count($events) . "):\n";
    foreach ($events as $evt) {
        $evtId = (int) $evt['id'];
        $sessions = $sessionModel->getSessionsByEventId($wsId, $evtId);
        echo "  - Event #{$evtId}: '{$evt['event_name']}' on {$evt['event_date']}\n";
        echo "    Sessions (" . count($sessions) . "):\n";
        foreach ($sessions as $s) {
            echo "     * Session #{$s['id']}: '{$s['session_name']}' | Start: {$s['start_time']} | Default: " . ($s['is_default'] ? 'YES' : 'NO') . "\n";
        }
    }
}

// 2. Verify schema structure
echo "\n=== SCHEMA VERIFICATION ===\n";
$tables = $db->query("SHOW TABLES LIKE 'event_sessions'")->fetchAll();
echo "Table 'event_sessions' exists: " . (!empty($tables) ? "YES" : "NO") . "\n";

$cols = $db->query("SHOW COLUMNS FROM guest_events LIKE 'event_session_id'")->fetchAll();
echo "Column 'guest_events.event_session_id' exists: " . (!empty($cols) ? "YES" : "NO") . "\n";

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