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

$api_key = 'AIzaSyBAON_ChCgF5BEXX7ijp--GImeRmAHdUBY';
$page_title = "Admin Dashboard | Swarnawahini";

require_once __DIR__ . '/../config.php';
require __DIR__ . '/../components/functions.php';
require __DIR__ . '/../components/db_connect.php';

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

// Initialize message variables
$teledrama_message = '';
$banner_message = '';


$programme_message = '';
$contact_message = '';
$schedule_message = '';
$ad_message = '';
$live_top_ad_message = ''; 
$live_side_ad_message = ''; 
$event_message = '';
$shorts_message = '';
$embed_message = '';

// ---------------------------
// Handle Delete
// ---------------------------
if (isset($_GET['delete_id'])) {
    $delete_id = filter_input(INPUT_GET, 'delete_id', FILTER_VALIDATE_INT);
    if ($delete_id) {
        try {
            // Remove old image
            $stmt = $conn->prepare("SELECT cover_image FROM teledramas WHERE id = :id");
            $stmt->execute([':id' => $delete_id]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($row && $row['cover_image']) {
                $file = $_SERVER['DOCUMENT_ROOT'] . '/uploads/teledramas/' . $row['cover_image'];
                if (file_exists($file)) {
                    unlink($file);
                }
            }

            $stmt = $conn->prepare("DELETE FROM teledramas WHERE id = :id");
            $stmt->execute([':id' => $delete_id]);

            $teledrama_message = "Teledrama deleted successfully!";
        } catch (Exception $e) {
            $teledrama_message = "Error deleting teledrama: " . htmlspecialchars($e->getMessage());
        }
    }
}

// ------------------ NEW YOUTUBE SHORTS HANDLER (Playlist 2) ------------------
$shorts_message_new = ''; 

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sync_shorts_new'])) {
    $playlist_id_new = trim($_POST['playlist_id_new']);
    
    if (!empty($playlist_id_new)) {
        // Save New Playlist ID to Settings
        $stmt = $conn->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('shorts_playlist_id_new', :val) ON DUPLICATE KEY UPDATE setting_value = :val");
        $stmt->execute([':val' => $playlist_id_new]);

        // Call YouTube API
        $api_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=$playlist_id_new&key=$api_key";
        $response = @file_get_contents($api_url);
        
        if ($response) {
            $data = json_decode($response, true);
            if (isset($data['items'])) {
                $added_count = 0;
                $stmt = $conn->prepare("INSERT IGNORE INTO youtube_shorts_new (video_id, title, thumbnail_url, published_at) VALUES (:vid, :title, :thumb, :pub)");
                
                foreach ($data['items'] as $item) {
                    $vid = $item['snippet']['resourceId']['videoId'];
                    $title = $item['snippet']['title'];
                    $thumb = $item['snippet']['thumbnails']['high']['url'] ?? '';
                    $pub = date('Y-m-d H:i:s', strtotime($item['snippet']['publishedAt']));

                    if ($title != "Private video" && $title != "Deleted video") {
                        $stmt->execute([':vid' => $vid, ':title' => $title, ':thumb' => $thumb, ':pub' => $pub]);
                        if ($stmt->rowCount() > 0) $added_count++;
                    }
                }
                $shorts_message_new = "Success! Synced $added_count new shorts.";
            } else {
                $shorts_message_new = "API Error: Check Playlist ID.";
            }
        } else {
            $shorts_message_new = "Connection Error: Check API Key.";
        }
    }
}

// Handle Delete for New Shorts
if (isset($_GET['delete_short_new']) && is_numeric($_GET['delete_short_new'])) {
    $id = (int)$_GET['delete_short_new'];
    $conn->prepare("DELETE FROM youtube_shorts_new WHERE id = ?")->execute([$id]);
    $shorts_message_new = "Short deleted from second feed!";
}

// Fetch New Shorts & Playlist ID
$saved_playlist_id_new = '';
try {
    $row_new = $conn->query("SELECT setting_value FROM site_settings WHERE setting_key = 'shorts_playlist_id_new'")->fetch(PDO::FETCH_ASSOC);
    $saved_playlist_id_new = $row_new ? $row_new['setting_value'] : '';
    $shorts_new = $conn->query("SELECT * FROM youtube_shorts_new ORDER BY published_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $shorts_new = []; }


// ------------------ EVENT MANAGEMENT HANDLER ------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_event'])) {
    $title = filter_input(INPUT_POST, 'event_title', FILTER_SANITIZE_STRING);
    $page_url = filter_input(INPUT_POST, 'event_page_url', FILTER_SANITIZE_URL);
    
    try {
        if (isset($_FILES['event_thumb']) && $_FILES['event_thumb']['error'] === UPLOAD_ERR_OK) {
            // Define target directory consistent with your existing structure
            $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/events/';
            if (!file_exists($target_dir)) {
                mkdir($target_dir, 0755, true);
            }
            
            // Generate a unique filename to prevent overwrites
            $filename = time() . '_' . basename($_FILES['event_thumb']['name']);
            
            if (move_uploaded_file($_FILES['event_thumb']['tmp_name'], $target_dir . $filename)) {
                // Insert into your 'events' table
                $stmt = $conn->prepare("INSERT INTO events (title, thumbnail_url, event_page_url) VALUES (:title, :thumb, :url)");
                $stmt->execute([
                    ':title' => $title, 
                    ':thumb' => $filename, 
                    ':url' => $page_url
                ]);
                $event_message = "Event added successfully!";
            } else {
                throw new Exception("Failed to move uploaded file.");
            }
        } else {
            throw new Exception("Thumbnail upload is required.");
        }
    } catch (Exception $e) {
        $event_message = "Error adding event: " . htmlspecialchars($e->getMessage());
    }
}

// Handle Event Deletion
if (isset($_GET['delete_event'])) {
    $delete_event_id = filter_input(INPUT_GET, 'delete_event', FILTER_VALIDATE_INT);
    if ($delete_event_id) {
        try {
            // 1. First, find the filename to delete it from the server folder
            $stmt = $conn->prepare("SELECT thumbnail_url FROM events WHERE id = :id");
            $stmt->execute([':id' => $delete_event_id]);
            $row = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($row && $row['thumbnail_url']) {
                $file_path = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/events/' . $row['thumbnail_url'];
                if (file_exists($file_path)) {
                    unlink($file_path); // Physically delete the image file
                }
            }

            // 2. Delete the record from the database
            $stmt = $conn->prepare("DELETE FROM events WHERE id = :id");
            $stmt->execute([':id' => $delete_event_id]);

            $event_message = "Event and associated image deleted successfully!";
        } catch (Exception $e) {
            $event_message = "Error deleting event: " . htmlspecialchars($e->getMessage());
        }
    }
}

// ------------------ SPECIAL CUSTOM EMBEDS HANDLER ------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['special_embed_code'])) {
    $title = filter_input(INPUT_POST, 'special_embed_title', FILTER_SANITIZE_STRING);
    $code = $_POST['special_embed_code']; // Allow raw HTML
    
    // Image Upload Logic
    $thumbnail_url = '';
    if (isset($_FILES['special_embed_thumb']) && $_FILES['special_embed_thumb']['error'] === UPLOAD_ERR_OK) {
        
        $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/embeds/';
        
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0755, true);
        }
        
        $filename = time() . '_' . basename($_FILES['special_embed_thumb']['name']);
        $target_file = $target_dir . $filename;
        
        if (move_uploaded_file($_FILES['special_embed_thumb']['tmp_name'], $target_file)) {
            $thumbnail_url = $filename;
        } else {
            $embed_message = "Error uploading thumbnail.";
        }
    }

    if (!empty($title) && !empty($code)) {
        try {
            $stmt = $conn->prepare("INSERT INTO special_embeds (title, embed_code, thumbnail_url) VALUES (:title, :code, :thumb)");
            $stmt->execute([':title' => $title, ':code' => $code, ':thumb' => $thumbnail_url]);
            $embed_message = "Special Embed added successfully!";
        } catch (Exception $e) {
            $embed_message = "Error: " . htmlspecialchars($e->getMessage());
        }
    }
}

