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

// Security Check
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') { 
    header("Location: " . BASE_URL . "index.php"); 
    exit(); 
}

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

// 2. Fetch Dramas and total unique evaluators
$report_query = "SELECT d.*, COUNT(DISTINCT r.user_id) as total_evaluators
                 FROM dramas d
                 LEFT JOIN ratings r ON d.id = r.drama_id
                 GROUP BY d.id 
                 ORDER BY d.created_at DESC";
$dramas = $pdo->query($report_query)->fetchAll();

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

<div class="container mt-4 mb-5">
    <div class="d-flex justify-content-between align-items-center mb-4 border-bottom border-secondary pb-3">
        <div>
            <h2 class="text-white fw-bold mb-0">Production Analytics</h2>
            <p class="text-white-50 small text-uppercase mb-0">Aggregated Episode Ratings</p>
        </div>
        <button onclick="window.print()" class="btn btn-outline-light btn-sm"><i class="bi bi-printer me-1"></i> Print Report</button>
    </div>

    <div class="row g-4">
        <?php foreach ($dramas as $row): 
            // 3. Fetch Dynamic Averages
            $avg_sql = "SELECT rp.parameter_name, rp.max_marks, AVG(rv.score) as avg_val
                        FROM rating_parameters rp
                        LEFT JOIN rating_values rv ON rp.id = rv.parameter_id
                        LEFT JOIN ratings r ON rv.rating_id = r.id
                        WHERE r.drama_id = ? 
                        GROUP BY rp.id";
            $stmt_avg = $pdo->prepare($avg_sql);
            $stmt_avg->execute([$row['id']]);
            $dynamic_stats = $stmt_avg->fetchAll();

            $total_overall = 0;
            foreach($dynamic_stats as $ds) { $total_overall += $ds['avg_val']; }
            
            // --- FIXED SQL-BASED EXPIRATION LOGIC ---
            // We ask MySQL to calculate the remaining seconds so Timezones don't break it
            $ep_stmt = $pdo->prepare("
                SELECT created_at,
                (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 created_at DESC LIMIT 1
            ");
            $ep_stmt->execute([$row['id']]);
            $latest_ep = $ep_stmt->fetch();

            if ($latest_ep) {
                $seconds_left = (int)$latest_ep['seconds_left'];
                $is_expired = ($seconds_left <= 0);
            } else {
                $is_expired = true;
                $seconds_left = 0;
            }
        ?>
        <div class="col-md-6 col-lg-4">
            <div class="card bg-dark border-secondary h-100 shadow-sm <?= ($latest_ep && !$is_expired) ? 'border-danger' : 'opacity-75' ?>">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <h5 class="text-white fw-bold mb-0"><?= htmlspecialchars($row['title']) ?></h5>
                        <span class="badge <?= ($latest_ep && !$is_expired) ? 'bg-danger' : 'bg-secondary' ?> x-small shadow text-uppercase">
                             <?= ($latest_ep && !$is_expired) ? 'Active Evaluation' : 'Closed' ?>
                        </span>
                    </div>
                    
                    <small class="text-muted d-block mb-3" style="font-size: 0.75rem;">
                        <?php if($latest_ep): ?>
                            Latest Update: <?= date('M d, g:i A', strtotime($latest_ep['created_at'])) ?>
                        <?php else: ?>
                            No episodes uploaded
                        <?php endif; ?>
                    </small>

                    <?php if($latest_ep && !$is_expired): ?>
                        <div class="bg-black p-2 rounded text-center border border-danger mb-4 shadow-sm">
                            <small class="text-danger d-block fw-bold" style="font-size: 0.7rem;">AUDIT WINDOW (<?= $deadline_hours ?>H)</small>
                            <span class="text-white fw-bold">
                                <?php 
                                    $h = floor($seconds_left / 3600);
                                    $m = floor(($seconds_left % 3600) / 60);
                                    echo "{$h}h {$m}m left";
                                ?>
                            </span>
                        </div>
                    <?php else: ?>
                        <div class="bg-black p-2 rounded text-center border border-secondary mb-4">
                            <small class="text-success d-block fw-bold" style="font-size: 0.7rem;">COMBINED AVERAGE SCORE</small>
                            <span class="text-white h4 fw-bold mb-0"><?= number_format($total_overall, 2) ?> <small class="text-muted" style="font-size: 0.8rem;">/ 100</small></span>
                        </div>
                    <?php endif; ?>

                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <small class="text-white-50 small">
                            <i class="bi bi-people-fill me-1"></i> <?= $row['total_evaluators'] ?> Participants
                        </small>
                    </div>

                    <a href="drama_reviews.php?id=<?= $row['id'] ?>" class="btn btn-outline-danger btn-sm w-100 fw-bold">VIEW DETAILED LOGS</a>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

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