<?php

declare(strict_types=1);

// ─── Production Safety Guard ─────────────────────────────────────────────────
// This script performs a destructive database reset. It MUST NEVER run in
// production. Block execution immediately if the environment is not local.
// Load .env manually here (before the full bootstrap) to read APP_ENV.
(function () {
    $envFile = __DIR__ . '/.env';
    $appEnv  = 'production'; // safe default — assume production if unreadable
    $devMode = 'false';
    if (is_readable($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);
            $k = trim($k);
            $v = trim($v);
            if ($k === 'APP_ENV')       $appEnv  = $v;
            if ($k === 'DEVELOPER_MODE') $devMode = strtolower($v);
        }
    }
    if ($appEnv !== 'local' || $devMode !== 'true') {
        if (!headers_sent()) {
            http_response_code(403);
        }
        echo "403 Forbidden — this script may only run in local developer mode.\n";
        exit(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';

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

use App\Core\Database;

$db = Database::getConnection();

echo "Starting Development Database Reset...\n";

// Disable foreign key checks for clean cleanup
$db->exec('SET FOREIGN_KEY_CHECKS = 0');

// 1. Identify or target 'test-couple' workspace
$stmtWs = $db->prepare('SELECT id FROM workspaces WHERE slug = "test-couple" LIMIT 1');
$stmtWs->execute();
$workspaceId = $stmtWs->fetchColumn();

if (!$workspaceId) {
    $stmtInsWs = $db->prepare('
        INSERT INTO workspaces (slug, groom_name, bride_name, wedding_date, event_type_id, commercial_plan_id, workspace_status)
        VALUES ("test-couple", "Ahmad", "Fatimah", "2026-12-12", 1, 1, "active")
    ');
    $stmtInsWs->execute();
    $workspaceId = (int) $db->lastInsertId();
    echo "Created workspace 'test-couple' (ID: $workspaceId)\n";
} else {
    $workspaceId = (int) $workspaceId;
    echo "Found workspace 'test-couple' (ID: $workspaceId)\n";
}

// Delete all OTHER workspaces and their related data
$db->prepare('DELETE FROM workspaces WHERE id != :ws_id')->execute(['ws_id' => $workspaceId]);

// 2. Clean users
$stmtSuperRole = $db->prepare('SELECT id FROM roles WHERE slug = "super_admin" LIMIT 1');
$stmtSuperRole->execute();
$superRoleId = (int) ($stmtSuperRole->fetchColumn() ?: 1);

$stmtCoupleRole = $db->prepare('SELECT id FROM roles WHERE slug = "couple" LIMIT 1');
$stmtCoupleRole->execute();
$coupleRoleId = (int) ($stmtCoupleRole->fetchColumn() ?: 2);

$stmtCrewRole = $db->prepare('SELECT id FROM roles WHERE slug = "crew" LIMIT 1');
$stmtCrewRole->execute();
$crewRoleId = (int) ($stmtCrewRole->fetchColumn() ?: 3);

$superHash = password_hash('Maskokoit123!', PASSWORD_BCRYPT);
$coupleHash = password_hash('test', PASSWORD_BCRYPT);

// Delete all users except superadmin, couple, testcrew
$db->exec('
    DELETE FROM users 
    WHERE (username IS NULL OR username NOT IN ("superadmin", "couple", "testcrew")) 
      AND (email IS NULL OR email NOT IN ("superadmin@inveetaire.com", "couple@inveetaire.com"))
');

// Upsert superadmin
$stmtSuper = $db->prepare('SELECT id FROM users WHERE username = "superadmin" OR email = "superadmin@inveetaire.com" LIMIT 1');
$stmtSuper->execute();
$superId = $stmtSuper->fetchColumn();
if ($superId) {
    $db->prepare('UPDATE users SET password_hash = :hash, role_id = :role, username = "superadmin", email = "superadmin@inveetaire.com", display_name = "Super Admin", is_active = 1 WHERE id = :id')
       ->execute(['hash' => $superHash, 'role' => $superRoleId, 'id' => $superId]);
} else {
    $db->prepare('INSERT INTO users (role_id, email, username, password_hash, display_name, is_active) VALUES (:role, "superadmin@inveetaire.com", "superadmin", :hash, "Super Admin", 1)')
       ->execute(['role' => $superRoleId, 'hash' => $superHash]);
}

// Upsert couple user
$stmtCpl = $db->prepare('SELECT id FROM users WHERE username = "couple" OR email = "couple@inveetaire.com" LIMIT 1');
$stmtCpl->execute();
$cplId = $stmtCpl->fetchColumn();
if ($cplId) {
    $db->prepare('UPDATE users SET workspace_id = :ws_id, username = "couple", email = "couple@inveetaire.com", password_hash = :hash, display_name = "Ahmad & Fatimah", is_active = 1 WHERE id = :id')
       ->execute(['ws_id' => $workspaceId, 'hash' => $coupleHash, 'id' => $cplId]);
} else {
    $db->prepare('INSERT INTO users (workspace_id, role_id, email, username, password_hash, display_name, is_active) VALUES (:ws_id, :role, "couple@inveetaire.com", "couple", :hash, "Ahmad & Fatimah", 1)')
       ->execute(['ws_id' => $workspaceId, 'role' => $coupleRoleId, 'hash' => $coupleHash]);
}

// Ensure testcrew user exists
$stmtCrew = $db->prepare('SELECT id FROM users WHERE username = "testcrew" LIMIT 1');
$stmtCrew->execute();
$crewUserId = $stmtCrew->fetchColumn();
if (!$crewUserId) {
    $crewHash = password_hash('crew123', PASSWORD_BCRYPT);
    $db->prepare('INSERT INTO users (workspace_id, role_id, username, password_hash, display_name, is_active) VALUES (:ws_id, :role, "testcrew", :hash, "Event Crew Desk 1", 1)')
       ->execute(['ws_id' => $workspaceId, 'role' => $crewRoleId, 'hash' => $crewHash]);
    $crewUserId = (int) $db->lastInsertId();
} else {
    $db->prepare('UPDATE users SET workspace_id = :ws_id, is_active = 1 WHERE id = :id')
       ->execute(['ws_id' => $workspaceId, 'id' => $crewUserId]);
}

// Ensure crew_accounts row exists
$db->prepare('DELETE FROM crew_accounts WHERE workspace_id != :ws_id')->execute(['ws_id' => $workspaceId]);
$stmtCrewAcc = $db->prepare('SELECT id FROM crew_accounts WHERE workspace_id = :ws_id AND user_id = :user_id LIMIT 1');
$stmtCrewAcc->execute(['ws_id' => $workspaceId, 'user_id' => $crewUserId]);
if (!$stmtCrewAcc->fetchColumn()) {
    $db->prepare('INSERT INTO crew_accounts (workspace_id, user_id, display_name, desk_label, is_active) VALUES (:ws_id, :user_id, "Event Crew", "Main Gate", 1)')
       ->execute(['ws_id' => $workspaceId, 'user_id' => $crewUserId]);
}

// Delete any other users
$db->prepare('DELETE FROM users WHERE username NOT IN ("superadmin", "couple", "testcrew") AND email NOT IN ("superadmin@inveetaire.com", "couple@inveetaire.com")')->execute();

// 3. Invitations
$db->prepare('DELETE FROM invitations WHERE workspace_id != :ws_id')->execute(['ws_id' => $workspaceId]);
$stmtInv = $db->prepare('SELECT id FROM invitations WHERE workspace_id = :ws_id LIMIT 1');
$stmtInv->execute(['ws_id' => $workspaceId]);
$invId = $stmtInv->fetchColumn();
if (!$invId) {
    $db->prepare('
        INSERT INTO invitations (workspace_id, theme_version_id, groom_display_name, bride_display_name, love_story, rsvp_enabled, wish_wall_enabled, invitation_status)
        VALUES (:ws_id, 1, "Ahmad", "Fatimah", "Our Journey of Love", 1, 1, "published")
    ')->execute(['ws_id' => $workspaceId]);
    $invId = (int) $db->lastInsertId();
}
$db->prepare('DELETE FROM invitation_sections WHERE invitation_id != :inv_id')->execute(['inv_id' => $invId]);

// 4. Ceremonies (wedding_events)
$db->prepare('DELETE FROM wedding_events WHERE workspace_id != :ws_id')->execute(['ws_id' => $workspaceId]);

// Ensure 3 ceremonies for test-couple
$requiredEvents = [
    ['name' => 'Holy Matrimony', 'venue' => 'Chapel Gereja Mawar Sharon', 'address' => 'Jl. Cempaka No.24, Tegalsari', 'is_primary' => 0, 'sort_order' => 1, 'time' => ' 09:00:00'],
    ['name' => 'Tea Pai', 'venue' => 'VIP Room Lt. 3', 'address' => 'Jl. Cempaka No.24, Tegalsari', 'is_primary' => 0, 'sort_order' => 2, 'time' => ' 11:30:00'],
    ['name' => 'Reception', 'venue' => 'Grand Ballroom Lt. 3', 'address' => 'Jl. Cempaka No.24, Tegalsari', 'is_primary' => 1, 'sort_order' => 3, 'time' => ' 18:00:00'],
];

$eventMap = [];
foreach ($requiredEvents as $req) {
    $stmtE = $db->prepare('SELECT id FROM wedding_events WHERE workspace_id = :ws_id AND event_name = :name LIMIT 1');
    $stmtE->execute(['ws_id' => $workspaceId, 'name' => $req['name']]);
    $eId = $stmtE->fetchColumn();
    if (!$eId) {
        $stmtIns = $db->prepare('
            INSERT INTO wedding_events (workspace_id, event_name, event_date, venue_name, venue_address, is_primary, sort_order, show_map, is_deleted)
            VALUES (:ws_id, :name, :date, :venue, :address, :is_primary, :sort, 1, 0)
        ');
        $stmtIns->execute([
            'ws_id'      => $workspaceId,
            'name'       => $req['name'],
            'date'       => '2026-12-12' . $req['time'],
            'venue'      => $req['venue'],
            'address'    => $req['address'],
            'is_primary' => $req['is_primary'],
            'sort'       => $req['sort_order']
        ]);
        $eId = (int) $db->lastInsertId();
    } else {
        $eId = (int) $eId;
        $db->prepare('UPDATE wedding_events SET is_deleted = 0 WHERE id = :id')->execute(['id' => $eId]);
    }
    $eventMap[$req['name']] = $eId;
}

// 5. Clean Guests, Checkins, RSVPs, Wishes, Guest Events
$db->exec('TRUNCATE TABLE checkins');
$db->exec('TRUNCATE TABLE rsvps');
$db->exec('TRUNCATE TABLE wishes');
$db->exec('TRUNCATE TABLE guest_timelines');
$db->exec('TRUNCATE TABLE guest_events');
$db->exec('TRUNCATE TABLE guests');

// 6. Create 10 fresh sample guests for test-couple
$sampleGuests = [
    [
        'guest_code'   => 'KIB8H',
        'honorific'    => 'Bpk. & Ibu',
        'full_name'    => 'Ahmad Fauzi',
        'side'         => 'groom',
        'guest_group'  => 'family',
        'invited_pax'  => 2,
        'phone_number' => '081234567890',
        'events'       => ['Holy Matrimony', 'Tea Pai', 'Reception']
    ],
    [
        'guest_code'   => 'B2K9L',
        'honorific'    => 'Dr.',
        'full_name'    => 'Budi Santoso',
        'side'         => 'groom',
        'guest_group'  => 'relatives',
        'invited_pax'  => 1,
        'phone_number' => '081298765432',
        'events'       => ['Holy Matrimony', 'Reception']
    ],
    [
        'guest_code'   => 'C3M1P',
        'honorific'    => 'Sdr.',
        'full_name'    => 'Charlie Wijaya',
        'side'         => 'bride',
        'guest_group'  => 'friends',
        'invited_pax'  => 2,
        'phone_number' => '081311223344',
        'events'       => ['Reception']
    ],
    [
        'guest_code'   => 'D4N2Q',
        'honorific'    => 'Ibu',
        'full_name'    => 'Dewi Lestari',
        'side'         => 'bride',
        'guest_group'  => 'colleagues',
        'invited_pax'  => 1,
        'phone_number' => '081355667788',
        'events'       => ['Reception']
    ],
    [
        'guest_code'   => 'E5P3R',
        'honorific'    => 'Pnt.',
        'full_name'    => 'Eko Prasetyo',
        'side'         => 'couple',
        'guest_group'  => 'church',
        'invited_pax'  => 2,
        'phone_number' => '081499887766',
        'events'       => ['Holy Matrimony', 'Reception']
    ],
    [
        'guest_code'   => 'F6Q4S',
        'honorific'    => 'Bpk.',
        'full_name'    => 'Ferry Gunawan',
        'side'         => 'groom',
        'guest_group'  => 'business_partners',
        'invited_pax'  => 2,
        'phone_number' => '081512344321',
        'events'       => ['Reception']
    ],
    [
        'guest_code'   => 'G7R5T',
        'honorific'    => 'Bpk. & Ibu',
        'full_name'    => 'Gideon Tan',
        'side'         => 'bride',
        'guest_group'  => 'vip',
        'invited_pax'  => 4,
        'phone_number' => '081699001122',
        'events'       => ['Holy Matrimony', 'Tea Pai', 'Reception']
    ],
    [
        'guest_code'   => 'H8S6U',
        'honorific'    => 'Sdri.',
        'full_name'    => 'Hendra Saputra',
        'side'         => 'groom',
        'guest_group'  => 'friends',
        'invited_pax'  => 1,
        'phone_number' => '081733445566',
        'events'       => ['Reception']
    ],
    [
        'guest_code'   => 'I9T7V',
        'honorific'    => 'Ibu',
        'full_name'    => 'Irene Kusuma',
        'side'         => 'bride',
        'guest_group'  => 'family',
        'invited_pax'  => 2,
        'phone_number' => '081877665544',
        'events'       => ['Holy Matrimony', 'Tea Pai', 'Reception']
    ],
    [
        'guest_code'   => 'J0U8W',
        'honorific'    => 'Bpk.',
        'full_name'    => 'Joko Widodo',
        'side'         => 'couple',
        'guest_group'  => 'others',
        'invited_pax'  => 2,
        'phone_number' => '081911335577',
        'events'       => ['Reception']
    ],
];

$stmtGuestIns = $db->prepare('
    INSERT INTO guests (workspace_id, guest_code, honorific, full_name, side, guest_group, invited_pax, phone_number, invitation_status, rsvp_status, checkin_status, is_deleted)
    VALUES (:ws_id, :code, :honorific, :name, :side, :group, :pax, :phone, "not_sent", "pending", "not_arrived", 0)
');

$stmtGeIns = $db->prepare('
    INSERT INTO guest_events (guest_id, wedding_event_id, workspace_id, rsvp_status)
    VALUES (:guest_id, :event_id, :ws_id, "pending")
');

foreach ($sampleGuests as $g) {
    $stmtGuestIns->execute([
        'ws_id'     => $workspaceId,
        'code'      => $g['guest_code'],
        'honorific' => $g['honorific'],
        'name'      => $g['full_name'],
        'side'      => $g['side'],
        'group'     => $g['guest_group'],
        'pax'       => $g['invited_pax'],
        'phone'     => $g['phone_number']
    ]);
    $gId = (int) $db->lastInsertId();

    foreach ($g['events'] as $evtName) {
        if (isset($eventMap[$evtName])) {
            $stmtGeIns->execute([
                'guest_id' => $gId,
                'event_id' => $eventMap[$evtName],
                'ws_id'    => $workspaceId
            ]);
        }
    }
}

// Re-enable foreign key checks
$db->exec('SET FOREIGN_KEY_CHECKS = 1');

echo "Database reset completed successfully!\n";
