<?php
// views/film_detail.php
// View ini digunakan untuk menampilkan detail film dan jadwal tayangnya.
// Variabel yang diharapkan: $film (array detail film), $jadwal (array jadwal tayang film)
// Variabel-variabel ini disediakan oleh FilmController->detail()

// Pesan sukses atau error dari sesi (jika ada)
if (isset($_SESSION['error_message'])) {
    echo "<p class='message error'>" . htmlspecialchars($_SESSION['error_message']) . "</p>";
    unset($_SESSION['error_message']);
}
if (isset($_SESSION['success_message'])) {
    echo "<p class='message success'>" . htmlspecialchars($_SESSION['success_message']) . "</p>";
    unset($_SESSION['success_message']);
}

// Pastikan $film tidak kosong sebelum mencoba mengakses datanya
if (!isset($film) || !is_array($film)) {
    echo "<p class='message error'>Data film tidak ditemukan.</p>";
    return; // Hentikan eksekusi jika data film tidak ada
}

// Cek status login dan peran pengguna
$is_logged_in = isset($_SESSION['user_id']);
$is_admin = $is_logged_in && $_SESSION['user_role'] === 'admin';

// Helper untuk format tanggal untuk tab
date_default_timezone_set('Asia/Jakarta');
$today = new DateTime();
$today->setTime(0, 0, 0); // Reset waktu ke awal hari
$bekasiTimezone = new DateTimeZone('Asia/Jakarta'); // Define timezone for consistency

$dates_for_tabs = [];
for ($i = 0; $i < 7; $i++) { // 7 hari ke depan
    $date = clone $today;
    $date->modify("+$i day");
    $dates_for_tabs[] = $date;
}

// Group jadwal berdasarkan tanggal, studio, lalu waktu untuk tampilan rapi
$grouped_jadwal = [];
foreach ($jadwal as $j) {
    $grouped_jadwal[$j['tanggal_tayang']][$j['studio_id']][] = $j;
}
ksort($grouped_jadwal); // Urutkan tanggal
?>

<div class="film-detail-container">
    <h1 class="film-title"><?php echo htmlspecialchars($film['judul']); ?></h1>

    <div class="film-header-info">
        <div class="film-ratings">
            <span class="rating-value">6.160 Vote</span>
            <span class="rating-separator">|</span>
            <span class="audience-count">28.079 Orang</span>
        </div>
    </div>

    <div class="tab-buttons">
        <div class="tab-button active" data-tab="sinopsis">SINOPSIS</div>
        <div class="tab-button" data-tab="jadwal">JADWAL</div>
    </div>

    <div class="tab-content-wrapper">
        <div id="sinopsis-content" class="tab-content active">
            <div class="film-content-flex">
                <div class="film-poster">
                    <?php if ($film['cover']): ?>
                        <img src="assets/img/film_covers/<?= htmlspecialchars(basename($film['cover'])) ?>" alt="Cover Film">
                    <?php else: ?>
                        <div class="no-cover-placeholder">No Cover</div>
                    <?php endif; ?>
                </div>
                <div class="film-details">
                    <p><strong>Kategori:</strong> <span class="detail-value"><?php echo htmlspecialchars($film['kategori']); ?></span></p>
                    <p><strong>Studio:</strong> <span class="detail-value"><?php echo htmlspecialchars($film['studio_nama']); ?></span></p>
                    <p><strong>Tanggal Rilis:</strong> <span class="detail-value"><?php echo htmlspecialchars($film['tanggal_rilis']); ?></span></p>
                    <h3>Sinopsis:</h3>
                    <p class="film-sinopsis"><?php echo nl2br(htmlspecialchars($film['sinopsis'])); ?></p>
                </div>
            </div>
        </div>

        <div id="jadwal-content" class="tab-content">
            <div class="date-tabs-nav">
                <?php $current_date_tab = new DateTime(null, $bekasiTimezone); ?>
                <?php foreach ($dates_for_tabs as $idx => $date_obj): ?>
                    <?php
                    $is_today = ($date_obj->format('Y-m-d') === $current_date_tab->format('Y-m-d'));
                    $day_name = '';
                    if ($is_today) {
                        $day_name = 'HARI INI';
                    } else {
                        $day_map = [
                            'Sun' => 'MIN', 'Mon' => 'SEN', 'Tue' => 'SEL', 'Wed' => 'RAB',
                            'Thu' => 'KAM', 'Fri' => 'JUM', 'Sat' => 'SAB'
                        ];
                        $day_name_short_en = $date_obj->format('D');
                        $day_name = $day_map[$day_name_short_en] ?? $day_name_short_en;
                    }
                    $active_class = ($idx === 0) ? 'active' : ''; // Hari ini atau hari pertama aktif secara default
                    ?>
                    <div class="date-tab-item <?= $active_class ?>" data-date="<?= $date_obj->format('Y-m-d') ?>">
                        <span class="date-number"><?= $date_obj->format('d') ?></span>
                        <span class="date-month"><?= $date_obj->format('M') ?></span>
                        <span class="date-day-name <?= $is_today ? 'today-label' : '' ?>"><?= $day_name ?></span>
                    </div>
                <?php endforeach; ?>
            </div>

            <div class="jadwal-list-container" id="jadwal-list-display">
                </div>
        </div>
    </div>

    <div class="bottom-back-button">
        <a href="index.php?hal=home" class="back-to-list-button">
            Kembali ke Home
        </a>
    </div>
