<?php
include('includes/header.php');

// Create api folder if it doesn't exist
if (!is_dir('api')) {
    mkdir('api', 0777, true);
}

// JSON file path for selector
$selector_file = 'api/selector.json';

// Read existing configuration or create new one
if (file_exists($selector_file)) {
    $content = file_get_contents($selector_file);
    $selector = json_decode($content, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        $selector = ['mode' => 'manualads.php'];
    }
} else {
    $selector = ['mode' => 'manualads.php'];
}

// Success message
$success_message = '';

// Process mode change
if (isset($_POST['save_mode'])) {
    $selected_mode = $_POST['mode'];
    if ($selected_mode == 'manual') {
        $selector['mode'] = 'manualads.php';
    } else if ($selected_mode == 'tmdb') {
        $selector['mode'] = 'posters.php';
    } else if ($selected_mode == 'posters1') {
        $selector['mode'] = 'posters1.php';
    } else if ($selected_mode == 'posters2') {
        $selector['mode'] = 'posters2.php';
    } else if ($selected_mode == 'posters3') {
        $selector['mode'] = 'posters3.php';
    }

    // Save to JSON
    $json = json_encode($selector, JSON_PRETTY_PRINT);
    file_put_contents($selector_file, $json);

    // Show success message
    $success_message = 'Mode saved successfully!';
}

// Determine active mode
$current_mode = ($selector['mode'] == 'manualads.php') ? 'manual' : 'tmdb';

// SQLite database configuration for ads
$db_path = 'api/ads.db';
$res = false;
$error = null;
$success = null;
$editingAd = null;

function sanitizeString($str) {
    return htmlspecialchars(strip_tags($str), ENT_QUOTES, 'UTF-8');
}

function sanitizeAndValidateUrl($url) {
    $url = filter_var($url, FILTER_SANITIZE_URL);
    if (filter_var($url, FILTER_VALIDATE_URL) === false) {
        return false;
    }
    return $url;
}

// Connect to SQLite database
try {
    $db = new SQLite3($db_path);

    // Check if the table exists and create it if not
    $tableCheck = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='ads'");
    if (!$tableCheck->fetchArray()) {
        $db->exec('CREATE TABLE ads (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT,
            url TEXT,
            created_on TEXT
        )');
    }

    // Handle delete action
    if (isset($_GET['delete'])) {
        $id = filter_var($_GET['delete'], FILTER_SANITIZE_NUMBER_INT);
        $stmt = $db->prepare('DELETE FROM ads WHERE id = :id');
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        
        if ($stmt->execute()) {
            $success = "Ad deleted successfully.";
        } else {
            $error = "Error deleting the ad: " . $db->lastErrorMsg();
        }
    }
    
    // Handle edit action
    if (isset($_GET['edit'])) {
        $id = filter_var($_GET['edit'], FILTER_SANITIZE_NUMBER_INT);
        $stmt = $db->prepare('SELECT * FROM ads WHERE id = :id');
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        $result = $stmt->execute();
        
        if ($result) {
            $editingAd = $result->fetchArray(SQLITE3_ASSOC);
        } else {
            $error = "Error retrieving ad information: " . $db->lastErrorMsg();
        }
    }

    // Handle the form for adding or editing ads
    if (isset($_POST['submit'])) {
        $title = sanitizeString($_POST['title']);
        $url = sanitizeAndValidateUrl($_POST['url']);
        $created_on = date('Y-m-d H:i:s');
        
        if ($url === false) {
            $error = "Invalid URL. Please enter a valid URL.";
        } else {
            if (isset($_POST['id'])) {
                // Update existing ad
                $id = filter_var($_POST['id'], FILTER_SANITIZE_NUMBER_INT);
                $stmt = $db->prepare('UPDATE ads SET title = :title, url = :url WHERE id = :id');
                $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
            } else {
                // Insert new ad
                $stmt = $db->prepare('INSERT INTO ads (title, url, created_on) VALUES (:title, :url, :created_on)');
                $stmt->bindValue(':created_on', $created_on, SQLITE3_TEXT);
            }
            
            $stmt->bindValue(':title', $title, SQLITE3_TEXT);
            $stmt->bindValue(':url', $url, SQLITE3_TEXT);
            
            if ($stmt->execute()) {
                $success = isset($_POST['id']) ? "Ad updated successfully." : "Ad saved successfully.";
                $editingAd = null;
            } else {
                $error = "Error saving the ad: " . $db->lastErrorMsg();
            }
        }
    }

    // Get existing ads
    $res = $db->query('SELECT * FROM ads ORDER BY created_on DESC');
    if ($res === false) {
        throw new Exception($db->lastErrorMsg());
    }
} catch (Exception $e) {
    $error = "Database error: " . $e->getMessage();
    $res = false;
}

