<?php
session_start();

// Check if user is logged in
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: login.php");
    exit;
}

    // Handle form submission
    $status = "";
    $message = "";
    
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the new prices from the form
        $newPrices = $_POST['prices'];
        
        // Check if prices.json exists and is writable, or if the directory is writable
        $file = 'prices.json';
        if ((file_exists($file) && !is_writable($file)) || (!file_exists($file) && !is_writable(__DIR__))) {
            $status = "error";
            $message = "Technical Error: Permission denied. The server cannot write to 'prices.json'.";
        } else {
            // Save to prices.json
            if (file_put_contents($file, json_encode($newPrices, JSON_PRETTY_PRINT))) {
                
                // VERIFICATION: Read back the file to ensure it matches
                // Clear state cache to ensure we get the fresh file content
                clearstatcache();
                $savedContent = file_get_contents($file);
                $savedData = json_decode($savedContent, true);

                // Simple comparison (arrays should match)
                // Note: We might need to be careful with type casting (strings vs ints) if PHP changes them
                // but json_encode/decode cycle usually preserves them enough for == comparison in PHP
                if ($savedData == $newPrices) {
                    $status = "success";
                    $message = "Price Verified & Updated Successfully on All Pages!";
                } else {
                    $status = "error";
                    $message = "Technical Error: Verification Failed. content mismatch.";
                }
            } else {
                $status = "error";
                $message = "Technical Error: Could not write to file.";
            }
        }
    }

    // Load current saved prices
    $savedPrices = [];
    if (file_exists('prices.json')) {
        $jsonContent = file_get_contents('prices.json');
        $savedPrices = json_decode($jsonContent, true) ?? [];
    }
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Admin Dashboard | Era Resorts</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
        <!-- Font Awesome -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
        <!-- Flatpickr for date selection -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
        <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
        <!-- SweetAlert2 for nice popups -->
        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <style>
            body {
                background-color: #121212;
                color: #eee;
                min-height: 100vh;
            }
            .navbar { border-bottom: 1px solid #333; }
            .card { background: #1e1e1e; border: 1px solid #333; }
            .form-control {
                background: #2a2a2a;
                border: 1px solid #444;
                color: #fff;
            }
            .form-control:focus {
                background: #2a2a2a;
                border-color: #c5a059;
                color: #fff;
            }
            .btn-save {
                background: linear-gradient(45deg, #c5a059, #e6c67d);
                border: none;
                color: #000;
                font-weight: bold;
            }
            .text-gold { color: #c5a059; }
        </style>
    </head>
    
    <body>
    
        <!-- Navbar -->
        <nav class="navbar navbar-dark bg-black py-3">
            <div class="container">
                <span class="navbar-brand mb-0 h1 text-gold">Era Resorts Admin (PHP)</span>
                <a href="logout.php" class="btn btn-outline-light btn-sm">Logout</a>
            </div>
        </nav>
    
        <div class="container py-5">
            <h2 class="mb-4">Manage Room Prices</h2>
            
            <form method="post" action="">
                <div class="row" id="roomList">
                    <!-- Room items will be injected here via JS using room-data.js 
                         and then values populated from PHP $savedPrices -->
                </div>
    
                <div class="mt-4 text-center">
                    <button type="submit" class="btn btn-save px-5 py-2">Save Changes</button>
                    <p class="text-muted mt-2 small">Changes are saved to the server and will update for all users.</p>
                </div>
            </form>
        </div>
        
        <?php if ($status === 'success'): ?>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                Swal.fire({
                    title: 'Success!',
                    text: '<?php echo $message; ?>',
                    icon: 'success',
                    confirmButtonColor: '#c5a059',
                    background: '#1e1e1e',
                    color: '#fff'
                });
            });
        </script>
        <?php elseif ($status === 'error'): ?>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                Swal.fire({
                    title: 'Error!',
                    text: '<?php echo $message; ?>',
                    icon: 'error',
                    confirmButtonColor: '#d33',
                    background: '#1e1e1e',
                    color: '#fff'
                });
            });
        </script>
        <?php endif; ?>

    <!-- Data Source for Structure -->
    <script src="../js/room-data.js"></script>

    <script>
        // PHP passes the saved prices to JS
        const savedPrices = <?php echo json_encode($savedPrices); ?>;
        
        const roomList = document.getElementById('roomList');

        roomData.forEach(room => {
            let actualPrice = room.basePrice;
            let offerPrice = room.basePrice;
            let isLocked = false;
            let lockedDates = '';
            
            if (savedPrices[room.id]) {
                if (typeof savedPrices[room.id] === 'object') {
                    actualPrice = savedPrices[room.id].actual || room.basePrice;
                    offerPrice = savedPrices[room.id].offer || room.basePrice;
                    // Properly handle true/'true'/1 string conversions for json decoded array
                    isLocked = savedPrices[room.id].locked === true || savedPrices[room.id].locked === "true" || savedPrices[room.id].locked == 1;
                    lockedDates = savedPrices[room.id].lockedDates || '';
                } else {
                    // Backwards compatibility with old flat number format
                    actualPrice = savedPrices[room.id];
                    offerPrice = savedPrices[room.id];
                }
            }
            
            const col = document.createElement('div');
            col.className = 'col-md-6 col-lg-4 mb-4';
            col.innerHTML = `
                <div class="card h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div>
                                <h5 class="card-title mb-0" style="color: #e6c67d;">${room.name}</h5>
                                <p class="text-muted small mb-0">ID: ${room.id}</p>
                            </div>
                            <div class="d-flex align-items-center">
                                <input type="hidden" name="prices[${room.id}][lockedDates]" id="locked-dates-${room.id}" value="${lockedDates}">
                                <!-- Keep legacy locked state hidden input for backward compatibility -->
                                <input type="hidden" name="prices[${room.id}][locked]" value="${isLocked ? 1 : 0}">
                                <i class="fas fa-calendar-times fs-4 text-danger" style="cursor: pointer;" id="cal-icon-${room.id}" title="Select Locked Dates"></i>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" style="color: #bbbbbb; font-weight: 500;">Actual Price (₹)</label>
                            <input type="number" class="form-control" 
                                name="prices[${room.id}][actual]" 
                                value="${actualPrice}">
                        </div>
                        <div class="mb-3">
                            <label class="form-label text-gold fw-bold">Offer Price (₹)</label>
                            <input type="number" class="form-control" 
                                name="prices[${room.id}][offer]" 
                                value="${offerPrice}">
                        </div>
                    </div>
                </div>
            `;
            roomList.appendChild(col);
        });

        // Initialize Flatpickr after pushing elements
        setTimeout(() => {
            roomData.forEach(room => {
                flatpickr(`#cal-icon-${room.id}`, {
                    mode: "multiple",
                    dateFormat: "Y-m-d",
                    defaultDate: document.getElementById(`locked-dates-${room.id}`).value.split(",").filter(d => d.trim() !== ""),
                    onChange: function(selectedDates, dateStr, instance) {
                        document.getElementById(`locked-dates-${room.id}`).value = dateStr;
                    }
                });
            });
        }, 100);
    </script>
</body>
</html>
