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

// --- MAILCHIMP NOTIFICATION FUNCTION (STREAM CONTEXT VERSION) ---
function notifyViaMailchimp($pdo, $subject, $htmlContent) {
    // 1. Mailchimp Configuration
    $apiKey = 'YOUR_MAILCHIMP_API_KEY'; // Replace with your Key
    $serverPrefix = 'us21'; // Replace with your server prefix (e.g., us1, us20)
    $url = "https://{$serverPrefix}.api.mailchimp.com/3.0/messages/send";

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

    if (empty($members)) return false;

    foreach ($members as $email) {
        $data = [
            "key" => $apiKey,
            "message" => [
                "html" => $htmlContent,
                "subject" => $subject,
                "from_email" => "portal@swarnavahini.lk",
                "from_name" => "Swarnavahini Ratings",
                "to" => [["email" => $email, "type" => "to"]]
            ]
        ];
        
        $payload = json_encode($data);

        // 2. Setup Stream Context (Replacing cURL)
        $options = [
            'http' => [
                'header'  => "Content-type: application/json\r\n" .
                             "Authorization: Basic " . base64_encode("user:$apiKey") . "\r\n",
                'method'  => 'POST',
                'content' => $payload,
                'ignore_errors' => true // Prevent script crash on API error
            ],
            'ssl' => [
                'verify_peer' => false,      // Necessary for many cPanel/Localhost environments
                'verify_peer_name' => false,
            ]
        ];

        $context  = stream_context_create($options);
        
        // 3. Send the request
        $result = @file_get_contents($url, false, $context);
        
        if ($result === FALSE) {
            error_log("Mailchimp Error: Failed to send via stream context.");
        }
    }
    return true;
}

// Handle New Teledrama Submission
if (isset($_POST['add_drama'])) {
    $title = $_POST['title'];
    $desc = $_POST['description'];
    
    $target_dir = "../uploads/thumbnails/";
    $file_name = time() . "_" . basename($_FILES["thumbnail"]["name"]);
    $target_file = $target_dir . $file_name;

    if (move_uploaded_file($_FILES["thumbnail"]["tmp_name"], $target_file)) {
        $sql = "INSERT INTO dramas (title, description, thumbnail) VALUES (?, ?, ?)";
        $pdo->prepare($sql)->execute([$title, $desc, $file_name]);
        
        // TRIGGER MAILCHIMP (Now uses file_get_contents)
        $emailBody = "<h1>New Content Alert</h1><p>The Teledrama <b>$title</b> has been added. Please log in to evaluate.</p>";
        notifyViaMailchimp($pdo, "New Teledrama: $title", $emailBody);

        $success = "Teledrama added successfully!";
    }
}

// Handle New Episode Submission
if (isset($_POST['add_episode'])) {
    $drama_id = $_POST['drama_id'];
    $ep_no = $_POST['ep_number'];
    $iframe = $_POST['iframe_code'];

    $sql = "INSERT INTO episodes (drama_id, ep_number, iframe_code) VALUES (?, ?, ?)";
    $pdo->prepare($sql)->execute([$drama_id, $ep_no, $iframe]);

    // Fetch drama name for the email
    $dStmt = $pdo->prepare("SELECT title FROM dramas WHERE id = ?");
    $dStmt->execute([$drama_id]);
    $dName = $dStmt->fetchColumn();

    // TRIGGER MAILCHIMP
    $emailBody = "<h1>New Episode Alert</h1><p>Episode $ep_no of <b>$dName</b> is ready for review.</p>";
    notifyViaMailchimp($pdo, "New Episode: $dName", $emailBody);

    $success = "Episode $ep_no added successfully!";
}

$dramas = $pdo->query("SELECT * FROM dramas ORDER BY created_at DESC")->fetchAll();
include '../includes/header.php';
?>

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="text-white fw-bold">Manage Teledramas</h2>
        <button class="btn btn-danger shadow" data-bs-toggle="modal" data-bs-target="#dramaModal">
            <i class="bi bi-plus-circle me-1"></i> Add New Teledrama
        </button>
    </div>

    <?php if(isset($success)): ?>
        <div class="alert alert-success bg-success text-white border-0 shadow-sm"><?= $success ?></div>
    <?php endif; ?>

    <div class="row">
        <?php foreach ($dramas as $drama): ?>
        <div class="col-md-4 mb-4">
            <div class="card bg-dark border-secondary shadow-sm h-100 drama-card">
                <img src="../uploads/thumbnails/<?= $drama['thumbnail'] ?>" class="card-img-top" style="height: 200px; object-fit: cover;">
                <div class="card-body">
                    <h5 class="card-title text-white fw-bold"><?= $drama['title'] ?></h5>
                    <p class="text-muted small"><?= substr($drama['description'], 0, 80) ?>...</p>
                    <div class="d-grid gap-2 mt-3">
                        <button class="btn btn-outline-info btn-sm" data-bs-toggle="modal" data-bs-target="#epModal<?= $drama['id'] ?>">+ Add Episode</button>
                        <a href="view_episodes.php?id=<?= $drama['id'] ?>" class="btn btn-outline-light btn-sm">Manage Episodes</a>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal fade" id="epModal<?= $drama['id'] ?>" 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">Add Episode to <?= $drama['title'] ?></h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="drama_id" value="<?= $drama['id'] ?>">
                        <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">Embed Code (Iframe)</label>
                            <textarea name="iframe_code" class="form-control bg-dark text-white border-secondary" rows="4" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer border-secondary">
                        <button type="submit" name="add_episode" class="btn btn-danger">Save & Notify Members</button>
                    </div>
                </form>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<div class="modal fade" id="dramaModal" tabindex="-1">
    <div class="modal-dialog">
        <form class="modal-content bg-dark text-white border-secondary" method="POST" enctype="multipart/form-data">
            <div class="modal-header border-secondary">
                <h5 class="modal-title">New Teledrama</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">Title</label>
                    <input type="text" name="title" class="form-control bg-dark text-white border-secondary" required>
                </div>
                <div class="mb-3">
                    <label class="small text-white-50">Description</label>
                    <textarea name="description" class="form-control bg-dark text-white border-secondary" rows="3"></textarea>
                </div>
                <div class="mb-3">
                    <label class="small text-white-50">Poster Thumbnail</label>
                    <input type="file" name="thumbnail" class="form-control bg-dark text-white border-secondary" accept="image/*" required>
                </div>
            </div>
            <div class="modal-footer border-secondary">
                <button type="submit" name="add_drama" class="btn btn-danger">Create & Notify Members</button>
            </div>
        </form>
    </div>
</div>
<?php include '../includes/footer.php'; ?>