// Handle Delete Custom Embed
if (isset($_GET['delete_embed']) && is_numeric($_GET['delete_embed'])) {
    $id = (int)$_GET['delete_embed'];
    
    // Delete image file first
    $stmt = $conn->prepare("SELECT thumbnail_url FROM special_embeds WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($row && $row['thumbnail_url']) {
        $file = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/embeds/' . $row['thumbnail_url'];
        if (file_exists($file)) {
            unlink($file);
        }
    }

    $conn->query("DELETE FROM special_embeds WHERE id = $id");
    $embed_message = "Special Embed deleted successfully!";
}

// Fetch Custom Embeds
try {
    $special_embeds = $conn->query("SELECT * FROM special_embeds ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $special_embeds = []; }


// ------------------ YOUTUBE SHORTS HANDLER ------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sync_shorts'])) {
    $playlist_id = trim($_POST['playlist_id']);
    
    if (!empty($playlist_id)) {
        // Save Playlist ID to Settings
        $stmt = $conn->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('shorts_playlist_id', :val) ON DUPLICATE KEY UPDATE setting_value = :val");
        $stmt->execute([':val' => $playlist_id]);

        // Call YouTube API
        $api_url = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=$playlist_id&key=$api_key";
        $response = @file_get_contents($api_url);
        
        if ($response) {
            $data = json_decode($response, true);
            if (isset($data['items'])) {
                $added_count = 0;
                $stmt = $conn->prepare("INSERT IGNORE INTO youtube_shorts (video_id, title, thumbnail_url, published_at) VALUES (:vid, :title, :thumb, :pub)");
                
                foreach ($data['items'] as $item) {
                    $vid = $item['snippet']['resourceId']['videoId'];
                    $title = $item['snippet']['title'];
                    $thumb = $item['snippet']['thumbnails']['high']['url'] ?? '';
                    $pub = date('Y-m-d H:i:s', strtotime($item['snippet']['publishedAt']));

                    if ($title != "Private video" && $title != "Deleted video") {
                        $stmt->execute([':vid' => $vid, ':title' => $title, ':thumb' => $thumb, ':pub' => $pub]);
                        if ($stmt->rowCount() > 0) $added_count++;
                    }
                }
                $shorts_message = "Success! Synced $added_count new shorts from YouTube.";
            } else {
                $shorts_message = "API Error: No items found. Check Playlist ID.";
            }
        } else {
            $shorts_message = "Connection Error: Could not reach YouTube API. Check API Key.";
        }
    } else {
        $shorts_message = "Please enter a Playlist ID.";
    }
}

// Handle Delete Short
if (isset($_GET['delete_short']) && is_numeric($_GET['delete_short'])) {
    $id = (int)$_GET['delete_short'];
    $conn->prepare("DELETE FROM youtube_shorts WHERE id = ?")->execute([$id]);
    $shorts_message = "Short deleted successfully!";
}

// Fetch Shorts & Playlist ID
$saved_playlist_id = '';
try {
    $row = $conn->query("SELECT setting_value FROM site_settings WHERE setting_key = 'shorts_playlist_id'")->fetch(PDO::FETCH_ASSOC);
    $saved_playlist_id = $row ? $row['setting_value'] : '';
    $shorts = $conn->query("SELECT * FROM youtube_shorts ORDER BY published_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $shorts = []; }





// --------------------------
// Handle Sort Order Update
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sort_order_update'])) {
    foreach ($_POST['sort_order'] as $id => $order) {
        $order = (int)$order;
        $id = (int)$id;
        try {
            $stmt = $conn->prepare("UPDATE teledramas SET sort_order = :sort_order WHERE id = :id");
            $stmt->execute([
                ':sort_order' => $order,
                ':id' => $id
            ]);
        } catch (Exception $e) {
            error_log("Error updating sort order for ID $id: " . $e->getMessage());
        }
    }
    $teledrama_message = "Sort order updated successfully!";
}

// ---------------------------
// Fetch all Teledramas
// ---------------------------
$teledramas = [];
try {
    $stmt = $conn->query("SELECT * FROM teledramas ORDER BY sort_order ASC, id DESC");
    $teledramas = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log("Error fetching teledramas: " . $e->getMessage());
}

// ------------------ BANNER UPLOAD HANDLER ------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['banner_image'])) {
    $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/banners/';
    $link_url = trim($_POST['link_url'] ?? ''); // ✅ New: banner link URL
    $banner_message = '';

    // Ensure directory exists
    if (!file_exists($target_dir)) {
        if (!mkdir($target_dir, 0755, 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_stable/logs/php_errors.log");
        }
    }

    // Check if directory writable
    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_stable/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));

        // Validate file
        if ($_FILES['banner_image']['size'] > 2000000) {
            $banner_message = "Error: File is too large. Maximum size is 2MB.";
        } elseif ($_FILES['banner_image']['error'] !== UPLOAD_ERR_OK) {
            $banner_message = "Error uploading file.";
        } else {
            $valid_extensions = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp'];
            if (!in_array($imageFileType, $valid_extensions)) {
                $banner_message = "Invalid file type. Only JPG, PNG, GIF, SVG, and WEBP are allowed.";
            } else {
                $check = ($imageFileType === 'svg')
                    ? simplexml_load_string(file_get_contents($_FILES['banner_image']['tmp_name'])) !== false
                    : getimagesize($_FILES['banner_image']['tmp_name']);

                if (!$check) {
                    $banner_message = "Invalid image file.";
                } elseif (file_exists($target_file)) {
                    $banner_message = "Error: File already exists.";
                } else {
                    if (move_uploaded_file($_FILES['banner_image']['tmp_name'], $target_file)) {
                        try {
                            $stmt = $conn->prepare("INSERT INTO banners (image_path, link_url) VALUES (:image_path, :link_url)");
                            $stmt->execute([
                                ':image_path' => $banner_image,
                                ':link_url' => $link_url
                            ]);
                            $banner_message = "Banner uploaded successfully!";
                        } catch (Exception $e) {
                            $banner_message = "Database error: " . htmlspecialchars($e->getMessage());
                            if (file_exists($target_file)) unlink($target_file);
                        }
                    } else {
                        $banner_message = "Error moving uploaded file.";
                    }
                }
            }
        }
    }
}

