<?php
/**
 * Hostiva Premium Guest Ecosystem Installer
 */

echo "<h2>Hostiva Premium Guest Ecosystem</h2>";

// 1. API Controller: Fetch Guest Data
$apiContent = <<<'PHP'
<?php
if (!defined('HOSTIVA_API')) exit;
require_permission('guest', 'viewer', 'admin', 'super_admin'); // Allow guests to access

$user = current_user();

// Fetch the active booking for this guest
$stmt = $pdo->prepare("
    SELECT b.*, p.name as property_name, p.address as property_address, p.image_url
    FROM bookings b
    JOIN properties p ON b.property_id = p.id
    WHERE b.guest_user_id = ? AND b.status IN ('confirmed', 'checked_in')
    ORDER BY b.check_in ASC LIMIT 1
");
$stmt->execute([$user['id']]);
$booking = $stmt->fetch();

if (!$booking) {
    echo json_encode(['success' => false, 'message' => 'No active reservations found.']);
    exit;
}

echo json_encode(['success' => true, 'data' => $booking]);
PHP;

// 2. Guest Dashboard HTML (The Premium UI)
$htmlContent = <<<'HTML'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Guest Concierge - Hostiva</title>
    <link rel="stylesheet" href="../assets/css/hostiva.css">
    <style>
        body { background: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; }
        .mobile-shell { max-width: 480px; margin: 0 auto; background: #1e293b; min-height: 100vh; padding: 20px; box-shadow: 0 0 40px rgba(0,0,0,0.5); }
        .hero { text-align: center; padding: 30px 0; }
        .hero h1 { font-size: 24px; font-weight: 300; margin-bottom: 5px; color: #e2e8f0; }
        .card { background: #334155; border-radius: 16px; padding: 20px; margin-bottom: 20px; border: 1px solid #475569; }
        .card h3 { margin-top: 0; font-size: 16px; color: #94a3b8; text-transform: uppercase; letter-spacing: 1px; }
        .data-row { display: flex; justify-content: space-between; margin-bottom: 12px; border-bottom: 1px solid #475569; padding-bottom: 8px;}
        .data-row:last-child { border: none; margin-bottom: 0; padding-bottom: 0; }
        .btn-gold { background: #d4af37; color: #000; padding: 12px 20px; border-radius: 8px; text-align: center; display: block; font-weight: bold; text-decoration: none; cursor: pointer; border: none; width: 100%; }
        .btn-gold:hover { background: #c5a028; }
        .wifi-blur { filter: blur(5px); cursor: pointer; transition: 0.3s; }
        .wifi-blur.revealed { filter: blur(0); cursor: default; }
        textarea { width: 100%; background: #0f172a; border: 1px solid #475569; color: white; padding: 10px; border-radius: 8px; margin-bottom: 10px; }
    </style>
</head>
<body>

<div class="mobile-shell">
    <div class="hero">
        <h1>Welcome, <span id="ui-name">Guest</span></h1>
        <p id="ui-prop" style="color: #d4af37;">Loading your stay...</p>
    </div>

    <div class="card">
        <h3>Your Itinerary</h3>
        <div class="data-row"><span>Check-in</span> <strong id="ui-in">--</strong></div>
        <div class="data-row"><span>Check-out</span> <strong id="ui-out">--</strong></div>
        <div class="data-row"><span>Address</span> <strong id="ui-address" style="text-align: right; max-width: 60%;">--</strong></div>
    </div>

    <div class="card">
        <h3>Property Wi-Fi</h3>
        <div class="data-row"><span>Network</span> <strong id="ui-wifi-net">--</strong></div>
        <div class="data-row"><span>Password</span> <strong class="wifi-blur" id="ui-wifi-pass" onclick="this.classList.add('revealed')">Tap to reveal</strong></div>
    </div>

    <div class="card">
        <h3>Maintenance & Support</h3>
        <p style="font-size: 14px; color: #cbd5e1; margin-bottom:15px;">Need something fixed or restocked? Message our on-site team directly.</p>
        <textarea id="issue-text" rows="3" placeholder="E.g., The AC in the master bedroom isn't cooling..."></textarea>
        <button class="btn-gold" onclick="reportIssue()" id="btn-report">Send to Maintenance</button>
    </div>

    <div class="card" style="text-align: center;">
        <h3>Loving your stay?</h3>
        <p style="font-size: 14px; color: #cbd5e1;">Your feedback means the world to us.</p>
        <a href="https://g.page/review/YOUR_LINK" target="_blank" class="btn-gold" style="background: transparent; border: 2px solid #d4af37; color: #d4af37;">Leave a 5-Star Review</a>
    </div>
</div>

<script>
    // Load Data
    async function loadDashboard() {
        const res = await fetch('../api/?r=guest_dashboard');
        const json = await res.json();
        
        if(json.success) {
            const b = json.data;
            document.getElementById('ui-name').innerText = b.guest_name || 'Guest';
            document.getElementById('ui-prop').innerText = b.property_name;
            document.getElementById('ui-in').innerText = new Date(b.check_in).toLocaleDateString();
            document.getElementById('ui-out').innerText = new Date(b.check_out).toLocaleDateString();
            document.getElementById('ui-address').innerText = b.property_address;
            document.getElementById('ui-wifi-net').innerText = b.wifi_network || 'Hostiva_Guest';
            document.getElementById('ui-wifi-pass').innerText = b.wifi_password || 'Welcome123';
            
            // Store property ID for the ticket system
            window.propId = b.property_id;
        }
    }

    // Connect directly to V3 Operations Kanban
    async function reportIssue() {
        const text = document.getElementById('issue-text').value;
        if(!text) return alert("Please describe the issue.");
        
        document.getElementById('btn-report').innerText = "Sending...";
        
        // Push directly to the staff's ticket kanban board!
        const formData = new FormData();
        formData.append('title', 'Guest Report: ' + text.substring(0, 20) + '...');
        formData.append('description', text);
        formData.append('property_id', window.propId);
        formData.append('priority', 'high');
        formData.append('status', 'open');

        // Note: Assumes your api/?r=tickets endpoint accepts POST for creation
        await fetch('../api/?r=tickets', { method: 'POST', body: formData });
        
        document.getElementById('issue-text').value = '';
        document.getElementById('btn-report').innerText = "Sent! We are on it.";
        setTimeout(() => document.getElementById('btn-report').innerText = "Send to Maintenance", 3000);
    }

    loadDashboard();
</script>
</body>
</html>
HTML;

function writeFile($path, $content) {
    if (!file_exists(dirname($path))) mkdir(dirname($path), 0755, true);
    file_put_contents($path, $content);
    echo "<p style='color:green;'>✅ Created: {$path}</p>";
}

writeFile(__DIR__ . '/api/controllers/guest_dashboard.php', $apiContent);
writeFile(__DIR__ . '/pages/guest/dashboard.html', $htmlContent);

echo "<h3>🎉 Premium Guest Portal Installed!</h3>";
echo "<p>Next Step: Link a guest's user_id to their booking in your database, then log in as the guest and visit <code>pages/guest/dashboard.html</code></p>";
?>