<!DOCTYPE html>
<html dir="ltr" lang="en-US">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="description" content="Reservations - Granny Restaurant Manager">
    <link href="../assets/images/favicon/favicon.png" rel="icon">

    <link href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="manager-styles.css">

    <title>Reservations - Granny Restaurant</title>

    <style>
        .main-content {
            padding: 30px 30px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            background: white;
            padding: 20px 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .page-header h1 {
            color: #1e3c72;
            font-size: 28px;
        }



        .controls {
            background: white;
            padding: 20px 30px;
            border-radius: 10px;
            margin-bottom: 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .control-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        .control-group label {
            font-size: 12px;
            color: #666;
            font-weight: 600;
            text-transform: uppercase;
        }

        .control-group input,
        .control-group select {
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-family: inherit;
            font-size: 14px;
            min-width: 200px;
        }

        .bookings-table {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            overflow: hidden;
            overflow-x: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 900px;
        }

        thead {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
        }

        th {
            padding: 15px 20px;
            text-align: left;
            font-weight: 600;
            font-size: 13px;
            text-transform: uppercase;
            white-space: nowrap;
        }

        td {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            white-space: nowrap;
        }

        tbody tr:hover {
            background: #f8f9fa;
        }

        .booking-id {
            font-weight: 600;
            color: #1e3c72;
        }

        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
            text-align: center;
            min-width: 100px;
        }

        .status-pending {
            background: #cce5ff;
            color: #004085;
        }

        .status-confirmed {
            background: #d4edda;
            color: #155724;
        }

        .status-checked_in {
            background: #d1ecf1;
            color: #0c5460;
        }

        .status-checked_out {
            background: #c3e6cb;
            color: #155724;
        }

        .status-cancelled {
            background: #f8d7da;
            color: #721c24;
        }

        .status-no_show {
            background: #e2e3e5;
            color: #383d41;
        }

        .actions {
            display: flex;
            gap: 8px;
        }

        .btn {
            padding: 8px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background: #2a5298;
            color: white;
        }

        .btn-primary:hover {
            background: #1e3c72;
        }

        .btn-success {
            background: #28a745;
            color: white;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-warning {
            background: #ffc107;
            color: #333;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }

        .empty-state i {
            font-size: 48px;
            margin-bottom: 15px;
            opacity: 0.5;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .stat-title {
            font-size: 12px;
            color: #666;
            text-transform: uppercase;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: #1e3c72;
        }

        /* Responsive Stats Grid */
        @media (max-width: 1440px) and (min-width: 1025px) {
            .stats {
                grid-template-columns: repeat(3, 1fr);
            }
        }

        @media (max-width: 1024px) and (min-width: 769px) {
            .stats {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .stats {
                grid-template-columns: 1fr;
            }

            .controls {
                flex-direction: column;
                align-items: stretch;
            }

            .control-group input,
            .control-group select {
                min-width: auto;
                width: 100%;
            }

            .bookings-table {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            table {
                font-size: 12px;
                min-width: 100%;
            }

            th, td {
                padding: 10px 8px;
                white-space: nowrap;
            }

            th {
                font-size: 11px;
            }

            .actions {
                flex-wrap: wrap;
                gap: 4px;
            }

            .btn {
                padding: 6px 8px;
                font-size: 11px;
            }

            .page-header {
                flex-direction: column;
                align-items: flex-start;
                padding: 15px;
            }

            .page-header h1 {
                font-size: 20px;
            }

            .main-content {
                padding: 15px 15px;
            }

            .container {
                padding: 0;
            }
        }

        @media (max-width: 480px) {
            .bookings-table {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            table {
                font-size: 11px;
            }

            th, td {
                padding: 8px 6px;
            }

            th {
                font-size: 10px;
            }

            .btn {
                padding: 5px 6px;
                font-size: 10px;
            }

            .stat-value {
                font-size: 24px;
            }

            .page-header h1 {
                font-size: 18px;
            }
        }
    </style>
</head>

<body>
    <div class="dashboard-container">
        <?php include 'sidebar.php'; ?>
        <div class="main-content">
            <div class="container">
                <div class="page-header">
            <h1><i class="fas fa-calendar-check"></i> Reservations Management</h1>
        </div>

        <!-- Statistics -->
        <div class="stats" id="statsContainer">
            <div class="stat-card">
                <div class="stat-title">Today's Bookings</div>
                <div class="stat-value" id="totalBookings">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">Confirmed</div>
                <div class="stat-value" id="confirmedBookings">0</div>
            </div>
            <div class="stat-card">
                <div class="stat-title">Total Guests</div>
                <div class="stat-value" id="totalGuests">0</div>
            </div>
        </div>

        <!--Controls -->
        <div class="controls">
            <div class="control-group">
                <label>Date</label>
                <input type="date" id="filterDate" onchange="filterBookings()">
            </div>

            <div class="control-group">
                <label>Status</label>
                <select id="filterStatus" onchange="filterBookings()">
                    <option value="">All Status</option>
                    <option value="pending">Pending</option>
                    <option value="confirmed">Confirmed</option>
                    <option value="checked_in">Checked In</option>
                    <option value="checked_out">Checked Out</option>
                    <option value="cancelled">Cancelled</option>
                    <option value="no_show">No Show</option>
                </select>
            </div>

            <div class="control-group">
                <label>&nbsp;</label>
                <button class="btn btn-primary" onclick="refreshBookings()">
                    <i class="fas fa-sync"></i> Refresh
                </button>
            </div>
        </div>

        <!-- Bookings Table -->
        <div class="bookings-table">
            <table id="bookingsTable">
                <thead>
                    <tr>
                        <th>Booking ID</th>
                        <th>Customer Name</th>
                        <th>Email</th>
                        <th>Date & Time</th>
                        <th>Guests</th>
                        <th>Status</th>
                        <th>Tables</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="bookingsBody">
                    <tr>
                        <td colspan="8" style="text-align: center; padding: 40px;">
                            <i class="fas fa-spinner fa-spin"></i> Loading...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <script>
        let allBookings = [];

        $(document).ready(function() {
            checkAuthentication();
            setDateFilter();
            loadBookings();
        });

        function checkAuthentication() {
            if (!localStorage.getItem('manager_id')) {
                window.location.href = 'login.php';
            }
        }

        function setDateFilter() {
            const today = new Date().toISOString().split('T')[0];
            $('#filterDate').val(today);
        }

        function loadBookings() {
            const date = $('#filterDate').val();
            const managerId = localStorage.getItem('manager_id');

            $.ajax({
                url: `../backend/manager_bookings_api.php?action=today&manager_id=${managerId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        allBookings = response.data;
                        displayBookings(allBookings);
                        loadStats();
                    }
                }
            });
        }

        function displayBookings(bookings) {
            if (bookings.length === 0) {
                $('#bookingsBody').html(`
                    <tr>
                        <td colspan="8">
                            <div class="empty-state">
                                <i class="fas fa-inbox"></i>
                                <p>No bookings found</p>
                            </div>
                        </td>
                    </tr>
                `);
                return;
            }

            let html = '';
            bookings.forEach(booking => {
                const dateTime = new Date(booking.booking_date + 'T' + booking.slot_time).toLocaleString();
                const statusClass = `status-${booking.status}`;
                
                // Get today's date in YYYY-MM-DD format
                const today = new Date().toISOString().split('T')[0];
                const bookingDate = booking.booking_date;
                const isBookingToday = bookingDate === today;

                html += `
                    <tr>
                        <td class="booking-id">#${booking.id}</td>
                        <td>${booking.name}</td>
                        <td>${booking.email}</td>
                        <td>${dateTime}</td>
                        <td>${booking.guests}</td>
                        <td><span class="status-badge ${statusClass}">${booking.status.replace('_', ' ').toUpperCase()}</span></td>
                        <td>${booking.table_numbers || 'Not allocated'}</td>
                        <td>
                            <div class="actions">
                                <button class="btn btn-primary" onclick="viewBooking(${booking.id})">
                                    <i class="fas fa-eye"></i> View
                                </button>
                                ${booking.status === 'pending' ? `
                                    <button class="btn btn-success" onclick="confirmBooking(${booking.id})">
                                        <i class="fas fa-check"></i> Confirm
                                    </button>
                                ` : ''}
                                ${booking.status === 'confirmed' ? `
                                    <button class="btn btn-primary" onclick="checkinBooking(${booking.id})" 
                                        ${!isBookingToday ? 'disabled style="opacity: 0.5; cursor: not-allowed;" title="Check-in only available on the booking date"' : ''}>
                                        <i class="fas fa-sign-in-alt"></i> Check In
                                    </button>
                                ` : ''}
                                ${booking.status !== 'cancelled' && booking.status !== 'no_show' ? `
                                    <button class="btn btn-danger" onclick="cancelBooking(${booking.id})">
                                        <i class="fas fa-times"></i> Cancel
                                    </button>
                                ` : ''}
                            </div>
                        </td>
                    </tr>
                `;
            });

            $('#bookingsBody').html(html);
        }

        function loadStats() {
            const today = new Date().toISOString().split('T')[0];
            const managerId = localStorage.getItem('manager_id');
            $.ajax({
                url: `../backend/manager_bookings_api.php?action=get_booking_stats&date=${today}&manager_id=${managerId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        const data = response.data;
                        $('#totalBookings').text(data.total_bookings);
                        $('#totalGuests').text(data.total_guests);

                        const confirmed = data.by_status.find(s => s.status === 'confirmed');
                        $('#confirmedBookings').text(confirmed ? confirmed.count : 0);
                    }
                }
            });
        }

        function filterBookings() {
            const selectedDate = $('#filterDate').val();
            const status = $('#filterStatus').val();
            const managerId = localStorage.getItem('manager_id');

            $.ajax({
                url: `../backend/manager_bookings_api.php?action=today&date=${selectedDate}&manager_id=${managerId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        allBookings = response.data;
                        
                        // Apply status filter if selected
                        let filtered = allBookings;
                        if (status) {
                            filtered = allBookings.filter(b => b.status === status);
                        }
                        
                        displayBookings(filtered);
                    }
                },
                error: function() {
                    $('#bookingsBody').html(`
                        <tr>
                            <td colspan="8">
                                <div class="empty-state">
                                    <i class="fas fa-exclamation-circle"></i>
                                    <p>Error loading bookings</p>
                                </div>
                            </td>
                        </tr>
                    `);
                }
            });
        }

        function viewBooking(bookingId) {
            const managerId = localStorage.getItem('manager_id');
            $.ajax({
                url: `../backend/manager_bookings_api.php?action=get&booking_id=${bookingId}&manager_id=${managerId}`,
                method: 'GET',
                success: function(response) {
                    if (response.success) {
                        const booking = response.data;
                        const dateTime = new Date(booking.booking_date + 'T' + booking.slot_time).toLocaleString();

                        let tablesHtml = 'Not allocated';
                        if (booking.assigned_tables && booking.assigned_tables.length > 0) {
                            tablesHtml = booking.assigned_tables.map(t => `Table ${t.display_name || t.table_number}`).join(', ');
                        }

                        Swal.fire({
                            title: `Booking #${booking.id}`,
                            html: `
                                <div style="text-align: left;">
                                    <p><strong>Name:</strong> ${booking.name}</p>
                                    <p><strong>Email:</strong> ${booking.email}</p>
                                    <p><strong>Phone:</strong> ${booking.phone}</p>
                                    <p><strong>Date & Time:</strong> ${dateTime}</p>
                                    <p><strong>Guests:</strong> ${booking.guests}</p>
                                    <p><strong>Meal Type:</strong> ${booking.meal_type || 'N/A'}</p>
                                    <p><strong>Dietary Needs:</strong> ${booking.dietary_needs || 'None'}</p>
                                    <p><strong>Tables:</strong> ${tablesHtml}</p>
                                    <p><strong>Special Requests:</strong> ${booking.special_requests || 'None'}</p>
                                </div>
                            `
                        });
                    }
                }
            });
        }

        function confirmBooking(bookingId) {
            const managerId = localStorage.getItem('manager_id');
            Swal.fire({
                title: 'Confirm Booking?',
                text: 'Do you want to confirm this booking?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Confirm'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: `../backend/manager_bookings_api.php?action=confirm&manager_id=${managerId}`,
                        method: 'POST',
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify({ booking_id: bookingId }),
                        success: function(response) {
                            if (response.success) {
                                Swal.fire('Success', 'Booking confirmed', 'success');
                                loadBookings();
                            } else {
                                Swal.fire('Error', response.message, 'error');
                            }
                        }
                    });
                }
            });
        }

        function checkinBooking(bookingId) {
            const managerId = localStorage.getItem('manager_id');
            // Verify the booking is for today
            const today = new Date().toISOString().split('T')[0];
            const booking = allBookings.find(b => b.id == bookingId);
            
            if (!booking) {
                Swal.fire('Error', 'Booking not found', 'error');
                return;
            }
            
            if (booking.booking_date !== today) {
                Swal.fire('Error', 'Check-in is only allowed on the booking date', 'error');
                return;
            }
            
            Swal.fire({
                title: 'Check In Booking?',
                text: 'Customer has arrived?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#17a2b8',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Check In'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: `../backend/manager_bookings_api.php?action=checkin&manager_id=${managerId}`,
                        method: 'POST',
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify({ booking_id: bookingId }),
                        success: function(response) {
                            if (response.success) {
                                Swal.fire('Success', 'Booking checked in', 'success');
                                loadBookings();
                            }
                        }
                    });
                }
            });
        }

        function cancelBooking(bookingId) {
            const managerId = localStorage.getItem('manager_id');
            Swal.fire({
                title: 'Cancel Booking?',
                input: 'text',
                inputPlaceholder: 'Reason for cancellation',
                showCancelButton: true,
                confirmButtonColor: '#dc3545',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Cancel Booking'
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: `../backend/manager_bookings_api.php?action=cancel&manager_id=${managerId}`,
                        method: 'POST',
                        contentType: 'application/json',
                        dataType: 'json',
                        data: JSON.stringify({ 
                            booking_id: bookingId,
                            reason: result.value
                        }),
                        success: function(response) {
                            if (response.success) {
                                Swal.fire('Success', 'Booking cancelled', 'success');
                                loadBookings();
                            }
                        }
                    });
                }
            });
        }

        function refreshBookings() {
            loadBookings();
            Swal.fire('Success', 'Bookings refreshed', 'success');
        }

        // Refresh every 60 seconds
        setInterval(loadBookings, 60000);
    </script>

    <!-- Manager Sidebar Script -->
    <script src="manager-sidebar.js"></script>
</body>

</html>