// 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'] . '/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/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/logs/php_errors.log");
    }
}




// ---------------------------
// Handle Add/Update Teledrama
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['title']) && !isset($_POST['sort_order_update'])) {

    $teledrama_id     = filter_input(INPUT_POST, 'teledrama_id', FILTER_SANITIZE_NUMBER_INT);
    $title            = filter_input(INPUT_POST, 'title', FILTER_SANITIZE_STRING);
    // NEW: Capture the category input
    $category         = filter_input(INPUT_POST, 'category', 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'] . '/Uploads/teledramas/';
    $teledrama_message = '';

// Slug generation logic
    if (function_exists('create_slug')) { 
        $slug = create_slug($title); 
    } else { 
        // FIX: Convert to lowercase FIRST, then replace special characters
        $lowercase_title = strtolower(trim($title));
        $slug = trim(preg_replace('/[^a-z0-9-]+/', '-', $lowercase_title), '-'); 
        
        // Remove double hyphens if there were multiple spaces
        $slug = preg_replace('/-+/', '-', $slug);
    }

    // Image upload logic
    if (isset($_FILES['cover_image']) && $_FILES['cover_image']['error'] === UPLOAD_ERR_OK) {
        $cover_image = basename($_FILES['cover_image']['name']);
        move_uploaded_file($_FILES['cover_image']['tmp_name'], $target_dir . $cover_image);
    }

    try {
        if (empty($teledrama_message)) {
            if ($teledrama_id) {
                // UPDATE Existing: Added 'category = :category'
                $stmt = $conn->prepare("
                    UPDATE teledramas 
                    SET title = :title, slug = :slug, category = :category, description = :description, youtube_playlist = :youtube_playlist, cover_image = :cover_image
                    WHERE id = :id
                ");
                $stmt->execute([
                    ':title' => $title, ':slug' => $slug, ':category' => $category, 
                    ':description' => $description, ':youtube_playlist' => $youtube_playlist, 
                    ':cover_image' => $cover_image, ':id' => $teledrama_id
                ]);
                $new_teledrama_id = $teledrama_id;
                $teledrama_message = "Teledrama updated successfully!";
            } else {
                // INSERT New: Added 'category'
                $stmt = $conn->prepare("
                    INSERT INTO teledramas (title, slug, category, description, youtube_playlist, cover_image, sort_order, created_at, thumbnail_updated_at)
                    VALUES (:title, :slug, :category, :description, :youtube_playlist, :cover_image, 0, NOW(), NOW())
                ");
                $stmt->execute([
                    ':title' => $title, ':slug' => $slug, ':category' => $category, 
                    ':description' => $description, ':youtube_playlist' => $youtube_playlist, 
                    ':cover_image' => $cover_image
                ]);
                $new_teledrama_id = $conn->lastInsertId();
                $teledrama_message = "Teledrama added successfully!";
            }
            
            // Fetch playlist videos
             if (!empty($youtube_playlist)) {
                try {
                    fetchPlaylistVideosAndUpdate($youtube_playlist, $api_key, $conn, $new_teledrama_id, 'teledrama_videos', 'teledramas', 'teledrama');
                } catch (Exception $e) { error_log("Error fetching: " . $e->getMessage()); }
            }
        }
    } catch (Exception $e) {
        $teledrama_message = "Error saving teledrama: " . htmlspecialchars($e->getMessage());
    }
}

// ---------------------------
// Handle Programme Submission
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['programme_title']) && !isset($_POST['update_sort_order'])) {

    $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      = '';
    $programme_message = '';

    $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/programmes/';
    if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);

    // Handle cover image upload
    if (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', 'svg'])) {
            $programme_message = "Invalid image file. Please upload JPG, PNG, GIF, or SVG.";
        } elseif (file_exists($target_file)) {
            $programme_message = "Error: File already exists.";
        } elseif (!move_uploaded_file($_FILES['cover_image']['tmp_name'], $target_file)) {
            $programme_message = "Error uploading cover image.";
        }
    }

    try {
        if (empty($programme_message)) {
            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
                ");
                $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, sort_order, created_at, thumbnail_updated_at)
                    VALUES (:title, :description, :youtube_playlist, :cover_image, 0, NOW(), NOW())
                ");
                $stmt->execute([
                    ':title' => $title,
                    ':description' => $description,
                    ':youtube_playlist' => $youtube_playlist,
                    ':cover_image' => $cover_image
                ]);
                $new_programme_id = $conn->lastInsertId();
                $programme_message = "Programme added successfully!";
            }

            // ----- Fetch episodes and update thumbnails immediately -----
            if (!empty($youtube_playlist)) {
                try {
                    fetchPlaylistVideosAndUpdate(
                        $youtube_playlist,
                        $api_key,
                        $conn,
                        $new_programme_id,
                        'programmes_videos', // table for programme videos
                        'programmes',        // main table
                        'programme'          // type for logic (for thumbnail update)
                    );
                } catch (Exception $e) {
                    error_log("Error fetching episodes for programme ID {$new_programme_id}: " . $e->getMessage());
                }
            }
        }

    } catch (Exception $e) {
        $programme_message = "Error saving programme: " . htmlspecialchars($e->getMessage());
    }
}


// -----------------------------
// Handle Programme Deletion
// -----------------------------
if (isset($_GET['delete_programme']) && is_numeric($_GET['delete_programme'])) {
    $id = (int)$_GET['delete_programme'];
    $stmt = $conn->prepare("DELETE FROM programmes WHERE id=:id");
    $stmt->execute([':id' => $id]);
    $programme_message = "Programme deleted successfully!";
}

// -----------------------------
// Handle Sort Order Update
// -----------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_sort_order'])) {
    foreach ($_POST['sort_order'] as $id => $order) {
        $stmt = $conn->prepare("UPDATE programmes SET sort_order=:sort_order WHERE id=:id");
        $stmt->execute([
            ':sort_order' => (int)$order,
            ':id' => (int)$id
        ]);
    }
    $programme_message = "Sort order updated successfully!";
}