?>

<!-- Custom styles for the control panel -->
<style>
    .adm_container {
        max-width: 1200px;
        margin: 20px auto;
        padding: 15px;
    }
    
    .adm_title {
        text-align: center;
        margin-bottom: 20px;
        color: #ffffff;
    }
    
    .adm_card {
        background-color: #2a2a2a;
        border-radius: 8px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
        overflow: hidden;
        transition: all 0.3s ease;
    }
    
    .adm_card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
    }
    
    .adm_card_header {
        background-color: var(--accent-tertiary);
        color: var(--light);
        padding: 15px 20px;
        border-radius: 5px 5px 0 0;
        display: flex;
        align-items: center;
    }
    
    [data-theme="light"] .adm_card_header {
        background-color: var(--accent-tertiary);
        color: var(--light);
    }
    
    .adm_card_body {
        padding: 20px;
        background-color: var(--dark);
        color: var(--light);
    }
    
    [data-theme="light"] .adm_card_body {
        background-color: var(--light);
        color: var(--dark);
    }
    
    .adm_form_control {
        background-color: var(--primary-dark);
        border: 1px solid var(--primary);
        color: var(--light);
        padding: 10px 15px;
        border-radius: 4px;
        width: 100%;
    }
    
    [data-theme="light"] .adm_form_control {
        background-color: var(--light);
        border: 2px solid var(--accent-tertiary);
        color: var(--dark);
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    
    .adm_form_control:focus {
        background-color: var(--primary-dark);
        color: var(--light);
        border-color: var(--accent-tertiary);
        outline: none;
    }
    
    [data-theme="light"] .adm_form_control:focus {
        background-color: var(--light);
        color: var(--dark);
        border-color: var(--accent-tertiary);
        border-width: 2px;
        box-shadow: 0 0 0 3px rgba(231, 111, 81, 0.3);
    }
    
    .adm_form_select {
        background-color: var(--primary-dark);
        border: 1px solid var(--primary);
        color: var(--light);
        padding: 10px 15px;
        border-radius: 4px;
        width: 100%;
        appearance: auto;
    }
    
    [data-theme="light"] .adm_form_select {
        background-color: var(--light);
        border: 2px solid var(--accent-tertiary);
        color: var(--dark);
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    
    .adm_form_select:focus {
        background-color: var(--primary-dark);
        color: var(--light);
        border-color: var(--accent-tertiary);
        outline: none;
    }
    
    [data-theme="light"] .adm_form_select:focus {
        background-color: var(--light);
        color: var(--dark);
        border-color: var(--accent-tertiary);
        border-width: 2px;
        box-shadow: 0 0 0 3px rgba(231, 111, 81, 0.3);
    }
    
    .adm_form_label {
        color: var(--light);
        margin-bottom: 8px;
    }
    
    [data-theme="light"] .adm_form_label {
        color: var(--dark);
        display: block;
    }
    
    .adm_btn {
        display: inline-block;
        font-weight: 400;
        text-align: center;
        white-space: nowrap;
        vertical-align: middle;
        user-select: none;
        border: 1px solid transparent;
        padding: 0.5rem 1rem;
        font-size: 1rem;
        line-height: 1.5;
        border-radius: 0.25rem;
        transition: all 0.15s ease-in-out;
        cursor: pointer;
    }
    
    .adm_btn_primary {
        background-color: var(--accent-secondary);
        border-color: var(--accent-tertiary);
        color: var(--light);
    }
    
    .adm_btn_primary:hover {
        background-color: var(--accent-tertiary);
        border-color: var(--accent-secondary);
    }
    
    .adm_alert {
        position: relative;
        padding: 12px 20px;
        margin-bottom: 16px;
        border: 1px solid transparent;
        border-radius: 4px;
    }
    
    .adm_alert_success {
        background-color: rgba(40, 167, 69, 0.2);
        color: #2ecc71;
        border-left: 4px solid #2ecc71;
    }
    
    .adm_alert_danger {
        background-color: rgba(229, 9, 20, 0.2);
        color: #e74c3c;
        border-left: 4px solid #e74c3c;
    }
    
    .adm_flex {
        display: flex;
    }
    
    .adm_items_center {
        align-items: center;
    }
    
    .adm_justify_end {
        justify-content: flex-end;
    }
    
    .adm_mb_0 {
        margin-bottom: 0;
    }
    
    .adm_me_2 {
        margin-right: 0.5rem;
    }
    
    .adm_ms_2 {
        margin-left: 0.5rem;
    }
    
    .adm_mt_2 {
        margin-top: 0.5rem;
    }
    
    .adm_mb_3 {
        margin-bottom: 1rem;
    }
    
    .adm_w_100 {
        width: 100%;
    }
    
    .adm_row {
        display: flex;
        flex-wrap: wrap;
        margin-right: -15px;
        margin-left: -15px;
    }
    
    .adm_col_6 {
        flex: 0 0 50%;
        max-width: 50%;
        padding-right: 15px;
        padding-left: 15px;
    }
    
    .adm_col_12 {
        flex: 0 0 100%;
        max-width: 100%;
        padding-right: 15px;
        padding-left: 15px;
    }
    
    /* Modern styling for ads display */
    .modern_header {
        background-color: var(--accent-tertiary);
    }
    
    .dark_bg {
        background-color: #212121;
    }
    
    /* Control bar */
    .ads_control_bar {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid #333;
    }
    
    .ads_counter {
        color: #ccc;
        font-size: 1rem;
        display: flex;
        align-items: center;
    }
    
    .ads_counter_badge {
        background-color: var(--accent-tertiary);
        color: var(--light);
        border-radius: 20px;
        padding: 2px 10px;
        margin-right: 8px;
        font-weight: 500;
    }
    
    .ads_view_controls {
        display: flex;
        align-items: center;
    }
    
    .view_mode_label {
        color: #ccc;
        margin-right: 10px;
    }
    
    .view_mode_switcher {
        display: flex;
        background-color: var(--primary-dark);
        border-radius: 8px;
        overflow: hidden;
    }
    
    .view_btn {
        border: none;
        background-color: transparent;
        color: var(--light);
        padding: 8px 15px;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    .view_btn:hover {
        background-color: var(--primary);
    }
    
    .view_btn_active {
        background-color: var(--accent-tertiary);
        color: var(--light);
    }
    
    [data-theme="light"] .view_btn_active {
        background-color: var(--accent-tertiary);
        color: var(--light);
    }
    
    /* Search and filter */
    .search_filter_bar {
        margin-bottom: 20px;
    }
    
    .search_container {
        position: relative;
    }
    
    .search_input {
        width: 100%;
        padding: 12px 20px 12px 45px;
        border: none;
        border-radius: 8px;
        background-color: #333;
        color: white;
        font-size: 1rem;
        transition: all 0.3s ease;
    }
    
    .search_input:focus {
        background-color: #444;
        outline: none;
        box-shadow: 0 0 0 2px rgba(229, 9, 20, 0.5);
    }
    
    .search_icon {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        color: #999;
    }
    
    /* Gallery View */
    .ads_masonry_grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
        gap: 20px;
        margin-top: 20px;
    }
    
    .ad_masonry_item {
        break-inside: avoid;
        margin-bottom: 20px;
    }
    
    .ad_card_modern {
        background-color: #2a2a2a;
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        transition: all 0.3s ease;
    }
    
    .ad_card_modern:hover {
        transform: translateY(-5px);
        box-shadow: 0 15px 35px rgba(0, 0, 0, 0.4);
    }
    
    .ad_image_wrapper {
        position: relative;
        overflow: hidden;
    }
    
    .ad_img {
        width: 100%;
        height: 200px;
        object-fit: cover;
        transition: all 0.5s ease;
    }
    
    .ad_card_modern:hover .ad_img {
        transform: scale(1.05);
    }
    
    .ad_overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(to top, rgba(0,0,0,0.8) 0%, transparent 100%);
        opacity: 0;
        display: flex;
        align-items: flex-end;
        justify-content: center;
        padding: 15px;
        transition: all 0.3s ease;
    }
    
    .ad_card_modern:hover .ad_overlay {
        opacity: 1;
    }
    
    .ad_actions {
        display: flex;
        gap: 10px;
    }
    
    .ad_btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: rgba(255, 255, 255, 0.2);
        backdrop-filter: blur(5px);
        color: white;
        border: none;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    .ad_btn:hover {
        transform: translateY(-3px);
    }
    
    .ad_btn_edit:hover {
        background-color: #3498db;
    }
    
    .ad_btn_delete:hover {
        background-color: #e74c3c;
    }
    
    .ad_info {
        padding: 15px;
    }
    
    .ad_title {
        font-size: 1.1rem;
        color: white;
        margin: 0 0 8px 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    
    .ad_meta {
        display: flex;
        justify-content: space-between;
        color: #999;
        font-size: 0.85rem;
    }
    
    /* List View */
    .ads_list {
        display: flex;
        flex-direction: column;
        gap: 15px;
    }
    
    .ad_list_item {
        display: flex;
        align-items: center;
        background-color: #2a2a2a;
        border-radius: 10px;
        overflow: hidden;
        padding: 10px;
        transition: all 0.3s ease;
    }
    
    .ad_list_item:hover {
        background-color: #333;
        transform: translateX(5px);
    }
    
    .ad_list_thumbnail {
        width: 80px;
        height: 80px;
        border-radius: 8px;
        overflow: hidden;
        flex-shrink: 0;
    }
    
    .ad_list_img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .ad_list_content {
        flex-grow: 1;
        padding: 0 15px;
    }
    
    .ad_list_title {
        font-size: 1.1rem;
        color: white;
        margin: 0 0 5px 0;
    }
    
    .ad_list_meta {
        color: #999;
        font-size: 0.85rem;
        display: flex;
        gap: 15px;
    }
    
    .ad_list_actions {
        display: flex;
        gap: 10px;
    }
    
    .ad_list_btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 36px;
        height: 36px;
        border-radius: 50%;
        color: white;
        border: none;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    .ad_btn_edit {
        background-color: rgba(52, 152, 219, 0.2);
        color: #3498db;
    }
    
    .ad_btn_delete {
        background-color: rgba(231, 76, 60, 0.2);
        color: #e74c3c;
    }
    
    /* Compact View */
    .ads_compact_grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 15px;
    }
    
    .ad_compact_card {
        background-color: #2a2a2a;
        border-radius: 8px;
        overflow: hidden;
        transition: all 0.3s ease;
        position: relative;
    }
    
    .ad_compact_card:hover {
        transform: scale(1.05);
        z-index: 1;
    }
    
    .ad_compact_img_container {
        height: 120px;
        overflow: hidden;
    }
    
    .ad_compact_img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }
    
    .ad_compact_title {
        padding: 10px;
        color: white;
        font-size: 0.9rem;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        text-align: center;
    }
    
    .ad_compact_actions {
        position: absolute;
        top: 5px;
        right: 5px;
        display: flex;
        flex-direction: column;
        gap: 5px;
        opacity: 0;
        transition: all 0.3s ease;
    }
    
    .ad_compact_card:hover .ad_compact_actions {
        opacity: 1;
    }
    
    .ad_compact_btn {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        color: white;
        font-size: 0.8rem;
        background-color: rgba(0, 0, 0, 0.6);
        backdrop-filter: blur(3px);
        border: none;
        cursor: pointer;
        transition: all 0.2s ease;
    }
    
    /* Empty state */
    .empty_state {
        text-align: center;
        padding: 60px 0;
        color: #777;
    }
    
    .empty_state_icon {
        font-size: 4rem;
        margin-bottom: 20px;
        color: #333;
    }
    
    .empty_state_title {
        font-size: 1.5rem;
        margin-bottom: 10px;
        color: #ccc;
    }
    
    .empty_state_message {
        margin-bottom: 25px;
    }
    
    .empty_state_btn {
        background-color: #e50914;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 30px;
        font-size: 1rem;
        cursor: pointer;
        transition: all 0.3s ease;
    }
    
    .empty_state_btn:hover {
        background-color: #c30710;
        transform: translateY(-2px);
    }
    
    /* Responsive adjustments */
    @media (max-width: 768px) {
        .adm_col_6 {
            flex: 0 0 100%;
            max-width: 100%;
        }
        
        .ads_control_bar {
            flex-direction: column;
            gap: 15px;
            align-items: flex-start;
        }
        
        .ads_masonry_grid {
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        }
        
        .ads_compact_grid {
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
        }
        
        .ad_list_item {
            flex-direction: column;
            align-items: flex-start;
        }
        
        .ad_list_thumbnail {
            width: 100%;
            height: 150px;
            margin-bottom: 10px;
        }
        
        .ad_list_actions {
            position: absolute;
            top: 10px;
            right: 10px;
        }
        
        .ad_list_content {
            padding: 0;
            width: 100%;
        }
    }
