<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header("Location: login.php");
    exit;
}
?>
<html>
    <a href="logout.php">Logout</a>
</html>

<?php
$page_title = "Admin Dashboard | Swarnawahini";
require $_SERVER['DOCUMENT_ROOT'] . '/swarnawahini_web/components/db_connect.php';

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

// Initialize message variables
$teledrama_message = '';
$banner_message = '';
$special_program_message = '';
$featured_program_message = '';
$programme_message = '';
$contact_message = '';
$schedule_message = '';

// Handle Teledrama Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['title']) && !isset($_POST['special_program_id']) && !isset($_POST['featured_program_id']) && !isset($_POST['programme_id']) && !isset($_POST['schedule_day'])) {
    $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 = '';

    $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/swarnawahini_web/uploads/teledramas/';
    if (!file_exists($target_dir)) {
        if (!mkdir($target_dir, 0777, true)) {
            $teledrama_message = "Error: Failed to create teledrama upload directory.";
            error_log("Teledrama upload failed: Could not create directory $target_dir", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        }
    }
    if (!is_writable($target_dir)) {
        $teledrama_message = "Error: Teledrama upload directory is not writable.";
        error_log("Teledrama upload failed: Directory $target_dir is not writable.", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    } elseif (isset($_FILES['cover_image']) && $_FILES['cover_image']['error'] === UPLOAD_ERR_OK) {
        $cover_image = basename($_FILES['cover_image']['name']);
        $target_file = $target_dir . $cover_image;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        $check = getimagesize($_FILES['cover_image']['tmp_name']);
        if ($check === false || !in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif'])) {
            $teledrama_message = "Invalid image file. Please upload JPG, PNG, or GIF.";
            error_log("Teledrama upload failed: Invalid image file.", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        } elseif (file_exists($target_file)) {
            $teledrama_message = "Error: File already exists.";
            error_log("Teledrama upload failed: File $target_file already exists.", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        } elseif (!move_uploaded_file($_FILES['cover_image']['tmp_name'], $target_file)) {
            $teledrama_message = "Error uploading cover image.";
            error_log("Teledrama upload failed: Unable to move file to $target_file, Error: " . $_FILES['cover_image']['error'], 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        }
    }

    try {
        $stmt = $conn->prepare("INSERT INTO teledramas (title, description, youtube_playlist, cover_image) VALUES (:title, :description, :youtube_playlist, :cover_image)");
        if ($stmt === false) {
            throw new Exception("Failed to prepare SQL statement for teledrama insertion: " . json_encode($conn->errorInfo()));
        }
        $stmt->execute([
            ':title' => $title,
            ':description' => $description,
            ':youtube_playlist' => $youtube_playlist,
            ':cover_image' => $cover_image
        ]);
        if (!$teledrama_message) {
            $teledrama_message = "Teledrama added successfully!";
        }
    } catch (Exception $e) {
        $teledrama_message = "Error saving teledrama to database: " . htmlspecialchars($e->getMessage());
        error_log("Teledrama database error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        if ($cover_image && file_exists($target_file)) {
            unlink($target_file);
        }
    }
}

// Handle Banner Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['banner_image'])) {
    $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/swarnawahini_web/uploads/banners/';
    if (!file_exists($target_dir)) {
        if (!mkdir($target_dir, 0777, true)) {
            $banner_message = "Error: Failed to create banner upload directory.";
            error_log("Banner upload failed: Could not create directory $target_dir", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        }
    }
    if (!is_writable($target_dir)) {
        $banner_message = "Error: Banner upload directory is not writable.";
        error_log("Banner upload failed: Directory $target_dir is not writable.", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    } else {
        $banner_image = basename($_FILES['banner_image']['name']);
        $target_file = $target_dir . $banner_image;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        if ($_FILES['banner_image']['error'] !== UPLOAD_ERR_OK) {
            $upload_errors = [
                UPLOAD_ERR_INI_SIZE => "File exceeds upload_max_filesize.",
                UPLOAD_ERR_FORM_SIZE => "File exceeds MAX_FILE_SIZE in form.",
                UPLOAD_ERR_PARTIAL => "File was only partially uploaded.",
                UPLOAD_ERR_NO_FILE => "No file was uploaded.",
                UPLOAD_ERR_NO_TMP_DIR => "Missing temporary folder.",
                UPLOAD_ERR_CANT_WRITE => "Failed to write file to disk.",
                UPLOAD_ERR_EXTENSION => "A PHP extension stopped the file upload."
            ];
            $banner_message = "Upload error: " . ($upload_errors[$_FILES['banner_image']['error']] ?? "Unknown error.");
            error_log("Banner upload error: " . $banner_message, 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        } else {
            $check = getimagesize($_FILES['banner_image']['tmp_name']);
            if ($check === false || !in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif'])) {
                $banner_message = "Invalid image file. Please upload JPG, PNG, or GIF.";
                error_log("Banner upload failed: Invalid image file.", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
            } elseif (file_exists($target_file)) {
                $banner_message = "Error: File already exists.";
                error_log("Banner upload failed: File $target_file already exists.", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
            } elseif (move_uploaded_file($_FILES['banner_image']['tmp_name'], $target_file)) {
                try {
                    $stmt = $conn->prepare("INSERT INTO banners (image_path) VALUES (:image_path)");
                    if ($stmt === false) {
                        throw new Exception("Failed to prepare SQL statement for banner insertion: " . json_encode($conn->errorInfo()));
                    }
                    $stmt->execute([':image_path' => $banner_image]);
                    $banner_message = "Banner uploaded successfully!";
                } catch (Exception $e) {
                    $banner_message = "Error saving banner to database: " . htmlspecialchars($e->getMessage());
                    error_log("Banner database error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
                    if (file_exists($target_file)) {
                        unlink($target_file);
                    }
                }
            } else {
                $banner_message = "Error moving uploaded file. Check server permissions.";
                error_log("Banner upload failed: Unable to move file to $target_file, Error: " . $_FILES['banner_image']['error'], 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
            }
        }
    }
}

// Handle Banner Deletion
if (isset($_GET['delete_banner']) && is_numeric($_GET['delete_banner'])) {
    $id = (int)$_GET['delete_banner'];
    try {
        $stmt = $conn->prepare("SELECT image_path FROM banners WHERE id = :id");
        if ($stmt === false) {
            throw new Exception("Failed to prepare SQL statement for banner deletion query: " . json_encode($conn->errorInfo()));
        }
        $stmt->execute([':id' => $id]);
        $banner = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($banner) {
            $file_path = $_SERVER['DOCUMENT_ROOT'] . '/swarnawahini_web/uploads/banners/' . $banner['image_path'];
            if (file_exists($file_path)) {
                if (!unlink($file_path)) {
                    error_log("Failed to delete banner file: $file_path", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
                }
            }
            $stmt = $conn->prepare("DELETE FROM banners WHERE id = :id");
            if ($stmt === false) {
                throw new Exception("Failed to prepare SQL statement for banner deletion: " . json_encode($conn->errorInfo()));
            }
            $stmt->execute([':id' => $id]);
            $banner_message = "Banner deleted successfully!";
        } else {
            $banner_message = "Banner not found.";
        }
    } catch (Exception $e) {
        $banner_message = "Error deleting banner: " . htmlspecialchars($e->getMessage());
        error_log("Banner deletion error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    }
}

// Handle Special Program Submission (Add/Edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['special_program_title'])) {
    $special_program_id = filter_input(INPUT_POST, 'special_program_id', FILTER_SANITIZE_NUMBER_INT);
    $title = filter_input(INPUT_POST, 'special_program_title', FILTER_SANITIZE_STRING);
    $youtube_url = filter_input(INPUT_POST, 'youtube_url', FILTER_SANITIZE_URL);

    $video_id = '';
    if (preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/', $youtube_url, $match)) {
        $video_id = $match[1];
    }

    if (!$video_id) {
        $special_program_message = "Invalid YouTube URL. Please use a URL like https://www.youtube.com/watch?v=VIDEO_ID";
    } else {
        $thumbnail_url = "https://i.ytimg.com/vi/{$video_id}/hqdefault.jpg";
        $headers = @get_headers($thumbnail_url);
        if ($headers && strpos($headers[0], '200') === false) {
            error_log("Thumbnail URL inaccessible: $thumbnail_url, Headers: " . implode(", ", $headers), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
            $thumbnail_url = 'default.jpg';
            $special_program_message = "Thumbnail URL inaccessible. Using default image.";
        }

        try {
            if ($special_program_id) {
                $stmt = $conn->prepare("UPDATE special_programs SET title = :title, youtube_url = :youtube_url, thumbnail_url = :thumbnail_url WHERE id = :id");
                if ($stmt === false) {
                    throw new Exception("Failed to prepare SQL statement for special program update: " . json_encode($conn->errorInfo()));
                }
                $stmt->execute([
                    ':title' => $title,
                    ':youtube_url' => $youtube_url,
                    ':thumbnail_url' => $thumbnail_url,
                    ':id' => $special_program_id
                ]);
                $special_program_message = "Special program updated successfully!";
            } else {
                $stmt = $conn->prepare("INSERT INTO special_programs (title, youtube_url, thumbnail_url) VALUES (:title, :youtube_url, :thumbnail_url)");
                if ($stmt === false) {
                    throw new Exception("Failed to prepare SQL statement for special program insertion: " . json_encode($conn->errorInfo()));
                }
                $stmt->execute([
                    ':title' => $title,
                    ':youtube_url' => $youtube_url,
                    ':thumbnail_url' => $thumbnail_url
                ]);
                $special_program_message = "Special program added successfully!";
            }
        } catch (Exception $e) {
            $special_program_message = "Error processing special program: " . htmlspecialchars($e->getMessage());
            error_log("Special program database error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        }
    }
}

// Handle Special Program Deletion
if (isset($_GET['delete_special_program']) && is_numeric($_GET['delete_special_program'])) {
    $id = (int)$_GET['delete_special_program'];
    try {
        $stmt = $conn->prepare("DELETE FROM special_programs WHERE id = :id");
        if ($stmt === false) {
            throw new Exception("Failed to prepare SQL statement for special program deletion: " . json_encode($conn->errorInfo()));
        }
        $stmt->execute([':id' => $id]);
        $special_program_message = "Special program deleted successfully!";
    } catch (Exception $e) {
        $special_program_message = "Error deleting special program: " . htmlspecialchars($e->getMessage());
        error_log("Special program deletion error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    }
}

// Handle Featured Program Submission (Add/Edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['featured_program_title'])) {
    $featured_program_id = filter_input(INPUT_POST, 'featured_program_id', FILTER_SANITIZE_NUMBER_INT);
    $title = filter_input(INPUT_POST, 'featured_program_title', FILTER_SANITIZE_STRING);
    $youtube_url = filter_input(INPUT_POST, 'youtube_url', FILTER_SANITIZE_URL);

    $video_id = '';
    if (preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/', $youtube_url, $match)) {
        $video_id = $match[1];
    }

    if (!$video_id) {
        $featured_program_message = "Invalid YouTube URL. Please use a URL like https://www.youtube.com/watch?v=VIDEO_ID";
    } else {
        $thumbnail_url = "https://i.ytimg.com/vi/{$video_id}/hqdefault.jpg";
        $headers = @get_headers($thumbnail_url);
        if ($headers && strpos($headers[0], '200') === false) {
            error_log("Thumbnail URL inaccessible: $thumbnail_url, Headers: " . implode(", ", $headers), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
            $thumbnail_url = 'default.jpg';
            $featured_program_message = "Thumbnail URL inaccessible. Using default image.";
        }

        try {
            if ($featured_program_id) {
                $stmt = $conn->prepare("UPDATE featured_programs SET title = :title, youtube_url = :youtube_url, thumbnail_url = :thumbnail_url WHERE id = :id");
                if ($stmt === false) {
                    throw new Exception("Failed to prepare SQL statement for featured program update: " . json_encode($conn->errorInfo()));
                }
                $stmt->execute([
                    ':title' => $title,
                    ':youtube_url' => $youtube_url,
                    ':thumbnail_url' => $thumbnail_url,
                    ':id' => $featured_program_id
                ]);
                $featured_program_message = "Featured program updated successfully!";
            } else {
                $stmt = $conn->prepare("INSERT INTO featured_programs (title, youtube_url, thumbnail_url) VALUES (:title, :youtube_url, :thumbnail_url)");
                if ($stmt === false) {
                    throw new Exception("Failed to prepare SQL statement for featured program insertion: " . json_encode($conn->errorInfo()));
                }
                $stmt->execute([
                    ':title' => $title,
                    ':youtube_url' => $youtube_url,
                    ':thumbnail_url' => $thumbnail_url
                ]);
                $featured_program_message = "Featured program added successfully!";
            }
        } catch (Exception $e) {
            $featured_program_message = "Error processing featured program: " . htmlspecialchars($e->getMessage());
            error_log("Featured program database error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        }
    }
}

// Handle Featured Program Deletion
if (isset($_GET['delete_featured_program']) && is_numeric($_GET['delete_featured_program'])) {
    $id = (int)$_GET['delete_featured_program'];
    try {
        $stmt = $conn->prepare("DELETE FROM featured_programs WHERE id = :id");
        if ($stmt === false) {
            throw new Exception("Failed to prepare SQL statement for featured program deletion: " . json_encode($conn->errorInfo()));
        }
        $stmt->execute([':id' => $id]);
        $featured_program_message = "Featured program deleted successfully!";
    } catch (Exception $e) {
        $featured_program_message = "Error deleting featured program: " . htmlspecialchars($e->getMessage());
        error_log("Featured program deletion error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    }
}

// Handle Programme Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['programme_title'])) {
    $programme_id = filter_input(INPUT_POST, 'programme_id', FILTER_SANITIZE_NUMBER_INT);
    $title = filter_input(INPUT_POST, 'programme_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 = '';

    // Define upload directory
    $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/swarnawahini_web/uploads/programmes/';
    if (!file_exists($target_dir)) {
        if (!mkdir($target_dir, 0777, true)) {
            $programme_message = "Error: Failed to create programme upload directory.";
            error_log("Programme upload failed: Could not create directory $target_dir", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        }
    }

    // Check directory writability
    if (!is_writable($target_dir)) {
        $programme_message = "Error: Programme upload directory is not writable.";
        error_log("Programme upload failed: Directory $target_dir is not writable.", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    } elseif (isset($_FILES['cover_image']) && $_FILES['cover_image']['error'] === UPLOAD_ERR_OK) {
        $cover_image = basename($_FILES['cover_image']['name']);
        $target_file = $target_dir . $cover_image;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        // Validate image
        $check = getimagesize($_FILES['cover_image']['tmp_name']);
        if ($check === false || !in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif'])) {
            $programme_message = "Invalid image file. Please upload JPG, PNG, or GIF.";
            error_log("Programme upload failed: Invalid image file for $target_file", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        } elseif (file_exists($target_file)) {
            $programme_message = "Error: File already exists.";
            error_log("Programme upload failed: File $target_file already exists.", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        } elseif (!move_uploaded_file($_FILES['cover_image']['tmp_name'], $target_file)) {
            $programme_message = "Error uploading cover image.";
            error_log("Programme upload failed: Unable to move file to $target_file, Error: " . $_FILES['cover_image']['error'], 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        }
    }

    try {
        if ($programme_id) {
            // Update existing programme
            $stmt = $conn->prepare("UPDATE programmes SET title = :title, description = :description, youtube_playlist = :youtube_playlist, cover_image = :cover_image WHERE id = :id");
            if ($stmt === false) {
                throw new Exception("Failed to prepare SQL statement for programme update: " . json_encode($conn->errorInfo()));
            }
            $stmt->execute([
                ':title' => $title,
                ':description' => $description,
                ':youtube_playlist' => $youtube_playlist,
                ':cover_image' => $cover_image,
                ':id' => $programme_id
            ]);
            $new_programme_id = $programme_id;
            $programme_message = "Programme updated successfully!";
        } else {
            // Insert new programme
            $stmt = $conn->prepare("INSERT INTO programmes (title, description, youtube_playlist, cover_image) VALUES (:title, :description, :youtube_playlist, :cover_image)");
            if ($stmt === false) {
                throw new Exception("Failed to prepare SQL statement for programme insertion: " . json_encode($conn->errorInfo()));
            }
            $stmt->execute([
                ':title' => $title,
                ':description' => $description,
                ':youtube_playlist' => $youtube_playlist,
                ':cover_image' => $cover_image
            ]);
            $new_programme_id = $conn->lastInsertId(); // Get the newly created ID
            $programme_message = "Programme added successfully!";
        }

        // Update YouTube thumbnail for the programme
        if (!empty($youtube_playlist)) {
            $thumbnail = getYouTubeThumbnail($youtube_playlist, 'AIzaSyBAON_ChCgF5BEXX7ijp--GImeRmAHdUBY', $conn, $new_programme_id, 'programmes');
            if ($thumbnail === 'default.jpg') {
                error_log("Warning: Thumbnail fetch returned default.jpg for programme ID $new_programme_id", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
            }
        }
    } catch (Exception $e) {
        $programme_message = "Error saving programme to database: " . htmlspecialchars($e->getMessage());
        error_log("Programme database error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        if ($cover_image && file_exists($target_file)) {
            unlink($target_file);
        }
    }
}
// Handle Programme Deletion
if (isset($_GET['delete_programme']) && is_numeric($_GET['delete_programme'])) {
    $id = (int)$_GET['delete_programme'];
    try {
        $stmt = $conn->prepare("SELECT cover_image FROM programmes WHERE id = :id");
        if ($stmt === false) {
            throw new Exception("Failed to prepare SQL statement for programme deletion query: " . json_encode($conn->errorInfo()));
        }
        $stmt->execute([':id' => $id]);
        $programme = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($programme) {
            $file_path = $_SERVER['DOCUMENT_ROOT'] . '/swarnawahini_web/uploads/programmes/' . $programme['cover_image'];
            if (file_exists($file_path)) {
                if (!unlink($file_path)) {
                    error_log("Failed to delete programme file: $file_path", 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
                }
            }
            $stmt = $conn->prepare("DELETE FROM programmes WHERE id = :id");
            if ($stmt === false) {
                throw new Exception("Failed to prepare SQL statement for programme deletion: " . json_encode($conn->errorInfo()));
            }
            $stmt->execute([':id' => $id]);
            $programme_message = "Programme deleted successfully!";
        } else {
            $programme_message = "Programme not found.";
        }
    } catch (Exception $e) {
        $programme_message = "Error deleting programme: " . htmlspecialchars($e->getMessage());
        error_log("Programme deletion error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    }
}

// Handle Contact Message Deletion
if (isset($_GET['delete_contact']) && is_numeric($_GET['delete_contact'])) {
    $id = (int)$_GET['delete_contact'];
    try {
        $stmt = $conn->prepare("DELETE FROM contact WHERE id = :id");
        if ($stmt === false) {
            throw new Exception("Failed to prepare SQL statement for contact deletion: " . json_encode($conn->errorInfo()));
        }
        $stmt->execute([':id' => $id]);
        $contact_message = "Contact message deleted successfully!";
    } catch (Exception $e) {
        $contact_message = "Error deleting contact message: " . htmlspecialchars($e->getMessage());
        error_log("Contact deletion error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    }
}

// Handle TV Schedule Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['schedule_day'])) {
    $day = filter_input(INPUT_POST, 'schedule_day', FILTER_SANITIZE_STRING);
    $time = filter_input(INPUT_POST, 'schedule_time', FILTER_SANITIZE_STRING);
    $program_name = filter_input(INPUT_POST, 'program_name', FILTER_SANITIZE_STRING);

    $valid_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    if (!in_array($day, $valid_days) || !preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $time) || empty($program_name)) {
        $schedule_message = "Invalid input. Ensure day, time (HH:MM), and program name are valid.";
    } else {
        try {
            $stmt = $conn->prepare("INSERT INTO tv_schedule (day, time, program_name) VALUES (:day, :time, :program_name)");
            if ($stmt === false) {
                throw new Exception("Failed to prepare SQL statement for schedule insertion: " . json_encode($conn->errorInfo()));
            }
            $stmt->execute([
                ':day' => $day,
                ':time' => $time,
                ':program_name' => $program_name
            ]);
            $schedule_message = "Program added to schedule successfully!";
        } catch (Exception $e) {
            $schedule_message = "Error adding schedule: " . htmlspecialchars($e->getMessage());
            error_log("Schedule database error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        }
    }
}

// Handle TV Schedule Deletion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_schedule_id'])) {
    $delete_id = filter_input(INPUT_POST, 'delete_schedule_id', FILTER_VALIDATE_INT);
    if ($delete_id !== false && $delete_id > 0) {
        try {
            $stmt = $conn->prepare("DELETE FROM tv_schedule WHERE id = :id");
            if ($stmt === false) {
                throw new Exception("Failed to prepare SQL statement for schedule deletion: " . json_encode($conn->errorInfo()));
            }
            $stmt->execute([':id' => $delete_id]);
            $schedule_message = "Program deleted from schedule successfully!";
        } catch (Exception $e) {
            $schedule_message = "Error deleting schedule: " . htmlspecialchars($e->getMessage());
            error_log("Schedule deletion error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
        }
    } else {
        $schedule_message = "Invalid schedule ID.";
    }
}

// Fetch all banners
try {
    $banners = $conn->query("SELECT * FROM banners ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $banner_message = "Error fetching banners: " . htmlspecialchars($e->getMessage());
    error_log("Banner fetch error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    $banners = [];
}

// Fetch all special programs
try {
    $special_programs = $conn->query("SELECT * FROM special_programs ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $special_program_message = "Error fetching special programs: " . htmlspecialchars($e->getMessage());
    error_log("Special program fetch error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    $special_programs = [];
}

// Fetch all featured programs
try {
    $featured_programs = $conn->query("SELECT * FROM featured_programs ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $featured_program_message = "Error fetching featured programs: " . htmlspecialchars($e->getMessage());
    error_log("Featured program fetch error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    $featured_programs = [];
}

// Fetch all programmes
try {
    $programmes = $conn->query("SELECT * FROM programmes ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $programme_message = "Error fetching programmes: " . htmlspecialchars($e->getMessage());
    error_log("Programme fetch error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    $programmes = [];
}

// Fetch all contact messages
try {
    $contact_messages = $conn->query("SELECT * FROM contact ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $contact_message = "Error fetching contact messages: " . htmlspecialchars($e->getMessage());
    error_log("Contact fetch error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    $contact_messages = [];
}

// Fetch all schedule entries
try {
    $schedule_entries = $conn->query("SELECT * FROM tv_schedule ORDER BY day, time ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $schedule_message = "Error fetching schedule entries: " . htmlspecialchars($e->getMessage());
    error_log("Schedule fetch error: " . $e->getMessage(), 3, "/home/monara/public_html/swarnawahini_web/logs/php_errors.log");
    $schedule_entries = [];
}

require $_SERVER['DOCUMENT_ROOT'] . '/swarnawahini_web/components/header.php';
?>

<div class="container mt-5">
    <h1 class="page-title"><?php echo htmlspecialchars($page_title); ?></h1>

    <!-- Tab Navigation -->
    <ul class="nav nav-tabs mb-4" id="dashboardTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="teledrama-tab" data-bs-toggle="tab" data-bs-target="#teledrama" type="button" role="tab" aria-controls="teledrama" aria-selected="true">Teledrama Management</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="banner-tab" data-bs-toggle="tab" data-bs-target="#banner" type="button" role="tab" aria-controls="banner" aria-selected="false">Banner Management</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="special-program-tab" data-bs-toggle="tab" data-bs-target="#special-program" type="button" role="tab" aria-controls="special-program" aria-selected="false">Special Program Management</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="featured-program-tab" data-bs-toggle="tab" data-bs-target="#featured-program" type="button" role="tab" aria-controls="featured-program" aria-selected="false">Featured Program Management</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="programme-tab" data-bs-toggle="tab" data-bs-target="#programme" type="button" role="tab" aria-controls="programme" aria-selected="false">Programme Management</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" type="button" role="tab" aria-controls="contact" aria-selected="false">Contact Messages</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="schedule-tab" data-bs-toggle="tab" data-bs-target="#schedule" type="button" role="tab" aria-controls="schedule" aria-selected="false">TV Schedule Management</button>
        </li>
    </ul>

    <!-- Tab Content -->
    <div class="tab-content" id="dashboardTabContent">
        <!-- Teledrama Management -->
        <div class="tab-pane fade show active" id="teledrama" role="tabpanel" aria-labelledby="teledrama-tab">
            <h2 class="section-title">Add New Teledrama</h2>
            <?php if ($teledrama_message) { ?>
                <div class="alert alert-<?php echo strpos($teledrama_message, 'Error') !== false ? 'danger' : 'success'; ?>"><?php echo htmlspecialchars($teledrama_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" required>
                </div>
                <div class="mb-3">
                    <label for="description" class="form-label">Description</label>
                    <textarea id="description" name="description" class="form-control" rows="3"></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" placeholder="e.g., PLabcdef123456789" required>
                </div>
                <div class="mb-3">
                    <label for="cover_image" class="form-label">Cover Image</label>
                    <input type="file" id="cover_image" name="cover_image" class="form-control" accept="image/*">
                </div>
                <button type="submit" class="btn btn-success">Add Teledrama</button>
            </form>
        </div>

        <!-- Banner Management -->
        <div class="tab-pane fade" id="banner" role="tabpanel" aria-labelledby="banner-tab">
            <h2 class="section-title">Manage Banners</h2>
            <?php if ($banner_message) { ?>
                <div class="alert alert-<?php echo strpos($banner_message, 'Error') !== false ? 'danger' : 'success'; ?>"><?php echo htmlspecialchars($banner_message); ?></div>
            <?php } ?>
            <form method="POST" enctype="multipart/form-data" class="glass-form mb-4">
                <div class="mb-3">
                    <label for="banner_image" class="form-label">Upload New Banner</label>
                    <input type="file" id="banner_image" name="banner_image" class="form-control" accept="image/*" required>
                </div>
                <button type="submit" class="btn btn-primary">Upload Banner</button>
            </form>
            <?php if (!empty($banners)) { ?>
                <div class="row row-cols-1 row-cols-md-3 g-4">
                    <?php foreach ($banners as $banner) { ?>
                        <div class="col">
                            <div class="card">
                                <img src="/swarnawahini_web/uploads/banners/<?php echo htmlspecialchars($banner['image_path']); ?>" class="card-img-top" alt="Banner">
                                <div class="card-body">
                                    <a href="?delete_banner=<?php echo $banner['id']; ?>" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this banner?');">Delete</a>
                                </div>
                            </div>
                        </div>
                    <?php } ?>
                </div>
            <?php } else { ?>
                <p>No banners uploaded yet.</p>
            <?php } ?>
        </div>

        <!-- Special Program Management -->
        <div class="tab-pane fade" id="special-program" role="tabpanel" aria-labelledby="special-program-tab">
            <h2 class="section-title">Manage Special Programs</h2>
            <?php if ($special_program_message) { ?>
                <div class="alert alert-<?php echo strpos($special_program_message, 'Error') !== false ? 'danger' : 'success'; ?>"><?php echo htmlspecialchars($special_program_message); ?></div>
            <?php } ?>
            <form method="POST" class="glass-form mb-4">
                <input type="hidden" name="special_program_id" id="special_program_id" value="">
                <div class="mb-3">
                    <label for="special_program_title" class="form-label">Title</label>
                    <input type="text" id="special_program_title" name="special_program_title" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label for="youtube_url_special" class="form-label">YouTube URL</label>
                    <input type="url" id="youtube_url_special" name="youtube_url" class="form-control" placeholder="https://www.youtube.com/watch?v=VIDEO_ID" required>
                </div>
                <button type="submit" class="btn btn-primary" id="special_program_submit">Add Special Program</button>
            </form>
            <?php if (!empty($special_programs)) { ?>
                <div class="row row-cols-1 row-cols-md-3 g-4">
                    <?php foreach ($special_programs as $program) { ?>
                        <div class="col">
                            <div class="card">
                                <img src="<?php echo htmlspecialchars($program['thumbnail_url'] ?? 'default.jpg'); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($program['title']); ?>">
                                <div class="card-body">
                                    <h6 class="card-title"><?php echo htmlspecialchars($program['title']); ?></h6>
                                    <p class="card-text"><?php echo htmlspecialchars($program['youtube_url']); ?></p>
                                    <button class="btn btn-warning edit-special-program" data-id="<?php echo $program['id']; ?>" data-title="<?php echo htmlspecialchars($program['title']); ?>" data-url="<?php echo htmlspecialchars($program['youtube_url']); ?>">Edit</button>
                                    <a href="?delete_special_program=<?php echo $program['id']; ?>" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this special program?');">Delete</a>
                                </div>
                            </div>
                        </div>
                    <?php } ?>
                </div>
            <?php } else { ?>
                <p>No special programs uploaded yet.</p>
            <?php } ?>
        </div>

        <!-- Featured Program Management -->
        <div class="tab-pane fade" id="featured-program" role="tabpanel" aria-labelledby="featured-program-tab">
            <h2 class="section-title">Manage Featured Programs</h2>
            <?php if ($featured_program_message) { ?>
                <div class="alert alert-<?php echo strpos($featured_program_message, 'Error') !== false ? 'danger' : 'success'; ?>"><?php echo htmlspecialchars($featured_program_message); ?></div>
            <?php } ?>
            <form method="POST" class="glass-form mb-4">
                <input type="hidden" name="featured_program_id" id="featured_program_id" value="">
                <div class="mb-3">
                    <label for="featured_program_title" class="form-label">Title</label>
                    <input type="text" id="featured_program_title" name="featured_program_title" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label for="youtube_url_featured" class="form-label">YouTube URL</label>
                    <input type="url" id="youtube_url_featured" name="youtube_url" class="form-control" placeholder="https://www.youtube.com/watch?v=VIDEO_ID" required>
                </div>
                <button type="submit" class="btn btn-primary" id="featured_program_submit">Add Featured Program</button>
            </form>
            <?php if (!empty($featured_programs)) { ?>
                <div class="row row-cols-1 row-cols-md-3 g-4">
                    <?php foreach ($featured_programs as $program) { ?>
                        <div class="col">
                            <div class="card">
                                <img src="<?php echo htmlspecialchars($program['thumbnail_url'] ?? 'default.jpg'); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($program['title']); ?>">
                                <div class="card-body">
                                    <h6 class="card-title"><?php echo htmlspecialchars($program['title']); ?></h6>
                                    <p class="card-text"><?php echo htmlspecialchars($program['youtube_url']); ?></p>
                                    <button class="btn btn-warning edit-featured-program" data-id="<?php echo $program['id']; ?>" data-title="<?php echo htmlspecialchars($program['title']); ?>" data-url="<?php echo htmlspecialchars($program['youtube_url']); ?>">Edit</button>
                                    <a href="?delete_featured_program=<?php echo $program['id']; ?>" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this featured program?');">Delete</a>
                                </div>
                            </div>
                        </div>
                    <?php } ?>
                </div>
            <?php } else { ?>
                <p>No featured programs uploaded yet.</p>
            <?php } ?>
        </div>

        <!-- Programme Management -->
        <div class="tab-pane fade" id="programme" role="tabpanel" aria-labelledby="programme-tab">
            <h2 class="section-title">Add New Programme</h2>
            <?php if ($programme_message) { ?>
                <div class="alert alert-<?php echo strpos($programme_message, 'Error') !== false ? 'danger' : 'success'; ?>"><?php echo htmlspecialchars($programme_message); ?></div>
            <?php } ?>
            <form method="POST" enctype="multipart/form-data" class="glass-form">
                <div class="mb-3">
                    <label for="programme_title" class="form-label">Title</label>
                    <input type="text" id="programme_title" name="programme_title" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label for="description" class="form-label">Description</label>
                    <textarea id="description" name="description" class="form-control" rows="3"></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" placeholder="e.g., PLabcdef123456789" required>
                </div>
                <div class="mb-3">
                    <label for="cover_image" class="form-label">Cover Image</label>
                    <input type="file" id="cover_image" name="cover_image" class="form-control" accept="image/*">
                </div>
                <button type="submit" class="btn btn-success">Add Programme</button>
            </form>

            <h3 class="section-title mt-4">Existing Programmes</h3>
            <div class="row row-cols-1 row-cols-md-3 g-4">
                <?php foreach ($programmes as $programme): ?>
                    <div class="col">
                        <div class="card">
                            <img src="/swarnawahini_web/uploads/programmes/<?php echo htmlspecialchars($programme['cover_image']); ?>" class="card-img-top" alt="<?php echo htmlspecialchars($programme['title']); ?>">
                            <div class="card-body">
                                <h6 class="card-title"><?php echo htmlspecialchars($programme['title']); ?></h6>
                                <p class="card-text"><?php echo htmlspecialchars($programme['description']); ?></p>
                                <a href="?delete_programme=<?php echo $programme['id']; ?>" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this programme?');">Delete</a>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Contact Messages -->
        <div class="tab-pane fade" id="contact" role="tabpanel" aria-labelledby="contact-tab">
            <h2 class="section-title">Contact Messages</h2>
            <?php if ($contact_message) { ?>
                <div class="alert alert-<?php echo strpos($contact_message, 'Error') !== false ? 'danger' : 'success'; ?>"><?php echo htmlspecialchars($contact_message); ?></div>
            <?php } ?>
            <?php if (!empty($contact_messages)) { ?>
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Message</th>
                                <th>Submitted At</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($contact_messages as $message) { ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($message['id']); ?></td>
                                    <td><?php echo htmlspecialchars($message['name']); ?></td>
                                    <td><?php echo htmlspecialchars($message['email']); ?></td>
                                    <td><?php echo htmlspecialchars(substr($message['message'], 0, 100)) . (strlen($message['message']) > 100 ? '...' : ''); ?></td>
                                    <td><?php echo htmlspecialchars($message['created_at']); ?></td>
                                    <td>
                                        <a href="?delete_contact=<?php echo $message['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this contact message?');">Delete</a>
                                    </td>
                                </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            <?php } else { ?>
                <p>No contact messages submitted yet.</p>
            <?php } ?>
        </div>

        <!-- TV Schedule Management -->
        <div class="tab-pane fade" id="schedule" role="tabpanel" aria-labelledby="schedule-tab">
            <h2 class="section-title">Add New Schedule Entry</h2>
            <?php if ($schedule_message) { ?>
                <div class="alert alert-<?php echo strpos($schedule_message, 'Error') !== false || strpos($schedule_message, 'Invalid') !== false ? 'danger' : 'success'; ?>"><?php echo htmlspecialchars($schedule_message); ?></div>
            <?php } ?>
            <form method="POST" class="glass-form mb-4">
                <div class="mb-3">
                    <label for="schedule_day" class="form-label">Day</label>
                    <select id="schedule_day" name="schedule_day" class="form-control" required>
                        <option value="" disabled selected>Select a day</option>
                        <?php
                        $days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
                        foreach ($days as $day) {
                            echo "<option value=\"$day\">$day</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label for="schedule_time" class="form-label">Time (HH:MM)</label>
                    <input type="time" id="schedule_time" name="schedule_time" class="form-control" required>
                </div>
                <div class="mb-3">
                    <label for="program_name" class="form-label">Program Name</label>
                    <input type="text" id="program_name" name="program_name" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-primary">Add Program</button>
            </form>
            <h3 class="mb-3">Current Schedule</h3>
            <?php if (empty($schedule_entries)) { ?>
                <p>No schedule entries added yet.</p>
            <?php } else { ?>
                <div class="table-responsive">
                    <table class="table table-striped table-bordered">
                        <thead>
                            <tr>
                                <th>Day</th>
                                <th>Time</th>
                                <th>Program</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($schedule_entries as $entry) { ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($entry['day']); ?></td>
                                    <td><?php echo date('h:i A', strtotime($entry['time'])); ?></td>
                                    <td><?php echo htmlspecialchars($entry['program_name']); ?></td>
                                    <td>
                                        <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to delete this schedule entry?');">
                                            <input type="hidden" name="delete_schedule_id" value="<?php echo $entry['id']; ?>">
                                            <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            <?php } ?>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    // Special Program Edit
    document.querySelectorAll('.edit-special-program').forEach(button => {
        button.addEventListener('click', () => {
            const id = button.getAttribute('data-id');
            const title = button.getAttribute('data-title');
            const url = button.getAttribute('data-url');

            document.getElementById('special_program_id').value = id;
            document.getElementById('special_program_title').value = title;
            document.getElementById('youtube_url_special').value = url;
            document.getElementById('special_program_submit').textContent = 'Update Special Program';
        });
    });

    // Featured Program Edit
    document.querySelectorAll('.edit-featured-program').forEach(button => {
        button.addEventListener('click', () => {
            const id = button.getAttribute('data-id');
            const title = button.getAttribute('data-title');
            const url = button.getAttribute('data-url');

            document.getElementById('featured_program_id').value = id;
            document.getElementById('featured_program_title').value = title;
            document.getElementById('youtube_url_featured').value = url;
            document.getElementById('featured_program_submit').textContent = 'Update Featured Program';
        });
    });
});
</script>

<?php require $_SERVER['DOCUMENT_ROOT'] . '/swarnawahini_web/components/footer.php'; ?>