<?php
include '../config/config.php';
include '../includes/auth.php';

$drama_id = isset($_GET['drama_id']) ? (int)$_GET['drama_id'] : 0;
$user_id = $_SESSION['user_id'];

// 1. FETCH DYNAMIC DEADLINE
$deadline_hours = $pdo->query("SELECT setting_value FROM site_settings WHERE setting_key = 'audit_deadline_hours'")->fetchColumn() ?: 24;

// 2. Fetch Drama Title
$stmt = $pdo->prepare("SELECT title FROM dramas WHERE id = ?");
$stmt->execute([$drama_id]);
$drama_title = $stmt->fetchColumn();

// 3. FETCH EPISODES WITH SQL-CALCULATED REMAINING TIME
// We calculate (created_at + deadline) - NOW() directly in MySQL
$stmt = $pdo->prepare("
    SELECT *, 
    (UNIX_TIMESTAMP(created_at) + ($deadline_hours * 3600)) AS expiry_unix,
    ((UNIX_TIMESTAMP(created_at) + ($deadline_hours * 3600)) - UNIX_TIMESTAMP()) AS seconds_left
    FROM episodes 
    WHERE drama_id = ? 
    ORDER BY ep_number ASC
");
$stmt->execute([$drama_id]);
$episodes = $stmt->fetchAll();

include '../includes/header.php';
?>

<div class="container mt-4 mb-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="text-white fw-bold mb-0"><?= htmlspecialchars($drama_title) ?></h2>
            <p class="text-white-50 small text-uppercase">Audit Window: <?= $deadline_hours ?> Hour(s)</p>
        </div>
        <a href="dashboard.php" class="btn btn-outline-light btn-sm">Back to Dashboard</a>
    </div>

    <div class="row g-4">
        <?php foreach ($episodes as $ep): 
            $time_left = (int)$ep['seconds_left'];
            $is_expired = ($time_left <= 0);
            $expiry_unix = $ep['expiry_unix'];

            $check = $pdo->prepare("SELECT score FROM ratings WHERE user_id = ? AND episode_id = ?");
            $check->execute([$user_id, $ep['id']]);
            $has_rated = $check->fetch();
        ?>
            <div class="col-md-6 col-lg-4">
                <div class="card bg-dark border-secondary h-100 shadow-sm <?= $is_expired ? 'opacity-75' : 'border-danger' ?>">
                    <div class="card-body p-4 d-flex flex-column">
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <h4 class="text-white fw-bold mb-0">Episode <?= $ep['ep_number'] ?></h4>
                            <?php if($has_rated): ?>
                                <span class="badge bg-success">Rated</span>
                            <?php endif; ?>
                        </div>

                        <div class="p-2 mb-4 rounded border <?= $is_expired ? 'border-secondary text-white-50' : 'border-danger text-danger' ?>" style="background: rgba(0,0,0,0.4);">
                            <div class="d-flex align-items-center small fw-bold">
                                <i class="bi bi-clock-history me-2"></i>
                                <span class="countdown-timer" data-expiry="<?= $expiry_unix ?>">
                                    <?php 
                                        if ($is_expired) {
                                            echo "Expired";
                                        } else {
                                            $h = floor($time_left / 3600);
                                            $m = floor(($time_left % 3600) / 60);
                                            $s = $time_left % 60;
                                            echo "{$h}h {$m}m {$s}s Remaining";
                                        }
                                    ?>
                                </span>
                            </div>
                        </div>

                        <div class="mt-auto">
                            <?php if(!$is_expired): ?>
                                <a href="watch.php?id=<?= $ep['id'] ?>" class="btn btn-danger w-100 fw-bold shadow-sm">
                                    Watch & Evaluate
                                </a>
                            <?php else: ?>
                                <button class="btn btn-secondary w-100 fw-bold disabled" disabled>Window Expired</button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<script>
function updateTimers() {
    const now = Math.floor(Date.now() / 1000);
    document.querySelectorAll('.countdown-timer').forEach(timer => {
        const expiry = parseInt(timer.getAttribute('data-expiry'));
        const timeLeft = expiry - now;

        if (timeLeft <= 0) {
            timer.innerHTML = "Expired";
            return;
        }

        const h = Math.floor(timeLeft / 3600);
        const m = Math.floor((timeLeft % 3600) / 60);
        const s = timeLeft % 60;
        timer.innerHTML = h + "h " + m + "m " + s + "s Remaining";
    });
}
setInterval(updateTimers, 1000);
</script>

<?php include '../includes/footer.php'; ?>