<?php

declare(strict_types=1);

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

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

use App\Core\Database;
use App\Modules\Invitation\InvitationModel;
use App\Modules\Invitation\InvitationService;
use App\Modules\PublicInvitation\PublicInvitationService;

echo "=== GOOGLE MAPS EMBED FIX VERIFICATION ===\n\n";

// 1. Verify public/.htaccess CSP header
$htaccessContent = file_get_contents(ROOT_PATH . '/public/.htaccess');
if (strpos($htaccessContent, "frame-src 'self' https://www.google.com https://*.google.com") !== false) {
    echo "[PASS] public/.htaccess CSP header contains frame-src directive permitting Google Maps!\n";
} else {
    echo "[FAIL] public/.htaccess CSP header missing required frame-src directive.\n";
}

// 2. Verify extractMapsEmbedUrl unit tests
$model = new InvitationModel();

$sampleIframe = '<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3966.521260322283!2d106.819561314769!3d-6.194741395515383!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x2e69f421f1c7d2eb%3A0xb3dfc067d5ff789!2sGrand%20Hyatt%20Jakarta!5e0!3m2!1sen!2sid!4v1620000000000!5m2!1sen!2sid" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"></iframe>';
$sampleDirectUrl = 'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3966.521260322283!2d106.819561314769!3d-6.194741395515383!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x2e69f421f1c7d2eb%3A0xb3dfc067d5ff789!2sGrand%20Hyatt%20Jakarta!5e0!3m2!1sen!2sid!4v1620000000000!5m2!1sen!2sid';
$maliciousInput = '<iframe src="https://attacker.com/malicious.html"></iframe>';

$res1 = $model->extractMapsEmbedUrl($sampleIframe);
$res2 = $model->extractMapsEmbedUrl($sampleDirectUrl);
$res3 = $model->extractMapsEmbedUrl($maliciousInput);
$res4 = $model->extractMapsEmbedUrl('');

if ($res1 === $sampleDirectUrl) {
    echo "[PASS] extractMapsEmbedUrl correctly extracted src from full <iframe ...> snippet!\n";
} else {
    echo "[FAIL] extractMapsEmbedUrl failed to extract iframe src.\n";
}

if ($res2 === $sampleDirectUrl) {
    echo "[PASS] extractMapsEmbedUrl correctly preserved direct embed URL on form resubmit!\n";
} else {
    echo "[FAIL] extractMapsEmbedUrl rejected direct embed URL.\n";
}

if ($res3 === null) {
    echo "[PASS] extractMapsEmbedUrl correctly rejected non-Google embed URL!\n";
} else {
    echo "[FAIL] extractMapsEmbedUrl failed to reject non-Google URL.\n";
}

if ($res4 === null) {
    echo "[PASS] extractMapsEmbedUrl correctly returned null for empty input!\n";
} else {
    echo "[FAIL] extractMapsEmbedUrl failed on empty input.\n";
}

// 3. Integration & Live Preview Payload Verification
$db = Database::getConnection();
$ws = $db->query('SELECT id, slug FROM workspaces LIMIT 1')->fetch(\PDO::FETCH_ASSOC);
if ($ws) {
    $wsId = (int) $ws['id'];

    $events = $model->getAllEvents($wsId);

    if (!empty($events)) {
        foreach ($events as &$e) {
            $e['event_date'] = !empty($e['event_date']) ? (new \DateTime($e['event_date']))->format('Y-m-d') : date('Y-m-d');
            $e['invitation_times'] = ['10:00'];
        }
        unset($e);

        $extracted = $model->extractMapsEmbedUrl($sampleIframe);
        $stmtUpd = $db->prepare("UPDATE wedding_events SET maps_embed_url = :url WHERE workspace_id = :ws_id AND id = :id");
        $stmtUpd->execute(['url' => $extracted, 'ws_id' => $wsId, 'id' => $events[0]['id']]);

        $pubModel = new \App\Modules\PublicInvitation\PublicInvitationModel();
        $allEvents = $pubModel->getAllEvents($wsId);
        $savedEmbedUrl = $allEvents[0]['maps_embed_url'] ?? '';

        if ($savedEmbedUrl === $sampleDirectUrl) {
            echo "[PASS] Database & Public Invitation model query returned valid maps_embed_url!\n";
        } else {
            echo "[FAIL] Database & Public Invitation model maps_embed_url mismatch (got: '{$savedEmbedUrl}').\n";
        }
    }
}

echo "\nGoogle Maps Embed Fix Verification Complete.\n";
