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

// Ensure session is started and admin check is performed
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') { 
    header("Location: " . BASE_URL . "index.php"); 
    exit(); 
}

$report_query = "SELECT d.*, 
                 COUNT(r.id) as total_reviews, 
                 AVG(r.score) as avg_score
                 FROM dramas d
                 LEFT JOIN episodes e ON d.id = e.drama_id
                 LEFT JOIN ratings r ON e.id = r.episode_id
                 GROUP BY d.id ORDER BY d.title ASC";
$dramas = $pdo->query($report_query)->fetchAll();

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

<div class="container mt-4">
    <h2 class="text-white fw-bold mb-4">Teledrama Analytics</h2>
    <div class="row g-4">
        <?php foreach ($dramas as $row): 
            // 1. Fix: Use consistent variable names
            // Use null coalescing to prevent PHP 8.2 round() errors
            $score = round($row['avg_score'] ?? 0, 1);
            
            // 2. Logic: Now $score is defined, so $badge logic works correctly
            $badge_class = ($score >= 7) ? 'bg-success' : (($score >= 4) ? 'bg-warning' : 'bg-danger');
        ?>
        <div class="col-md-4">
            <div class="card bg-dark border-secondary h-100 shadow">
                <img src="../uploads/thumbnails/<?= htmlspecialchars($row['thumbnail']) ?>" class="card-img-top" style="height:180px; object-fit:cover;">
                <div class="card-body">
                    <h5 class="text-white fw-bold"><?= htmlspecialchars($row['title']) ?></h5>
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <span class="badge <?= $badge_class ?> fs-6"><?= $score ?> / 10</span>
                        <small class="text-muted"><?= $row['total_reviews'] ?> Total Reviews</small>
                    </div>

                    <div class="progress mb-3" style="height: 8px; background-color: #333;">
                        <div class="progress-bar <?= $badge_class ?>" role="progressbar" style="width: <?= ($score * 10) ?>%"></div>
                    </div>

                    <a href="episode_details.php?drama_id=<?= $row['id'] ?>" class="btn btn-danger w-100">
                        View Episode-wise Data
                    </a>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

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