</style>

<div class="adm_container">
    <h1 class="adm_title">Control Panel</h1>
    
    <!-- Success message -->
    <?php if (!empty($success_message)): ?>
    <div class="adm_alert adm_alert_success">
        <i class="fas fa-check-circle adm_me_2"></i>
        <?php echo $success_message; ?>
    </div>
    <?php endif; ?>

    <!-- Mode selector -->
    <div class="adm_card">
        <div class="adm_card_header">
            <i class="fas fa-sliders-h adm_me_2"></i>
            <h5 class="adm_mb_0">Mode Configuration</h5>
        </div>
        <div class="adm_card_body">
            <form method="post" action="" class="adm_row">
                <div class="adm_col_6">
                    <div class="adm_mb_3">
                        <label for="modeSelect" class="adm_form_label">Select Mode:</label>
                        <select name="mode" id="modeSelect" class="adm_form_select">
                            <option value="manual" <?php echo ($selector['mode'] == 'manualads.php') ? 'selected' : ''; ?>>Manual</option>
                            <option value="tmdb" <?php echo ($selector['mode'] == 'posters.php') ? 'selected' : ''; ?>>Posters</option>
                            <option value="posters1" <?php echo ($selector['mode'] == 'posters1.php') ? 'selected' : ''; ?>>Posters 1</option>
                            <option value="posters2" <?php echo ($selector['mode'] == 'posters2.php') ? 'selected' : ''; ?>>Posters 2</option>
                            <option value="posters3" <?php echo ($selector['mode'] == 'posters3.php') ? 'selected' : ''; ?>>Posters 3</option>
                        </select>
                    </div>
                </div>
                <div class="adm_col_6 adm_flex adm_items_center">
                    <button type="submit" name="save_mode" class="adm_btn adm_btn_primary adm_w_100">
                        <i class="fas fa-save adm_me_2"></i>Save Mode
                    </button>
                </div>
                <div class="adm_col_12 adm_mt_2">
                    <div class="adm_flex adm_items_center">
                        <span>Current mode:</span>
                        <span class="adm_mode_indicator adm_ms_2">
                            <?php 
                            if ($selector['mode'] == 'manualads.php') echo 'Manual';
                            elseif ($selector['mode'] == 'posters.php') echo 'TMDB';
                            elseif ($selector['mode'] == 'posters1.php') echo 'Posters 1';
                            elseif ($selector['mode'] == 'posters2.php') echo 'Posters 2';
                            elseif ($selector['mode'] == 'posters3.php') echo 'Posters 3';
                            ?>
                        </span>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Form to add or edit ads -->
    <div class="adm_card">
        <div class="adm_card_header">
            <i class="fas fa-ad adm_me_2"></i>
            <h5 class="adm_mb_0"><?php echo $editingAd ? 'Edit Ad' : 'Add New Ad'; ?></h5>
        </div>
        <div class="adm_card_body">
            <?php if ($error): ?>
                <div class="adm_alert adm_alert_danger">
                    <i class="fas fa-exclamation-triangle adm_me_2"></i>
                    <?php echo $error; ?>
                </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="adm_alert adm_alert_success">
                    <i class="fas fa-check-circle adm_me_2"></i>
                    <?php echo $success; ?>
                </div>
            <?php endif; ?>

            <form method="post" class="adm_row">
                <?php if ($editingAd): ?>
                    <input type="hidden" name="id" value="<?php echo $editingAd['id']; ?>">
                <?php endif; ?>
                
                <div class="adm_col_6">
                    <div class="adm_mb_3">
                        <label for="title" class="adm_form_label">Ad Title</label>
                        <input class="adm_form_control" id="title" name="title" type="text" required value="<?php echo $editingAd ? htmlspecialchars($editingAd['title']) : ''; ?>"/>
                    </div>
                </div>
                
                <div class="adm_col_6">
                    <div class="adm_mb_3">
                        <label for="url" class="adm_form_label">Image URL</label>
                        <input class="adm_form_control" id="url" name="url" type="url" required value="<?php echo $editingAd ? htmlspecialchars($editingAd['url']) : ''; ?>"/>
                    </div>
                </div>
                
                <div class="adm_col_12 adm_flex adm_justify_end">
                    <button class="adm_btn adm_btn_primary" name="submit" type="submit">
                        <i class="fas <?php echo $editingAd ? 'fa-edit' : 'fa-plus'; ?> adm_me_2"></i>
                        <?php echo $editingAd ? 'Update Ad' : 'Add Ad'; ?>
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Display ads with enhanced UI -->
    <div class="adm_card">
        <div class="adm_card_header modern_header">
            <i class="fas fa-photo-video adm_me_2"></i>
            <h5 class="adm_mb_0">Gallery of Advertisements</h5>
        </div>
        <div class="adm_card_body dark_bg">
         <?php if ($res && $res->fetchArray(SQLITE3_ASSOC)): ?>
                <!-- Controls bar -->
                <div class="ads_control_bar">
                    <div class="ads_counter">
                        <?php 
                        $res->reset();
                        $count = 0;
                        while ($res->fetchArray(SQLITE3_ASSOC)) {
                            $count++;
                        }
                        ?>
                        <span class="ads_counter_badge"><?php echo $count; ?></span> Advertisements Available
                    </div>
                    
                    <div class="ads_view_controls">
                        <span class="view_mode_label">Display:</span>
                        <div class="view_mode_switcher">
                            <button class="view_btn view_btn_active" id="galleryBtn" data-view="gallery">
                                <i class="fas fa-th"></i>
                            </button>
                            <button class="view_btn" id="listBtn" data-view="list">
                                <i class="fas fa-list"></i>
                            </button>
                            <button class="view_btn" id="compactBtn" data-view="compact">
                                <i class="fas fa-grip-horizontal"></i>
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Search and filter bar -->
                <div class="search_filter_bar">
                    <div class="search_container">
                        <input type="text" id="adSearch" class="search_input" placeholder="Search ads...">
                        <i class="fas fa-search search_icon"></i>
                    </div>
                </div>

                <!-- Gallery View (default) -->
                <div class="ads_container" id="galleryView">
                    <div class="ads_masonry_grid">
                        <?php $res->reset(); ?>
                        <?php while ($ad = $res->fetchArray(SQLITE3_ASSOC)): ?>
                            <div class="ad_masonry_item" data-title="<?php echo strtolower(htmlspecialchars($ad['title'])); ?>">
                                <div class="ad_card_modern">
                                    <div class="ad_image_wrapper">
                                        <img src="<?php echo htmlspecialchars($ad['url']); ?>" alt="<?php echo htmlspecialchars($ad['title']); ?>" class="ad_img">
                                        <div class="ad_overlay">
                                            <div class="ad_actions">
                                                <a href="?edit=<?php echo $ad['id']; ?>" class="ad_btn ad_btn_edit" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="?delete=<?php echo $ad['id']; ?>" class="ad_btn ad_btn_delete" title="Delete" onclick="return confirm('Are you sure you want to delete this ad?');">
                                                    <i class="fas fa-trash-alt"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="ad_info">
                                        <h3 class="ad_title"><?php echo htmlspecialchars($ad['title']); ?></h3>
                                        <div class="ad_meta">
                                            <span class="ad_id">#<?php echo $ad['id']; ?></span>
                                            <span class="ad_date">
                                                <i class="far fa-clock"></i> 
                                                <?php echo isset($ad['created_on']) ? date('m/d/Y', strtotime($ad['created_on'])) : 'N/A'; ?>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>
                
                <!-- List View (hidden initially) -->
                <div class="ads_container" id="listView" style="display: none;">
                    <div class="ads_list">
                        <?php $res->reset(); ?>
                        <?php while ($ad = $res->fetchArray(SQLITE3_ASSOC)): ?>
                            <div class="ad_list_item" data-title="<?php echo strtolower(htmlspecialchars($ad['title'])); ?>">
                                <div class="ad_list_thumbnail">
                                    <img src="<?php echo htmlspecialchars($ad['url']); ?>" alt="<?php echo htmlspecialchars($ad['title']); ?>" class="ad_list_img">
                                </div>
                                <div class="ad_list_content">
                                    <h3 class="ad_list_title"><?php echo htmlspecialchars($ad['title']); ?></h3>
                                    <div class="ad_list_meta">
                                        <span class="ad_meta_id">#<?php echo $ad['id']; ?></span>
                                        <span class="ad_meta_date">
                                            <i class="far fa-calendar-alt"></i> 
                                            <?php echo isset($ad['created_on']) ? date('m/d/Y H:i', strtotime($ad['created_on'])) : 'N/A'; ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="ad_list_actions">
                                    <a href="?edit=<?php echo $ad['id']; ?>" class="ad_list_btn ad_btn_edit" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="?delete=<?php echo $ad['id']; ?>" class="ad_list_btn ad_btn_delete" title="Delete" onclick="return confirm('Are you sure you want to delete this ad?');">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>
                
                <!-- Compact View (hidden initially) -->
                <div class="ads_container" id="compactView" style="display: none;">
                    <div class="ads_compact_grid">
                        <?php $res->reset(); ?>
                        <?php while ($ad = $res->fetchArray(SQLITE3_ASSOC)): ?>
                            <div class="ad_compact_item" data-title="<?php echo strtolower(htmlspecialchars($ad['title'])); ?>">
                                <div class="ad_compact_card">
                                    <div class="ad_compact_img_container">
                                        <img src="<?php echo htmlspecialchars($ad['url']); ?>" alt="<?php echo htmlspecialchars($ad['title']); ?>" class="ad_compact_img">
                                    </div>
                                    <div class="ad_compact_title" title="<?php echo htmlspecialchars($ad['title']); ?>"><?php echo htmlspecialchars($ad['title']); ?></div>
                                    <div class="ad_compact_actions">
                                        <a href="?edit=<?php echo $ad['id']; ?>" class="ad_compact_btn ad_btn_edit" title="Edit">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                        <a href="?delete=<?php echo $ad['id']; ?>" class="ad_compact_btn ad_btn_delete" title="Delete" onclick="return confirm('Are you sure you want to delete this ad?');">
                                            <i class="fas fa-trash-alt"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    </div>
                </div>
                
            <?php else: ?>
                <div class="empty_state">
                    <div class="empty_state_icon">
                        <i class="fas fa-photo-video"></i>
                    </div>
                    <h3 class="empty_state_title">No Advertisements Yet</h3>
                    <p class="empty_state_message">Add your first advertisement to see it here.</p>
                    <button class="empty_state_btn" onclick="document.getElementById('title').focus();">
                        <i class="fas fa-plus adm_me_2"></i> Add New Advertisement
                    </button>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- JavaScript for view switching and search functionality -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Auto-dismiss alerts after 5 seconds
    setTimeout(function() {
        const alerts = document.querySelectorAll('.adm_alert');
        alerts.forEach(function(alert) {
            if (alert) {
                alert.style.display = 'none';
            }
        });
    }, 5000);
    
    // View switching functionality
    const galleryBtn = document.getElementById('galleryBtn');
    const listBtn = document.getElementById('listBtn');
    const compactBtn = document.getElementById('compactBtn');
    
    const galleryView = document.getElementById('galleryView');
    const listView = document.getElementById('listView');
    const compactView = document.getElementById('compactView');
    
    // Load saved view preference
    const savedView = localStorage.getItem('adsViewMode') || 'gallery';
    setActiveView(savedView);
    
    function setActiveView(viewMode) {
        // Hide all views
        galleryView.style.display = 'none';
        listView.style.display = 'none';
        compactView.style.display = 'none';
        
        // Remove active class from all buttons
        galleryBtn.classList.remove('view_btn_active');
        listBtn.classList.remove('view_btn_active');
        compactBtn.classList.remove('view_btn_active');
        
        // Show selected view and activate button
        if (viewMode === 'gallery') {
            galleryView.style.display = 'block';
            galleryBtn.classList.add('view_btn_active');
        } else if (viewMode === 'list') {
            listView.style.display = 'block';
            listBtn.classList.add('view_btn_active');
        } else if (viewMode === 'compact') {
            compactView.style.display = 'block';
            compactBtn.classList.add('view_btn_active');
        }
        
        // Save preference
        localStorage.setItem('adsViewMode', viewMode);
    }
    
    // Button click events
    galleryBtn.addEventListener('click', function() {
        setActiveView('gallery');
    });
    
    listBtn.addEventListener('click', function() {
        setActiveView('list');
    });
    
    compactBtn.addEventListener('click', function() {
        setActiveView('compact');
    });
    
    // Search functionality
    const searchInput = document.getElementById('adSearch');
    const galleryItems = document.querySelectorAll('.ad_masonry_item');
    const listItems = document.querySelectorAll('.ad_list_item');
    const compactItems = document.querySelectorAll('.ad_compact_item');
    
    searchInput.addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase().trim();
        
        // Filter gallery items
        galleryItems.forEach(item => {
            const title = item.dataset.title;
            if (title.includes(searchTerm)) {
                item.style.display = '';
            } else {
                item.style.display = 'none';
            }
        });
        
        // Filter list items
        listItems.forEach(item => {
            const title = item.dataset.title;
            if (title.includes(searchTerm)) {
                item.style.display = '';
            } else {
                item.style.display = 'none';
            }
        });
        
        // Filter compact items
        compactItems.forEach(item => {
            const title = item.dataset.title;
            if (title.includes(searchTerm)) {
                item.style.display = '';
            } else {
                item.style.display = 'none';
            }
        });
    });
});
</script>
</body>
</html>