// 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/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/logs/php_errors.log");
        }
    } else {
        $schedule_message = "Invalid schedule ID.";
    }

}

// ------------------ AD UPLOAD HANDLER ------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['ad_image'])) {
    // Make sure path is correct for your local setup
    $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/ads/';
    $link_url = trim($_POST['ad_link_url'] ?? '');
    $start_date = !empty($_POST['ad_start_date']) ? $_POST['ad_start_date'] : NULL;
    $end_date   = !empty($_POST['ad_end_date'])   ? $_POST['ad_end_date']   : NULL;

    $ad_message = '';

    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0755, true);
    }

    if (!is_writable($target_dir)) {
        $ad_message = "Error: Ads upload directory is not writable.";
    } else {
        $ad_image = basename($_FILES['ad_image']['name']);
        $target_file = $target_dir . $ad_image;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

        // Validate file (using 1000x300 as a reference, but not enforcing)
        $check = getimagesize($_FILES['ad_image']['tmp_name']);
        if (!$check) {
            $ad_message = "Invalid image file.";
        } elseif (file_exists($target_file)) {
            $ad_message = "Error: File already exists.";
        } elseif ($_FILES['ad_image']['size'] > 2000000) { // 2MB limit
            $ad_message = "Error: File is too large.";
        } else {
            if (move_uploaded_file($_FILES['ad_image']['tmp_name'], $target_file)) {
try {
                    // 1. UPDATE THIS LINE (Must have 4 placeholders)
                    $stmt = $conn->prepare("INSERT INTO horizontal_ads (image_path, link_url, start_date, end_date) VALUES (:image_path, :link_url, :start_date, :end_date)");
                    
                    // 2. UPDATE THIS BLOCK (Must match the 4 placeholders above)
                    $stmt->execute([
                        ':image_path' => $ad_image,
                        ':link_url'   => $link_url,
                        ':start_date' => $start_date,
                        ':end_date'   => $end_date
                    ]);
                    
                    $ad_message = "Ad uploaded successfully!";
                } catch (Exception $e) {
                    $ad_message = "Database error: " . htmlspecialchars($e->getMessage());
                    if (file_exists($target_file)) unlink($target_file);
                }
            } else {
                $ad_message = "Error moving uploaded file.";
            }
        }
    }
}

// Handle Ad Deletion
if (isset($_GET['delete_ad']) && is_numeric($_GET['delete_ad'])) {
    $id = (int)$_GET['delete_ad'];
    try {
        // First, get the image path to delete the file
        $stmt = $conn->prepare("SELECT image_path FROM horizontal_ads WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $ad = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($ad) {
            // Make sure path is correct for your local setup
            $file_path = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/ads/' . $ad['image_path'];
            if (file_exists($file_path)) {
                unlink($file_path);
            }
            
            // Now, delete from database
            $stmt = $conn->prepare("DELETE FROM horizontal_ads WHERE id = :id");
            $stmt->execute([':id' => $id]);
            $ad_message = "Ad deleted successfully!";
        } else {
            $ad_message = "Ad not found.";
        }
    } catch (Exception $e) {
        $ad_message = "Error deleting ad: " . htmlspecialchars($e->getMessage());
    }
}

// =======================================================
// START: LIVE PLAYER AD HANDLERS
// =======================================================

// ------------------ LIVE TOP AD UPLOAD ------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['live_top_ad_image'])) {
    $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/ads_live_top/';
    $link_url = trim($_POST['live_top_ad_link_url'] ?? '');

    if (!file_exists($target_dir)) mkdir($target_dir, 0755, true);

    if (!is_writable($target_dir)) {
        $live_top_ad_message = "Error: Top ad directory is not writable.";
    } else {
        $image_name = basename($_FILES['live_top_ad_image']['name']);
        $target_file = $target_dir . $image_name;

        if (move_uploaded_file($_FILES['live_top_ad_image']['tmp_name'], $target_file)) {
            try {
                $stmt = $conn->prepare("INSERT INTO live_top_ads (image_path, link_url) VALUES (:image_path, :link_url)");
                $stmt->execute([':image_path' => $image_name, ':link_url' => $link_url]);
                $live_top_ad_message = "Live Top Ad uploaded successfully!";
            } catch (Exception $e) {
                $live_top_ad_message = "Database error: " . $e->getMessage();
            }
        } else {
            $live_top_ad_message = "Error moving uploaded file.";
        }
    }
}

// ------------------ LIVE TOP AD DELETE ------------------
if (isset($_GET['delete_live_top_ad']) && is_numeric($_GET['delete_live_top_ad'])) {
    $id = (int)$_GET['delete_live_top_ad'];
    try {
        $stmt = $conn->prepare("SELECT image_path FROM live_top_ads WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $ad = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($ad) {
            $file_path = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/ads_live_top/' . $ad['image_path'];
            if (file_exists($file_path)) unlink($file_path);
            
            $stmt = $conn->prepare("DELETE FROM live_top_ads WHERE id = :id");
            $stmt->execute([':id' => $id]);
            $live_top_ad_message = "Live Top Ad deleted successfully!";
        }
    } catch (Exception $e) {
        $live_top_ad_message = "Error deleting ad: " . $e->getMessage();
    }
}

// ------------------ LIVE SIDE AD UPLOAD ------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['live_side_ad_image'])) {
    $target_dir = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/ads_live_side/';
    $link_url = trim($_POST['live_side_ad_link_url'] ?? '');

    if (!file_exists($target_dir)) mkdir($target_dir, 0755, true);

    if (!is_writable($target_dir)) {
        $live_side_ad_message = "Error: Side ad directory is not writable.";
    } else {
        $image_name = basename($_FILES['live_side_ad_image']['name']);
        $target_file = $target_dir . $image_name;

        if (move_uploaded_file($_FILES['live_side_ad_image']['tmp_name'], $target_file)) {
            try {
                $stmt = $conn->prepare("INSERT INTO live_side_ads (image_path, link_url) VALUES (:image_path, :link_url)");
                $stmt->execute([':image_path' => $image_name, ':link_url' => $link_url]);
                $live_side_ad_message = "Live Side Ad uploaded successfully!";
            } catch (Exception $e) {
                $live_side_ad_message = "Database error: " . $e->getMessage();
            }
        } else {
            $live_side_ad_message = "Error moving uploaded file.";
        }
    }
}

