<?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);
    $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, description = :description, youtube_playlist = :youtube_playlist, cover_image = :cover_image
                WHERE id = :id");
            $stmt->execute([
                ':title' => $title,
                ':description' => $description,
                ':youtube_playlist' => $youtube_playlist,
                ':cover_image' => $cover_image,
                ':id' => $id
            ]);

            $edit_message = "Teledrama updated successfully!";
            // Refresh data
            $teledrama['title'] = $title;
            $teledrama['description'] = $description;
            $teledrama['youtube_playlist'] = $youtube_playlist;
            $teledrama['cover_image'] = $cover_image;

        } 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 rel="stylesheet" href="/css/bootstrap.min.css">
</head>
<body class="container py-5">
    <h2>Edit Teledrama</h2>

    <?php if ($edit_message) { ?>
        <div class="alert alert-<?php echo strpos($edit_message, 'Error') !== false ? 'danger' : 'success'; ?>">
            <?php echo htmlspecialchars($edit_message); ?>
        </div>
    <?php } ?>

    <form method="POST" enctype="multipart/form-data" class="glass-form">
        <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="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="/uploads/teledramas/<?php echo htmlspecialchars($teledrama['cover_image']); ?>" width="120" class="mb-2"><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>
        <button type="submit" class="btn btn-primary">Update Teledrama</button>
        <a href="dashboard.php" class="btn btn-secondary">Back</a>
    </form>
</body>
</html>
