<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header("Location: login.php");
    exit;
}

require $_SERVER['DOCUMENT_ROOT'] . '/components/db_connect.php';

$page_title = "Edit Teledrama | Swarnawahini";

// Error logging
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/home/monara/public_html/logs/php_errors.log');
error_reporting(E_ALL);

$edit_message = '';
$teledrama = null;

// ---------------------------
// Validate ID
// ---------------------------
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$id) {
    die("Invalid Teledrama ID.");
}

// ---------------------------
// Fetch Teledrama
// ---------------------------
try {
    $stmt = $conn->prepare("SELECT * FROM teledramas WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $id]);
    $teledrama = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$teledrama) {
        die("Teledrama not found.");
    }
} catch (Exception $e) {
    die("Database error: " . htmlspecialchars($e->getMessage()));
}

// ---------------------------
// Handle Update
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
    $category = filter_input(INPUT_POST, 'category', FILTER_SANITIZE_STRING); // Get Category
    $description = filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
    $youtube_playlist = filter_input(INPUT_POST, 'youtube_playlist', FILTER_SANITIZE_STRING);

    $cover_image = $teledrama['cover_image']; // Keep old image by default
    $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/uploads/teledramas/';

    if (isset($_FILES['cover_image']) && $_FILES['cover_image']['error'] === UPLOAD_ERR_OK) {
        $new_file = basename($_FILES['cover_image']['name']);
        $target_file = $target_dir . $new_file;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        $check = getimagesize($_FILES['cover_image']['tmp_name']);
        if ($check === false || !in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif', 'svg'])) {
            $edit_message = "Invalid image file. Please upload JPG, PNG, or GIF.";
        } elseif (!move_uploaded_file($_FILES['cover_image']['tmp_name'], $target_file)) {
            $edit_message = "Error uploading new image.";
        } else {
            // Delete old file
            if ($cover_image && file_exists($target_dir . $cover_image)) {
                unlink($target_dir . $cover_image);
            }
            $cover_image = $new_file;
        }
    }

    if (!$edit_message) {
        try {
            $stmt = $conn->prepare("UPDATE teledramas 
                SET title = :title, category = :category, description = :description, youtube_playlist = :youtube_playlist, cover_image = :cover_image
                WHERE id = :id");
            
            $stmt->execute([
                ':title' => $title,
                ':category' => $category,
                ':description' => $description,
                ':youtube_playlist' => $youtube_playlist,
                ':cover_image' => $cover_image,
                ':id' => $id
            ]);

            // --- REDIRECT LOGIC ---
            header("Location: dashboard.php");
            exit; // Stop script execution immediately after redirect
            // ----------------------

        } catch (Exception $e) {
            $edit_message = "Error updating teledrama: " . htmlspecialchars($e->getMessage());
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo $page_title; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: #f8f9fa; }
        .glass-form {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            max-width: 600px;
            margin: auto;
        }
    </style>
</head>
<body class="container py-5">
    
    <div class="glass-form">
        <h2 class="mb-4 text-center">Edit Teledrama</h2>

        <?php if ($edit_message) { ?>
            <div class="alert alert-danger">
                <?php echo htmlspecialchars($edit_message); ?>
            </div>
        <?php } ?>

        <form method="POST" enctype="multipart/form-data">
            <div class="mb-3">
                <label for="title" class="form-label">Title</label>
                <input type="text" id="title" name="title" class="form-control" 
                       value="<?php echo htmlspecialchars($teledrama['title']); ?>" required>
            </div>

            <div class="mb-3">
                <label for="category" class="form-label">Category</label>
                <select id="category" name="category" class="form-select">
                    <option value="weekday" <?php echo ($teledrama['category'] == 'weekday') ? 'selected' : ''; ?>>Weekday (Mon-Fri)</option>
                    <option value="weekend" <?php echo ($teledrama['category'] == 'weekend') ? 'selected' : ''; ?>>Weekend (Sat-Sun)</option>
                </select>
            </div>

            <div class="mb-3">
                <label for="description" class="form-label">Description</label>
                <textarea id="description" name="description" class="form-control" rows="3"><?php echo htmlspecialchars($teledrama['description']); ?></textarea>
            </div>

            <div class="mb-3">
                <label for="youtube_playlist" class="form-label">YouTube Playlist ID</label>
                <input type="text" id="youtube_playlist" name="youtube_playlist" 
                       class="form-control" value="<?php echo htmlspecialchars($teledrama['youtube_playlist']); ?>" required>
            </div>

            <div class="mb-3">
                <label for="cover_image" class="form-label">Cover Image</label><br>
                <?php if ($teledrama['cover_image']) { ?>
                    <img src="/swarnawahini_web_stable/uploads/teledramas/<?php echo htmlspecialchars($teledrama['cover_image']); ?>" width="120" class="mb-2 rounded border"><br>
                <?php } ?>
                <input type="file" id="cover_image" name="cover_image" class="form-control" accept="image/*">
                <small class="text-muted">Leave empty to keep existing image.</small>
            </div>

            <div class="d-grid gap-2">
                <button type="submit" class="btn btn-primary">Update Teledrama</button>
                <a href="dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
            </div>
        </form>
    </div>

</body>
</html>