<?php
include '../config/config.php';
include '../includes/auth.php'; // Ensure admin only

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

// 1. Fetch Drama Details
$stmt = $pdo->prepare("SELECT * FROM dramas WHERE id = ?");
$stmt->execute([$drama_id]);
$drama = $stmt->fetch();

if (!$drama) { die("Teledrama not found."); }

// 2. Mandrill Notification Function (Replaced old Mailchimp logic)
function notifyEpMandrill($pdo, $dName, $epNo) {
    $mandrill_key = 'md-Vjza4GhgRIEoal3e-KKkmw'; // Your verified key
    $url = "https://mandrillapp.com/api/1.0/messages/send.json";

    $members = $pdo->query("SELECT email FROM users WHERE role = 'member' AND email IS NOT NULL")->fetchAll(PDO::FETCH_COLUMN);
    
    if (empty($members)) return;

    $recipients = array_map(function($email) {
        return ["email" => $email, "type" => "bcc"];
    }, $members);

    $html = "
        <div style='font-family: Arial; padding: 20px; border: 2px solid #e50914; max-width: 600px;'>
            <h2 style='color: #e50914;'>New Episode Available</h2>
            <p>Episode <strong>$epNo</strong> of <b>$dName</b> has been uploaded to the portal for evaluation.</p>
            <p>Please log in to the dashboard to submit your ratings.</p>
        </div>";

    $data = [
        "key" => $mandrill_key,
        "message" => [
            "html" => $html,
            "subject" => "New Episode Alert: $dName - Ep $epNo",
            "from_email" => "teldramaratings@test.athavaneng.com",
            "from_name" => "Swarnavahini Admin",
            "to" => [["email" => "admin@test.athavaneng.com", "type" => "to"]], // Main 'to'
            "bcc" => $recipients // All members in BCC
        ]
    ];

    $options = [
        'http' => [
            'header'  => "Content-type: application/json\r\n",
            'method'  => 'POST',
            'content' => json_encode($data),
            'ignore_errors' => true
        ],
        'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]
    ];

    $context = stream_context_create($options);
    @file_get_contents($url, false, $context);
}

// 3. Handle Add Episode
if (isset($_POST['add_episode'])) {
    $ep_number = $_POST['ep_number'];
    $iframe = $_POST['iframe_code'];

    $insert = $pdo->prepare("INSERT INTO episodes (drama_id, ep_number, iframe_code) VALUES (?, ?, ?)");
    if ($insert->execute([$drama_id, $ep_number, $iframe])) {
        notifyEpMandrill($pdo, $drama['title'], $ep_number);
        header("Location: view_episodes.php?id=$drama_id&success=1");
        exit();
    }
}

// 4. Fetch Episode List
$episodes = $pdo->prepare("SELECT * FROM episodes WHERE drama_id = ? ORDER BY ep_number ASC");
$episodes->execute([$drama_id]);
$epList = $episodes->fetchAll();

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

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-1">
                    <li class="breadcrumb-item"><a href="manage_dramas.php" class="text-danger text-decoration-none">Teledramas</a></li>
                    <li class="breadcrumb-item active text-white-50">Episodes</li>
                </ol>
            </nav>
            <h2 class="text-white fw-bold m-0"><?= $drama['title'] ?></h2>
        </div>
        <button class="btn btn-danger fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#addEpModal">
            <i class="bi bi-plus-lg me-1"></i> Add Episode
        </button>
    </div>

    <?php if(isset($_GET['success'])): ?>
        <div class="alert alert-success border-0 shadow-sm bg-success text-white small mb-4">
            <i class="bi bi-check-circle me-2"></i>New episode added and committee notified.
        </div>
    <?php endif; ?>

    <?php if(isset($_GET['updated'])): ?>
        <div class="alert alert-info border-0 shadow-sm bg-info text-dark fw-bold small mb-4">
            <i class="bi bi-info-circle me-2"></i>Episode details updated successfully.
        </div>
    <?php endif; ?>

    <div class="row">
        <?php if(empty($epList)): ?>
            <div class="col-12 text-center py-5">
                <p class="text-muted">No episodes found for this teledrama.</p>
            </div>
        <?php else: ?>
            <?php foreach ($epList as $ep): ?>
            <div class="col-md-4 mb-4">
                <div class="card bg-dark border-secondary h-100 shadow-sm overflow-hidden">
                    <div class="card-header bg-black border-secondary d-flex justify-content-between">
                        <span class="text-white fw-bold">Episode <?= $ep['ep_number'] ?></span>
                
                    </div>
                    <div class="card-body p-2">
                        <div class="ratio ratio-16x9 bg-black rounded border border-secondary mb-3">
                            <?= $ep['iframe_code'] ?>
                        </div>
                        <a href="edit_episode.php?id=<?= $ep['id'] ?>" class="btn btn-sm btn-outline-light w-100 fw-bold">
                            <i class="bi bi-pencil-square me-1"></i> Edit Details
                        </a>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<div class="modal fade" id="addEpModal" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content bg-dark text-white border-secondary" method="POST">
            <div class="modal-header border-secondary bg-black">
                <h5 class="modal-title">Upload Episode</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="small fw-bold text-white-50">Episode Number</label>
                    <input type="number" name="ep_number" class="form-control bg-black text-white border-secondary" placeholder="e.g. 1" required>
                </div>
                <div class="mb-3">
                    <label class="small fw-bold text-white-50">Iframe Code (YouTube/Vimeo)</label>
                    <textarea name="iframe_code" class="form-control bg-black text-white border-secondary" rows="5" placeholder="Paste embed code here..." required></textarea>
                </div>
            </div>
            <div class="modal-footer border-secondary">
                <button type="submit" name="add_episode" class="btn btn-danger w-100 fw-bold">Post Episode & Alert Team</button>
            </div>
        </form>
    </div>
</div>

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