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

$drama_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$stmt = $pdo->prepare("SELECT * FROM dramas WHERE id = ?");
$stmt->execute([$drama_id]);
$drama = $stmt->fetch();

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

// Trigger Function for Episode only
function notifyEpMailchimp($pdo, $dName, $epNo) {
    $apiKey = 'YOUR_MAILCHIMP_API_KEY';
    $serverPrefix = 'us21';
    $url = "https://{$serverPrefix}.api.mailchimp.com/3.0/messages/send";

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

    foreach ($members as $email) {
        $html = "<h2>New Episode Available</h2><p>Episode $epNo of <b>$dName</b> has been uploaded to the portal.</p>";
        $data = [
            "key" => $apiKey,
            "message" => [
                "html" => $html,
                "subject" => "New Episode: $dName",
                "from_email" => "portal@swarnavahini.lk",
                "to" => [["email" => $email, "type" => "to"]]
            ]
        ];
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_exec($ch);
        curl_close($ch);
    }
}

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])) {
        notifyEpMailchimp($pdo, $drama['title'], $ep_number);
        header("Location: view_episodes.php?id=$drama_id&success=1");
        exit();
    }
}

$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>
            <h2 class="text-white fw-bold"><?= $drama['title'] ?></h2>
            <p class="text-muted">Manage episode evaluation queue</p>
        </div>
        <button class="btn btn-danger" 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">Episode added and members notified via Mailchimp.</div>
    <?php endif; ?>

    <div class="row">
        <?php foreach ($epList as $ep): ?>
        <div class="col-md-4 mb-3">
            <div class="card bg-dark border-secondary h-100 shadow-sm">
                <div class="card-body">
                    <h5 class="text-white fw-bold mb-3">Episode <?= $ep['ep_number'] ?></h5>
                    <div class="ratio ratio-16x9 mb-3 bg-black rounded border border-secondary">
                        <?= $ep['iframe_code'] ?>
                    </div>
                    <button class="btn btn-sm btn-outline-secondary w-100">Edit Details</button>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </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">
                <h5 class="modal-title">New Episode for <?= $drama['title'] ?></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 text-white-50">Episode Number</label>
                    <input type="number" name="ep_number" class="form-control bg-dark text-white border-secondary" required>
                </div>
                <div class="mb-3">
                    <label class="small text-white-50">Iframe Code</label>
                    <textarea name="iframe_code" class="form-control bg-dark text-white border-secondary" rows="5" required></textarea>
                </div>
            </div>
            <div class="modal-footer border-secondary">
                <button type="submit" name="add_episode" class="btn btn-danger w-100">Save & Notify</button>
            </div>
        </form>
    </div>
</div>
<?php include '../includes/footer.php'; ?>