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

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

// --- 2. HANDLE DELETE PRODUCTION (Cascading) ---
if (isset($_GET['delete_drama'])) {
    $delete_id = (int)$_GET['delete_drama'];
    
    try {
        $pdo->beginTransaction();
        // Delete related rating values, ratings, and episodes first
        $pdo->prepare("DELETE FROM rating_values WHERE rating_id IN (SELECT id FROM ratings WHERE drama_id = ?)")->execute([$delete_id]);
        $pdo->prepare("DELETE FROM ratings WHERE drama_id = ?")->execute([$delete_id]);
        $pdo->prepare("DELETE FROM episodes WHERE drama_id = ?")->execute([$delete_id]);
        $pdo->prepare("DELETE FROM dramas WHERE id = ?")->execute([$delete_id]);
        $pdo->commit();
        $success = "Production and all related data deleted successfully.";
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = "Error: " . $e->getMessage();
    }
}

// --- UPDATED TRANSACTIONAL NOTIFICATION FUNCTION ---
function notifyViaMandrill($pdo, $subject, $htmlContent) {
    $url = "https://mandrillapp.com/api/1.0/messages/send.json";
    $mandrill_key = 'md-Vjza4GhgRIEoal3e-KKkmw'; 

    $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;

    $recipients = [];
    foreach ($members as $index => $email) {
        $recipients[] = [
            "email" => $email, 
            "type" => ($index === 0) ? "to" : "bcc"
        ];
    }

    $data = [
        "key" => $mandrill_key,
        "message" => [
            "html" => "
                <div style='font-family: Helvetica, Arial, sans-serif; padding: 20px; border-top: 4px solid #e50914; color: #333;'>
                    <div style='text-align: center; margin-bottom: 20px;'>
                        <h2 style='color: #e50914; margin-bottom: 5px;'>Swarnavahini Rating Portal</h2>
                        <hr style='border: 0; border-top: 1px solid #eee;'>
                    </div>
                    $htmlContent
                    <div style='margin-top: 30px; padding-top: 15px; border-top: 1px solid #eee; font-size: 12px; color: #888;'>
                        <p>This is an automated system notification. Please do not reply to this email.</p>
                    </div>
                </div>",
            "subject" => $subject,
            "from_email" => ADMIN_EMAIL,
            "from_name" => "Swarnavahini Ratings",
            "to" => $recipients
        ]
    ];

    $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);
}

// Handle New Teledrama Submission
if (isset($_POST['add_drama'])) {
    $title = htmlspecialchars($_POST['title']);
    $desc = htmlspecialchars($_POST['description']);
    $sql = "INSERT INTO dramas (title, description) VALUES (?, ?)";
    $pdo->prepare($sql)->execute([$title, $desc]);
    $success = "Production registered 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]);

    $dStmt = $pdo->prepare("SELECT title FROM dramas WHERE id = ?");
    $dStmt->execute([$drama_id]);
    $dName = $dStmt->fetchColumn();

    $emailBody = "
        <h3 style='color: #000;'>New Content for Evaluation</h3>
        <p><b>Episode $ep_no</b> of the production <b>$dName</b> is now live on the portal.</p>
        <div style='background: #fdf2f2; padding: 15px; border-left: 4px solid #e50914; margin: 15px 0;'>
            <strong style='color: #e50914;'>Evaluation Deadline:</strong><br>
            You have exactly <b>$deadline_hours hours</b> from now to watch and submit your ratings for this specific episode.
        </div>
        <p><a href='".BASE_URL."' style='display: inline-block; padding: 12px 25px; background: #e50914; color: #fff; text-decoration: none; border-radius: 5px; font-weight: bold;'>Login to Evaluate</a></p>";
    
    notifyViaMandrill($pdo, "Action Required: New Episode $ep_no - $dName", $emailBody);
    $success = "Episode $ep_no added and $deadline_hours-hour audit window started!";
}

$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 fw-bold shadow-sm" data-bs-toggle="modal" data-bs-target="#dramaModal">
            <i class="bi bi-plus-circle me-1"></i> Add Production
        </button>
    </div>

    <?php if(isset($success)): ?>
        <div class="alert alert-success bg-success text-white border-0 shadow-sm mb-4 p-2 fw-bold small text-center"><?= $success ?></div>
    <?php endif; ?>
    <?php if(isset($error)): ?>
        <div class="alert alert-danger bg-danger text-white border-0 shadow-sm mb-4 p-2 fw-bold small text-center"><?= $error ?></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">
                <div class="card-body d-flex flex-column p-4">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <h4 class="card-title text-white fw-bold mb-0"><?= htmlspecialchars($drama['title']) ?></h4>
                        <div class="dropdown">
                            <button class="btn btn-link text-white-50 p-0" type="button" data-bs-toggle="dropdown">
                                <i class="bi bi-three-dots-vertical fs-5"></i>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-dark">
                                <li><a class="dropdown-item" href="edit_drama.php?id=<?= $drama['id'] ?>"><i class="bi bi-pencil me-2"></i> Edit Details</a></li>
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item text-danger" href="?delete_drama=<?= $drama['id'] ?>" onclick="return confirm('WARNING: This will delete ALL episodes and ratings for this production. Continue?')">
                                    <i class="bi bi-trash me-2"></i> Delete Production</a>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <p class="text-white-50 small flex-grow-1"><?= substr(htmlspecialchars($drama['description']), 0, 150) ?>...</p>
                    <div class="d-grid gap-2 mt-3">
                        <button class="btn btn-danger btn-sm fw-bold" data-bs-toggle="modal" data-bs-target="#epModal<?= $drama['id'] ?>">
                            <i class="bi bi-plus-lg me-1"></i> Add Episode
                        </button>
                        <a href="view_episodes.php?id=<?= $drama['id'] ?>" class="btn btn-outline-light btn-sm fw-bold">Manage All 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 shadow" method="POST">
                    <div class="modal-header border-secondary bg-black">
                        <h5 class="modal-title">Upload Episode: <?= htmlspecialchars($drama['title']) ?></h5>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body p-4">
                        <input type="hidden" name="drama_id" value="<?= $drama['id'] ?>">
                        <div class="mb-3">
                            <label class="form-label small text-white-50 fw-bold">Episode Number</label>
                            <input type="number" name="ep_number" class="form-control bg-black text-white border-secondary" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small text-white-50 fw-bold">Iframe / Embed Code</label>
                            <textarea name="iframe_code" class="form-control bg-black text-white border-secondary" rows="4" placeholder="Paste embed code here..." required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer border-secondary bg-black">
                        <button type="submit" name="add_episode" class="btn btn-danger w-100 fw-bold">Upload & Start <?= $deadline_hours ?>h Audit</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 shadow" method="POST">
            <div class="modal-header border-secondary bg-black">
                <h5 class="modal-title">Register New Production</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body p-4">
                <div class="mb-3">
                    <label class="form-label small text-white-50 fw-bold">Production Title</label>
                    <input type="text" name="title" class="form-control bg-black text-white border-secondary" required>
                </div>
                <div class="mb-3">
                    <label class="form-label small text-white-50 fw-bold">Description</label>
                    <textarea name="description" class="form-control bg-black text-white border-secondary" rows="5" placeholder="Enter drama details..."></textarea>
                </div>
            </div>
            <div class="modal-footer border-secondary bg-black">
                <button type="submit" name="add_drama" class="btn btn-danger w-100 fw-bold">Add Production</button>
            </div>
        </form>
    </div>
</div>

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