// ------------------ LIVE SIDE AD DELETE ------------------
if (isset($_GET['delete_live_side_ad']) && is_numeric($_GET['delete_live_side_ad'])) {
    $id = (int)$_GET['delete_live_side_ad'];
    try {
        $stmt = $conn->prepare("SELECT image_path FROM live_side_ads WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $ad = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($ad) {
            $file_path = $_SERVER['DOCUMENT_ROOT'] . '/Uploads/ads_live_side/' . $ad['image_path'];
            if (file_exists($file_path)) unlink($file_path);
            
            $stmt = $conn->prepare("DELETE FROM live_side_ads WHERE id = :id");
            $stmt->execute([':id' => $id]);
            $live_side_ad_message = "Live Side Ad deleted successfully!";
        }
    } catch (Exception $e) {
        $live_side_ad_message = "Error deleting ad: " . $e->getMessage();
    }
}

// =======================================================
// END: LIVE PLAYER AD HANDLERS
// =======================================================

// Fetch all banners
try {
    $banners = $conn->query("SELECT * FROM banners ORDER BY sort_order ASC, id 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/logs/php_errors.log");
    $banners = [];
}




// 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/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/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/logs/php_errors.log");
    $schedule_entries = [];
}

// Fetch all ads
try {
    $horizontal_ads = $conn->query("SELECT * FROM horizontal_ads ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $ad_message = "Error fetching ads: " . htmlspecialchars($e->getMessage());
    $horizontal_ads = [];
}

// Fetch all live player ads
try {
    $live_top_ads = $conn->query("SELECT * FROM live_top_ads ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $live_top_ad_message = "Error fetching top ads: " . $e->getMessage();
    $live_top_ads = [];
}
try {
    $live_side_ads = $conn->query("SELECT * FROM live_side_ads ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $live_side_ad_message = "Error fetching side ads: " . $e->getMessage();
    $live_side_ads = [];
}

require __DIR__ . '/../components/header.php';
?>

<div class="container mt-5">
    <a href="logout.php" class="btn btn-danger">Logout</a>
    <h1 class="page-title"><?php echo htmlspecialchars($page_title); ?></h1>
    
    

<ul class="nav nav-tabs mb-4" id="dashboardTabs" role="tablist">
    
    <li class="nav-item" role="presentation">
    <button class="nav-link" id="shorts-new-tab" data-bs-toggle="tab" data-bs-target="#shorts-new" type="button" role="tab" aria-controls="shorts-new" aria-selected="false">YouTube Shorts (Tharu Reyak)</button>
</li>
    
    <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">
    <button class="nav-link" id="events-tab" data-bs-toggle="tab" data-bs-target="#events" type="button">Manage Events</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>
<li class="nav-item" role="presentation">
        <button class="nav-link" id="ads-tab" data-bs-toggle="tab" data-bs-target="#ads" type="button" role="tab" aria-controls="ads" aria-selected="false">Ad Management</button>
    </li>

<li class="nav-item" role="presentation">
        <button class="nav-link" id="live-ads-tab" data-bs-toggle="tab" data-bs-target="#live-ads" type="button" role="tab" aria-controls="live-ads" aria-selected="false">Live Player Ads</button>
    </li>


<li class="nav-item" role="presentation">
    <button class="nav-link" id="shorts-tab" data-bs-toggle="tab" data-bs-target="#shorts" type="button" role="tab">YouTube Shorts</button>
</li>
<li class="nav-item" role="presentation">
    <button class="nav-link" id="embeds-tab" data-bs-toggle="tab" data-bs-target="#embeds" type="button" role="tab">Custom Embeds</button>
</li>
</ul>



<div class="tab-content" id="dashboardTabContent">
    
    <div class="tab-pane fade" id="shorts-new" role="tabpanel" aria-labelledby="shorts-new-tab">
    <h2 class="section-title">Manage Tharu Reyak Shorts Feed</h2>
    
    <?php if ($shorts_message_new): ?>
        <div class="alert alert-info"><?php echo $shorts_message_new; ?></div>
    <?php endif; ?>

    <div class="card p-4 mb-4" style="background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2);">
        <form method="POST">
            <div class="mb-3">
                <label class="form-label text-white">YouTube Playlist ID (Feed 2)</label>
                <input type="text" name="playlist_id_new" class="form-control" value="<?php echo htmlspecialchars($saved_playlist_id_new); ?>" placeholder="e.g. PLrEnWoR732..." required>
                <small class="text-white-50">This playlist will only show on the Tharu Reyak page.</small>
            </div>
            <button type="submit" name="sync_shorts_new" class="btn btn-primary">
                Sync Tharu Reyak Feed
            </button>
        </form>
    </div>

    <h3 class="section-title">Synced Shorts (Playlist 2)</h3>
    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>Thumb</th>
                    <th>Title</th>
                    <th>Published</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if(!empty($shorts_new)): ?>
                    <?php foreach ($shorts_new as $s): ?>
                    <tr>
                        <td><img src="<?php echo $s['thumbnail_url']; ?>" style="height: 50px; border-radius: 4px;"></td>
                        <td><?php echo htmlspecialchars($s['title']); ?></td>
                        <td><?php echo date('M d, Y', strtotime($s['published_at'])); ?></td>
                        <td>
                            <a href="?delete_short_new=<?php echo $s['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Remove this short from the second feed?');">Remove</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="4" class="text-center">No shorts synced yet for this feed.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
    
    <div class="tab-pane fade show active" id="teledrama" role="tabpanel" aria-labelledby="teledrama-tab">
        <h2 class="mb-4">Teledrama Management</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 mb-5">
            <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="category" class="form-label">Category</label>
    <select id="category" name="category" class="form-control">
        <option value="weekday">Weekday (Mon-Fri)</option>
        <option value="weekend">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"></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>
<h3 class="section-title mb-3">All Teledramas</h3>
        <div class="table-responsive">
            <table class="table table-bordered table-striped align-middle">
                <thead class="table-dark">
                    <tr>
                        <th style="width: 50px; text-align: center;">Drag</th>
                        <th style="width: 50px; text-align: center;">#</th> <th>ID</th>
                        <th>Cover</th>
                        <th>Title</th>
                        <th>Category</th>
                        <th>Description</th>
                        <th>YouTube Playlist</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="sortable-teledramas">
                    <?php if (!empty($teledramas)) { ?>
                        <?php 
                        $position = 1; // Start counting from 1
                        foreach ($teledramas as $td) { 
                        ?>
                            <tr data-id="<?php echo $td['id']; ?>">
                                
                                <td style="cursor: grab; font-size: 20px; color: #888; text-align: center;">☰</td>
                                
                                <td class="row-position fw-bold text-center"><?php echo $position++; ?></td>
                                
                                <td><?php echo $td['id']; ?></td>

                                <td>
                                    <?php if ($td['cover_image']) { ?>
                                        <img src="<?php echo BASE_URL; ?>swarnawahini_web_stable/uploads/teledramas/<?php echo htmlspecialchars($td['cover_image']); ?>" width="80" style="border-radius:5px;">
                                    <?php } ?>
                                </td>

                                <td><?php echo htmlspecialchars($td['title']); ?></td>

                                <td>
                                    <?php if (isset($td['category']) && $td['category'] == 'weekend'): ?>
                                        <span class="badge bg-warning text-dark">Weekend</span>
                                    <?php else: ?>
                                        <span class="badge bg-info text-dark">Weekday</span>
                                    <?php endif; ?>
                                </td>

                                <td><?php echo htmlspecialchars($td['description']); ?></td>

                                <td><?php echo htmlspecialchars($td['youtube_playlist']); ?></td>

                                <td>
                                    <a href="edit_teledrama.php?id=<?php echo $td['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                                    <a href="?delete_id=<?php echo $td['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this teledrama?');">Delete</a>
                                </td>
                            </tr>
                        <?php } ?>
                    <?php } else { ?>
                        <tr>
                            <td colspan="9" class="text-center">No teledramas found.</td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        </div>
        </div>

    <div class="tab-pane fade" id="banner" role="tabpanel" aria-labelledby="banner-tab">
    <h2 class="section-title">Manage Banners</h2>

    <?php if (!empty($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>

        <div class="mb-3">
            <label for="link_url" class="form-label">Banner Link (Optional)</label>
            <input type="url" id="link_url" name="link_url" class="form-control" placeholder="https://example.com">
        </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" id="sortable-banners">
            <?php foreach ($banners as $banner) { ?>
                <div class="col" data-id="<?php echo $banner['id']; ?>">
                    <div class="card h-100 shadow-sm">
                        <div class="card-header bg-dark text-white text-center drag-handle" style="cursor: grab;">
                            ☰ Drag to Reorder
                        </div>
                        
                        <img src="<?php echo BASE_URL; ?>Uploads/banners/<?php echo htmlspecialchars($banner['image_path']); ?>" class="card-img-top" alt="Banner" style="height: 150px; object-fit: cover;">
                        
                        <div class="card-body text-center">
                            <?php if (!empty($banner['link_url'])) { ?>
                                <p class="text-truncate"><strong>Link:</strong> <a href="<?php echo htmlspecialchars($banner['link_url']); ?>" target="_blank">
                                    <?php echo htmlspecialchars($banner['link_url']); ?>
                                </a></p>
                            <?php } ?>
                            <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>


<div class="tab-pane fade" id="events" role="tabpanel">
    <div class="card mb-4">
        <div class="card-header bg-primary text-white">Add New Event</div>
        <div class="card-body">
            <?php if ($event_message): ?>
                <div class="alert alert-info"><?php echo $event_message; ?></div>
            <?php endif; ?>
            <form method="POST" enctype="multipart/form-data" class="row g-3">
                <div class="col-md-4">
                    <input type="text" name="event_title" class="form-control" placeholder="Event Title" required>
                </div>
                <div class="col-md-4">
                    <input type="text" name="event_page_url" class="form-control" placeholder="Link (e.g. rideerayak.php)" required>
                </div>
                <div class="col-md-3">
                    <input type="file" name="event_thumb" class="form-control" required>
                </div>
                <div class="col-md-1">
                    <button type="submit" name="add_event" class="btn btn-success">Add</button>
                </div>
            </form>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table table-hover align-middle">
            <thead>
                <tr>
                    <th>Thumbnail</th>
                    <th>Title</th>
                    <th>Link</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $stmt = $conn->query("SELECT * FROM events ORDER BY created_at DESC");
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)): ?>
                <tr>
                    <td><img src="/Uploads/events/<?php echo $row['thumbnail_url']; ?>" width="60" class="rounded"></td>
                    <td><?php echo htmlspecialchars($row['title']); ?></td>
                    <td><small><?php echo htmlspecialchars($row['event_page_url']); ?></small></td>
                    <td><a href="?delete_event=<?php echo $row['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete event?')">Delete</a></td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</div>

    

   <div class="tab-pane fade" id="programme" role="tabpanel" aria-labelledby="programme-tab">
    <h2 class="section-title">Add New Programme</h2>
    <?php if (!empty($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">
        <input type="hidden" name="programme_id" value="">
        <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>
    <form method="POST">
        <input type="hidden" name="update_sort_order" value="1">
        <table class="table table-bordered table-striped">
            <thead class="table-dark">
                <tr>
                <th>ID</th>
                <th>Cover</th>
                <th>Title</th>
                <th>Category</th>  <th>Description</th>
                <th>YouTube Playlist</th>
                <th>Sort Order</th>
                <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($programmes as $programme): ?>
                    <tr>
                        <td><input type="number" name="sort_order[<?php echo $programme['id']; ?>]" value="<?php echo $programme['sort_order']; ?>" class="form-control" style="width:80px"></td>
                        <td>
                            <?php if (!empty($programme['cover_image'])): ?>
                                <img src="<?php echo BASE_URL; ?>swarnawahini_web_stable/uploads/programmes/<?php echo htmlspecialchars($programme['cover_image']); ?>" width="60" height="40">
                            <?php endif; ?>
                        </td>
                        <td><?php echo htmlspecialchars($programme['title']); ?></td>
                        <td><?php echo htmlspecialchars($programme['description']); ?></td>
                        <td><?php echo htmlspecialchars($programme['youtube_playlist']); ?></td>
                        <td>
                            <a href="edit_programme.php?id=<?php echo $programme['id']; ?>" class="btn btn-sm btn-primary">Edit</a>
                            <a href="?delete_programme=<?php echo $programme['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this programme?');">Delete</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <button type="submit" class="btn btn-warning">Update Order</button>
    </form>
</div>

   <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>
                                <div class="message-short" id="short-<?php echo $message['id']; ?>">
                                    <?php echo htmlspecialchars(substr($message['message'], 0, 100)); ?>
                                    <?php if (strlen($message['message']) > 100) { ?>
                                        ... <button class="btn btn-link p-0" onclick="toggleMessage(<?php echo $message['id']; ?>)">See More</button>
                                    <?php } ?>
                                </div>

                                <div class="message-full d-none" id="full-<?php echo $message['id']; ?>">
                                    <?php echo nl2br(htmlspecialchars($message['message'])); ?>
                                    <br>
                                    <button class="btn btn-link p-0" onclick="toggleMessage(<?php echo $message['id']; ?>)">See Less</button>
                                </div>
                            </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>

<script>
function toggleMessage(id) {
    const shortMsg = document.getElementById(`short-${id}`);
    const fullMsg = document.getElementById(`full-${id}`);

    if (shortMsg.classList.contains('d-none')) {
        shortMsg.classList.remove('d-none');
        fullMsg.classList.add('d-none');
    } else {
        shortMsg.classList.add('d-none');
        fullMsg.classList.remove('d-none');
    }
}
</script>


    <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">Now Showing</h3>
        <?php
        date_default_timezone_set("Asia/Colombo"); // adjust to your timezone
        $currentDay = date('l'); // Monday, Tuesday...
        $currentTime = date('H:i:s');

        $now_stmt = $conn->prepare("
            SELECT * FROM tv_schedule 
            WHERE day = :day 
            AND time <= :time 
            ORDER BY time DESC 
            LIMIT 1
        ");
        $now_stmt->execute([':day' => $currentDay, ':time' => $currentTime]);
        $now_program = $now_stmt->fetch(PDO::FETCH_ASSOC);
        ?>

        <?php if ($now_program): ?>
            <div class="alert alert-info">
                <strong><?php echo htmlspecialchars($now_program['program_name']); ?></strong> 
                is showing now (<?php echo date('h:i A', strtotime($now_program['time'])); ?>)
            </div>
        <?php else: ?>
            <div class="alert alert-warning">No program currently airing.</div>
        <?php endif; ?>

        <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 class="tab-pane fade" id="ads" role="tabpanel" aria-labelledby="ads-tab">
    <h2 class="section-title">Manage Horizontal Ads</h2>

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

    <form method="POST" enctype="multipart/form-data" class="glass-form mb-4">
        <div class="mb-3">
            <label for="ad_image" class="form-label">Upload New Ad (Recommended 1000x300)</label>
            <input type="file" id="ad_image" name="ad_image" class="form-control" accept="image/*" required>
        </div>
        <div class="mb-3">
            <label for="ad_link_url" class="form-label">Ad Link (Optional)</label>
            <input type="url" id="ad_link_url" name="ad_link_url" class="form-control" placeholder="https://example.com">
        </div>
        
        <div class="row">
            <div class="col-md-6 mb-3">
                <label for="ad_start_date" class="form-label">Start Date (Optional)</label>
                <input type="datetime-local" id="ad_start_date" name="ad_start_date" class="form-control">
                <small class="text-muted">Leave empty to show immediately.</small>
            </div>
            <div class="col-md-6 mb-3">
                <label for="ad_end_date" class="form-label">End Date (Optional)</label>
                <input type="datetime-local" id="ad_end_date" name="ad_end_date" class="form-control">
                <small class="text-muted">Leave empty to run forever.</small>
            </div>
        </div>
        <button type="submit" class="btn btn-primary">Upload Ad</button>
    </form>

    <h3 class="section-title mt-4">Uploaded Ads</h3>
    <?php if (!empty($horizontal_ads)) { ?>
        <div class="row row-cols-1 row-cols-md-3 g-4">
            <?php foreach ($horizontal_ads as $ad) { ?>
                <div class="col">
                    <div class="card h-100">
                        <img src="<?php echo BASE_URL; ?>Uploads/ads/<?php echo htmlspecialchars($ad['image_path']); ?>" class="card-img-top" alt="Ad" style="height: 100px; object-fit: cover;">
                        <div class="card-body">
                            <?php if (!empty($ad['link_url'])) { ?>
                                <p class="mb-2 text-truncate"><strong>Link:</strong> <a href="<?php echo htmlspecialchars($ad['link_url']); ?>" target="_blank">
                                    <?php echo htmlspecialchars($ad['link_url']); ?>
                                </a></p>
                            <?php } ?>
                            
                            <div class="mb-3 small">
                                <div><strong>Start:</strong> <?php echo $ad['start_date'] ? date('Y-m-d H:i', strtotime($ad['start_date'])) : '<span class="text-success">Immediately</span>'; ?></div>
                                <div><strong>End:</strong> <?php echo $ad['end_date'] ? date('Y-m-d H:i', strtotime($ad['end_date'])) : '<span class="text-success">Forever</span>'; ?></div>
                            </div>
                            <a href="?delete_ad=<?php echo $ad['id']; ?>" class="btn btn-danger btn-sm w-100" onclick="return confirm('Are you sure you want to delete this ad?');">Delete</a>
                        </div>
                    </div>
                </div>
            <?php } ?>
        </div>
    <?php } else { ?>
        <p>No ads uploaded yet.</p>
    <?php } ?>


</div><div class="tab-pane fade" id="live-ads" role="tabpanel" aria-labelledby="live-ads-tab">
    
    <h2 class="section-title">Manage Live Top Banner (460x50)</h2>
    <?php if (!empty($live_top_ad_message)) { ?>
        <div class="alert alert-<?php echo strpos($live_top_ad_message, 'Error') !== false ? 'danger' : 'success'; ?>">
            <?php echo htmlspecialchars($live_top_ad_message); ?>
        </div>
    <?php } ?>

    <form method="POST" enctype="multipart/form-data" class="glass-form mb-4">
        <div class="mb-3">
            <label for="live_top_ad_image" class="form-label">Upload New Top Ad (460x50)</label>
            <input type="file" id="live_top_ad_image" name="live_top_ad_image" class="form-control" accept="image/*" required>
        </div>
        <div class="mb-3">
            <label for="live_top_ad_link_url" class="form-label">Ad Link (Optional)</label>
            <input type="url" id="live_top_ad_link_url" name="live_top_ad_link_url" class="form-control" placeholder="https://example.com">
        </div>
        <button type="submit" class="btn btn-primary">Upload Top Ad</button>
    </form>

    <h3 class="section-title mt-4">Uploaded Top Ads</h3>
    <?php if (!empty($live_top_ads)) { ?>
        <div class="row row-cols-1 row-cols-md-3 g-4">
            <?php foreach ($live_top_ads as $ad) { ?>
                <div class="col">
                    <div class="card">
                        <img src="<?php echo BASE_URL; ?>Uploads/ads_live_top/<?php echo htmlspecialchars($ad['image_path']); ?>" class="card-img-top" alt="Top Ad">
                        <div class="card-body">
                            <a href="?delete_live_top_ad=<?php echo $ad['id']; ?>" class="btn btn-danger" onclick="return confirm('Delete this ad?');">Delete</a>
                        </div>
                    </div>
                </div>
            <?php } ?>
        </div>
    <?php } else { ?><p>No top ads uploaded.</p><?php } ?>

    <hr class="my-5">

    <h2 class="section-title">Manage Live Side Banners (160x600)</h2>
    <?php if (!empty($live_side_ad_message)) { ?>
        <div class="alert alert-<?php echo strpos($live_side_ad_message, 'Error') !== false ? 'danger' : 'success'; ?>">
            <?php echo htmlspecialchars($live_side_ad_message); ?>
        </div>
    <?php } ?>

    <form method="POST" enctype="multipart/form-data" class="glass-form mb-4">
        <div class="mb-3">
            <label for="live_side_ad_image" class="form-label">Upload New Side Ad (160x600)</label>
            <input type="file" id="live_side_ad_image" name="live_side_ad_image" class="form-control" accept="image/*" required>
        </div>
        <div class="mb-3">
            <label for="live_side_ad_link_url" class="form-label">Ad Link (Optional)</label>
            <input type="url" id="live_side_ad_link_url" name="live_side_ad_link_url" class="form-control" placeholder="https://example.com">
        </div>
        <button type="submit" class="btn btn-primary">Upload Side Ad</button>
    </form>

    <h3 class="section-title mt-4">Uploaded Side Ads</h3>
    <?php if (!empty($live_side_ads)) { ?>
        <div class="row row-cols-1 row-cols-md-4 g-4">
            <?php foreach ($live_side_ads as $ad) { ?>
                <div class="col">
                    <div class="card">
                        <img src="<?php echo BASE_URL; ?>Uploads/ads_live_side/<?php echo htmlspecialchars($ad['image_path']); ?>" class="card-img-top" alt="Side Ad" style="height: 200px; object-fit: cover;">
                        <div class="card-body">
                            <a href="?delete_live_side_ad=<?php echo $ad['id']; ?>" class="btn btn-danger" onclick="return confirm('Delete this ad?');">Delete</a>
                        </div>
                    </div>
                </div>
            <?php } ?>
        </div>
    <?php } else { ?><p>No side ads uploaded.</p><?php } ?>

</div>

<div class="tab-pane fade" id="embeds" role="tabpanel">
    <h2 class="section-title">Manage Custom Embeds (Non-YouTube)</h2>
    
    <?php if ($embed_message): ?>
        <div class="alert alert-info"><?php echo $embed_message; ?></div>
    <?php endif; ?>

    <form method="POST" class="glass-form mb-4" enctype="multipart/form-data">
        <div class="mb-3">
            <label class="form-label">Program Title</label>
            <input type="text" name="special_embed_title" class="form-control" placeholder="e.g. Live Event Stream" required>
        </div>
        
        <div class="mb-3">
            <label class="form-label">Custom Thumbnail (Optional)</label>
            <input type="file" name="special_embed_thumb" class="form-control" accept="image/*">
            <small class="text-white-50">Upload a cover image if the embed code doesn't have a good preview.</small>
        </div>

        <div class="mb-3">
            <label class="form-label">Embed Code (Raw HTML)</label>
            <textarea name="special_embed_code" class="form-control" rows="6" placeholder="Paste <iframe>, <video>, or <script> tags here..." required></textarea>
            <small class="text-white-50">Use this for players that are NOT YouTube (e.g. Facebook, Vimeo, Custom Servers).</small>
        </div>
        <button type="submit" class="btn btn-primary">Add Embed</button>
    </form>

    <h3 class="section-title">Existing Embeds</h3>
    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Thumb</th> <th>Title</th>
                    <th>Code Snippet</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($special_embeds as $embed): ?>
                <tr>
                    <td><?= $embed['id'] ?></td>
                    <td>
                        <?php if ($embed['thumbnail_url']): ?>
                            <img src="/swarnawahini_web_stable/uploads/embeds/<?= htmlspecialchars($embed['thumbnail_url']) ?>" style="height: 50px; width: auto; border-radius: 4px;">
                        <?php else: ?>
                            <span class="badge bg-secondary">No Image</span>
                        <?php endif; ?>
                    </td>
                    <td><?= htmlspecialchars($embed['title']) ?></td>
                    <td><code><?= htmlspecialchars(substr($embed['embed_code'], 0, 50)) ?>...</code></td>
                    <td>
                        <a href="?delete_embed=<?= $embed['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Delete this embed?');">Delete</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="tab-pane fade" id="shorts" role="tabpanel">
    <h2 class="section-title">Manage YouTube Shorts Feed</h2>
    
    <?php if ($shorts_message): ?>
        <div class="alert alert-info"><?php echo $shorts_message; ?></div>
    <?php endif; ?>

    <div class="card p-4 mb-4" style="background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.2);">
        <form method="POST">
            <div class="mb-3">
                <label class="form-label text-white">YouTube Playlist ID</label>
                <input type="text" name="playlist_id" class="form-control" value="<?php echo htmlspecialchars($saved_playlist_id); ?>" placeholder="e.g. PLrEnWoR732..." required>
                <small class="text-white-50">Find this in your YouTube URL: youtube.com/playlist?list=<b>THIS_PART</b></small>
            </div>
            <button type="submit" name="sync_shorts" class="btn btn-danger">
                Sync Now
            </button>
        </form>
    </div>

    <h3 class="section-title">Synced Shorts</h3>
    <div class="table-responsive">
        <table class="table table-bordered table-striped">
            <thead>
                <tr>
                    <th>Thumb</th>
                    <th>Title</th>
                    <th>Published</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if(!empty($shorts)): ?>
                    <?php foreach ($shorts as $short): ?>
                    <tr>
                        <td><img src="<?php echo $short['thumbnail_url']; ?>" style="height: 50px;"></td>
                        <td><?php echo htmlspecialchars($short['title']); ?></td>
                        <td><?php echo date('M d, Y', strtotime($short['published_at'])); ?></td>
                        <td>
                            <a href="?delete_short=<?php echo $short['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Remove this short?');">Remove</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr><td colspan="4" class="text-center">No shorts synced yet. Enter a playlist ID above.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</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 __DIR__ . '/../components/footer.php'; ?>

<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Teledrama Drag and Drop Sorting
    var teledramaTable = document.getElementById('sortable-teledramas');
    
    if (teledramaTable) {
        Sortable.create(teledramaTable, {
            animation: 150, 
            ghostClass: 'bg-light', 
            handle: 'td:first-child', // Only allow dragging from the icon
            
            onEnd: function (evt) {
                var order = [];
                
                // Loop through all rows to get the new order AND update the numbers
                teledramaTable.querySelectorAll('tr').forEach(function(row, index) {
                    // Push to our array for the database
                    order.push(row.getAttribute('data-id'));
                    
                    // NEW: Update the visual number instantly (index starts at 0, so add 1)
                    var positionCell = row.querySelector('.row-position');
                    if (positionCell) {
                        positionCell.innerText = index + 1;
                    }
                });

                // Send new order to PHP
                fetch('update_sort_order.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ order: order })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status !== 'success') {
                        alert('Error saving order: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            }
        });
    }
});

// Banner Drag and Drop Sorting
    var bannerTable = document.getElementById('sortable-banners');
    
    if (bannerTable) {
        Sortable.create(bannerTable, {
            animation: 150, 
            ghostClass: 'opacity-50', 
            handle: '.drag-handle', // Only drag by clicking the dark header bar
            
            onEnd: function (evt) {
                var order = [];
                
                // Get the new order of banner IDs
                bannerTable.querySelectorAll('.col').forEach(function(col) {
                    order.push(col.getAttribute('data-id'));
                });

                // Send new order to PHP
                fetch('update_banner_sort.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ order: order })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status !== 'success') {
                        alert('Error saving banner order: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            }
        });
    }
</script>