</div>

<style>
    /* Global/Base Styles (re-confirm from previous versions) */
    body {
        font-family: 'Poppins', sans-serif;
        background-color: #f0f2f5;
        color: #333;
        line-height: 1.6;
        margin: 0;
        padding: 0;
    }

    /* Message Styling (Success/Error) */
    .message {
        padding: 12px 20px;
        margin: 20px auto;
        border-radius: 8px;
        text-align: center;
        font-weight: 600;
        max-width: 900px;
        box-sizing: border-box;
        animation: fadeInDown 0.5s ease-out;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    @keyframes fadeInDown {
        from { opacity: 0; transform: translateY(-20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .message.error {
        background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb;
    }
    .message.success {
        background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb;
    }

    /* Main Container */
    .film-detail-container {
        max-width: 950px; /* Lebar yang lebih besar untuk layout baru */
        margin: 30px auto;
        padding: 30px;
        background-color: #ffffff;
        border-radius: 12px;
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
        animation: fadeIn 0.8s ease-out;
    }
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .film-title {
        text-align: center;
        color: #1a2a3a;
        font-size: 2.8em;
        font-weight: 800;
        margin-bottom: 20px;
        line-height: 1.2;
    }

    .film-header-info {
        display: flex;
        justify-content: center;
        gap: 25px;
        margin-bottom: 30px;
        color: #6a737d;
        font-size: 0.95em;
    }
    .film-ratings .rating-value, .audience-count {
        font-weight: 600;
        color: #333;
    }
    .film-ratings .rating-separator {
        margin: 0 5px;
        color: #ccc;
    }

    /* Tabs Styling (Sinopsis / Jadwal) */
    .tab-buttons {
        display: flex;
        justify-content: center;
        border-bottom: 2px solid #e0e0e0;
        margin-bottom: 25px;
    }
    .tab-button {
        padding: 15px 30px;
        cursor: pointer;
        font-weight: 600;
        font-size: 1.1em;
        color: #6a737d;
        border-bottom: 2px solid transparent;
        transition: all 0.3s ease;
        flex-grow: 1;
        text-align: center;
    }
    .tab-button:hover {
        color: #007bff;
    }
    .tab-button.active {
        color: #007bff;
        border-bottom-color: #007bff;
        font-weight: 700;
    }

    .tab-content-wrapper {
        min-height: 400px;
    }
    .tab-content {
        display: none;
        animation: fadeInContent 0.5s ease-out;
    }
    .tab-content.active {
        display: block;
    }
    @keyframes fadeInContent {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }

    /* Sinopsis Tab Content */
    .film-content-flex {
        display: flex;
        flex-wrap: wrap;
        gap: 30px;
        align-items: flex-start;
    }
    .film-poster {
        flex: 0 0 auto;
        width: 300px;
        max-width: 100%;
        text-align: center;
    }
    .film-poster img {
        max-width: 100%;
        height: auto;
        border-radius: 12px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    .no-cover-placeholder {
        width: 300px;
        height: 450px;
        background-color: #e0e0e0;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 12px;
        font-size: 1.8em;
        color: #aaa;
        margin: 0 auto;
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }

    .film-details {
        flex: 1;
        min-width: 350px;
    }
    .film-details p {
        margin-bottom: 10px;
        font-size: 1.05em;
    }
    .film-details p strong {
        color: #333;
        min-width: 100px;
        display: inline-block;
    }
    .film-details .detail-value {
        color: #007bff;
        font-weight: 600;
    }
    .film-details h3 {
        color: #1a2a3a;
        font-size: 1.5em;
        margin-top: 25px;
        margin-bottom: 10px;
        border-bottom: 1px solid #eee;
        padding-bottom: 5px;
    }
    .film-sinopsis {
        line-height: 1.7;
        font-size: 1.05em;
        color: #555;
        white-space: pre-wrap;
    }

    /* Jadwal Tab Content */
    .date-tabs-nav {
        display: flex;
        justify-content: space-between;
        gap: 10px;
        margin-bottom: 30px;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
        padding-bottom: 10px;
        border-bottom: 1px solid #e0e0e0;
    }
    .date-tab-item {
        flex-shrink: 0;
        width: 90px;
        text-align: center;
        padding: 10px 5px;
        border-radius: 8px;
        cursor: pointer;
        background-color: #f8f9fa;
        border: 1px solid #e0e0e0;
        transition: all 0.2s ease;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    .date-tab-item:hover {
        background-color: #e9ecef;
        border-color: #c9d2d8;
    }
    .date-tab-item.active {
        background-color: #007bff;
        color: white;
        border-color: #007bff;
        box-shadow: 0 4px 10px rgba(0,123,255,0.2);
        transform: translateY(-2px);
    }
    .date-tab-item.active .date-number,
    .date-tab-item.active .date-month,
    .date-tab-item.active .date-day-name {
        color: white;
    }
    .date-number {
        font-size: 1.6em;
        font-weight: 700;
        line-height: 1;
        color: #333;
    }
    .date-month {
        font-size: 0.8em;
        text-transform: uppercase;
        color: #6a737d;
        margin-top: 3px;
    }
    .date-day-name {
        font-size: 0.9em;
        font-weight: 600;
        color: #333;
        margin-top: 5px;
    }
    /* "HARI INI" style */
    .date-tab-item.active .date-day-name,
    .date-tab-item:not(.active) .date-day-name.today-label {
        color: #dc3545; /* Merah untuk HARI INI */
        font-weight: 700;
    }
    .date-tab-item.active .date-day-name.today-label {
        color: white; /* Putih jika aktif */
    }

    /* Jadwal List Container */
    .jadwal-list-container {
        margin-top: 20px;
    }

    .cinema-schedule-card {
        background-color: #fff;
        border: 1px solid #e0e0e0;
        border-radius: 12px;
        margin-bottom: 25px;
        overflow: hidden;
        box-shadow: 0 4px 15px rgba(0,0,0,0.08);
    }
    .cinema-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        background-color: #f8f9fa;
        border-bottom: 1px solid #e9ecef;
    }
    .cinema-name {
        font-size: 1.15em;
        font-weight: 600;
        color: #333;
    }
    /* .cinema-info-logo { (Dihapus)
        background-color: #dc3545;
        color: white;
        padding: 5px 10px;
        border-radius: 5px;
        font-size: 0.8em;
        font-weight: bold;
        letter-spacing: 0.5px;
    } */

    .schedule-times-grid {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        padding: 20px;
    }
    .time-slot-button {
        background-color: #e0e0e0;
        color: #333;
        padding: 10px 18px;
        border-radius: 8px;
        text-decoration: none;
        font-weight: 600;
        font-size: 1.05em;
        transition: all 0.2s ease;
        border: 1px solid #ccc;
        min-width: 80px;
        text-align: center;
        /* cursor: pointer; (Akan diatur via JS untuk kasus non-disabled) */
    }
    .time-slot-button:hover:not(.disabled) { /* Hanya hover jika tidak disabled */
        background-color: #007bff;
        color: white;
        border-color: #007bff;
        box-shadow: 0 2px 8px rgba(0,123,255,0.2);
    }
    .time-slot-button.disabled { /* Style for disabled/unavailable times */
        background-color: #f0f0f0;
        color: #aaa;
        cursor: not-allowed;
        border-color: #e0e0e0;
        pointer-events: none; /* Disable clicks */
        text-decoration: line-through; /* Optional: tambahkan garis coret */
    }
    .time-slot-button.past-showtime { /* Specific style for past showtimes */
        background-color: #fcebeb; /* Light red */
        color: #dc3545; /* Red text */
        border-color: #f5c6cb;
    }


    .bottom-banner {
        background-color: #e6f2ff; /* Light blue background */
        color: #007bff;
        padding: 15px 20px;
        display: flex;
        justify-content: center; /* Center the text */
        align-items: center;
        font-size: 0.9em;
        border-top: 1px solid #cce0ff;
    }
    .banner-text {
        font-weight: 500;
        text-align: center;
        flex-grow: 1; /* Biarkan teks mengisi ruang */
    }
    /* .buy-ticket-btn { (Dihapus) */
    /* ... */
    /* } */

    .no-jadwal-message {
        text-align: center;
        color: #666;
        padding: 40px 20px;
        background-color: #fefefe;
        border: 1px dashed #e0e0e0;
        border-radius: 10px;
        margin-top: 20px;
    }

    /* Bottom back button (now 'Kembali ke Home' button) */
    .bottom-back-button {
        text-align: center;
        margin-top: 40px;
    }
    .back-to-list-button {
        background-color: #007bff; /* Primary blue */
        color: white;
        padding: 12px 25px;
        border-radius: 30px;
        text-decoration: none;
        font-weight: 600;
        transition: background-color 0.3s ease, transform 0.2s ease;
        box-shadow: 0 3px 8px rgba(0, 123, 255, 0.2);
        border: none; /* Make it a button style */
        cursor: pointer;
        display: inline-block; /* Ensure it behaves like a link/button */
    }
    .back-to-list-button:hover {
        background-color: #0056b3;
        transform: translateY(-2px);
    }

    /* Responsive Adjustments */
    @media (max-width: 768px) {
        .film-detail-container {
            margin: 20px 15px;
            padding: 20px;
        }
        .film-title {
            font-size: 2.2em;
        }
        .film-header-info {
            flex-direction: column;
            gap: 10px;
            align-items: center;
        }
        .tab-button {
            padding: 12px 20px;
            font-size: 1em;
        }
        .film-content-flex {
            flex-direction: column;
            align-items: center;
        }
        .film-poster, .no-cover-placeholder {
            width: 250px;
            height: auto;
        }
        .film-details {
            min-width: unset;
            width: 100%;
        }
        .film-details h3 {
            font-size: 1.3em;
        }
        .film-sinopsis {
            font-size: 1em;
        }
        .date-tabs-nav {
            justify-content: flex-start;
            padding: 0 10px 10px 10px;
            margin-left: -15px;
            margin-right: -15px;
        }
        .date-tab-item {
            width: 80px;
            padding: 8px 3px;
        }
        .date-number {
            font-size: 1.4em;
        }
        .date-month, .date-day-name {
            font-size: 0.75em;
        }
        /* Filters bar removed entirely */
        .cinema-schedule-card {
            margin-bottom: 20px;
        }
        .schedule-times-grid {
            padding: 15px;
            gap: 8px;
            justify-content: center;
        }
        .time-slot-button {
            padding: 8px 12px;
            font-size: 0.95em;
            min-width: 70px;
        }
        .bottom-banner {
            flex-direction: column;
            gap: 10px;
            text-align: center;
        }
        /* .buy-ticket-btn removed */
    }
    @media (max-width: 480px) {
        .film-title {
            font-size: 2em;
        }
        .tab-button {
            font-size: 0.9em;
            padding: 10px 15px;
        }
        .date-tab-item {
            width: 70px;
            font-size: 0.9em;
        }
    }
</style>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Tab switching (Sinopsis / Jadwal)
    const tabButtons = document.querySelectorAll('.tab-button');
    const tabContents = document.querySelectorAll('.tab-content');

    tabButtons.forEach(button => {
        button.addEventListener('click', () => {
            const tabId = button.dataset.tab;

            tabButtons.forEach(btn => btn.classList.remove('active'));
            tabContents.forEach(content => content.classList.remove('active'));

            button.classList.add('active');
            document.getElementById(`${tabId}-content`).classList.add('active');
        });
    });

    // Date tabs (with frontend filtering based on PHP-provided data)
    const dateTabItems = document.querySelectorAll('.date-tab-item');
    const jadwalListDisplay = document.getElementById('jadwal-list-display');
    // PHP variable for all grouped jadwal data
    const allJadwalData = <?= json_encode($grouped_jadwal); ?>;
    
    // Helper function for HTML escaping in JavaScript
    function htmlspecialchars(str) {
        if (typeof str !== 'string' && typeof str !== 'number') return str;
        str = String(str);
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return str.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

    // Function to render schedules for a given date
    function renderJadwal(selectedDate) {
        const jadwalForSelectedDate = allJadwalData[selectedDate] || {};
        let htmlContent = '';

        if (Object.keys(jadwalForSelectedDate).length > 0) {
            // Sort studios alphabetically for consistent display
            const sortedStudioIds = Object.keys(jadwalForSelectedDate).sort((a, b) => {
                // Safely access studio_nama, fallback if data is missing (though should be present)
                const studioNameA = jadwalForSelectedDate[a][0] ? jadwalForSelectedDate[a][0].studio_nama : '';
                const studioNameB = jadwalForSelectedDate[b][0] ? jadwalForSelectedDate[b][0].studio_nama : '';
                return studioNameA.localeCompare(studioNameB);
            });

            sortedStudioIds.forEach(studioId => {
                const jadwalByStudio = jadwalForSelectedDate[studioId];
                if (jadwalByStudio && jadwalByStudio.length > 0) {
                    // Sort showtimes within each studio by time
                    jadwalByStudio.sort((a, b) => {
                        const timeA = new Date(`2000/01/01 ${a.waktu_tayang}`);
                        const timeB = new Date(`2000/01/01 ${b.waktu_tayang}`);
                        return timeA - timeB;
                    });

                    let timeSlotsHtml = '';
                    const currentTime = new Date(<?php echo time() * 1000; ?>); // Current server time in milliseconds
                    currentTime.setMilliseconds(0); // Optional: remove milliseconds for cleaner comparison

                    jadwalByStudio.forEach(j => {
                        // Construct showtime with correct date to compare
                        const showtimeDateTime = new Date(`${j.tanggal_tayang}T${j.waktu_tayang}:00`); // Ensure proper format for parsing
                        
                        const isPastShowtime = showtimeDateTime < currentTime;
                        
                        // PHP variables passed to JS to check login/admin status
                        const isLoggedIn = <?= json_encode($is_logged_in); ?>;
                        const isAdmin = <?= json_encode($is_admin); ?>;

                        let buttonClass = 'time-slot-button';
                        let buttonTag = 'span'; // Default to span (disabled)
                        let linkHref = '';

                        if (isLoggedIn && !isAdmin && !isPastShowtime) {
                            buttonTag = 'a';
                            linkHref = `index.php?hal=pemesanan_form&jadwal_id=${htmlspecialchars(j.id)}`;
                            buttonClass += ' enabled-link'; // Add a class for enabled links
                        } else {
                            buttonClass += ' disabled';
                            if (isPastShowtime) {
                                buttonClass += ' past-showtime';
                            }
                        }

                        timeSlotsHtml += `
                            <${buttonTag} ${linkHref ? `href="${linkHref}"` : ''} class="${buttonClass}">
                                ${htmlspecialchars(j.waktu_tayang.substring(0, 5))}
                            </${buttonTag}>
                        `;
                    });

                    htmlContent += `
                        <div class="cinema-schedule-card">
                            <div class="cinema-header">
                                <span class="cinema-name">${htmlspecialchars(jadwalByStudio[0].studio_nama)}</span>
                                </div>
                            <div class="schedule-times-grid">
                                ${timeSlotsHtml}
                            </div>
                            <div class="bottom-banner">
                                <span class="banner-text">Silakan Pilih Jam sebelum memilih kursi</span>
                                </div>
                        </div>
                    `;
                }
            });
        } else {
            htmlContent = '<p class="no-jadwal-message">Tidak ada jadwal tayang untuk film ini pada tanggal yang dipilih.</p>';
        }
        jadwalListDisplay.innerHTML = htmlContent;
    }

    dateTabItems.forEach(dateTab => {
        dateTab.addEventListener('click', function() {
            dateTabItems.forEach(item => item.classList.remove('active'));
            this.classList.add('active');
            renderJadwal(this.dataset.date);
        });
    });

    // Initial render: Trigger click on the first date tab on load to display initial schedules
    // This ensures schedules are loaded for "HARI INI" by default.
    if (dateTabItems.length > 0) {
        dateTabItems[0].click();
    }

    // Event listener untuk tombol "Lihat Jadwal & Pesan Tiket" telah dihapus
    // karena sekarang menjadi tautan "Kembali ke Home" yang tidak memerlukan JS tambahan.
});
</script>