<?php
session_start();
require_once '../config.php';
require_once 'blog-functions.php';

// Function to check and reconnect MySQL connection if needed
function checkDatabaseConnection($connection) {
    if (!$connection || !mysqli_ping($connection)) {
        // Reconnect to database
        require_once '../config.php';
        return $link ?? $connection;
    }
    return $connection;
}

// Clean initialization - no debugging alerts

// Check if admin is logged in
if (!isset($_SESSION['admin_id']) || !isset($_SESSION['admin_name'])) {
    header("Location: admin-login.php");
    exit;
}

// Create necessary tables if they don't exist
$create_blogs_table = "CREATE TABLE IF NOT EXISTS `blogs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `slug` varchar(255) NOT NULL,
  `content` longtext NOT NULL,
  `excerpt` text DEFAULT NULL,
  `featured_image` varchar(255) DEFAULT NULL,
  `category` varchar(100) DEFAULT 'general',
  `tags` text DEFAULT NULL,
  `status` enum('draft','published','archived') DEFAULT 'draft',
  `views` int(11) DEFAULT 0,
  `likes` int(11) DEFAULT 0,
  `author_id` int(11) DEFAULT 1,
  `meta_title` varchar(255) DEFAULT NULL,
  `meta_description` text DEFAULT NULL,
  `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
  `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `slug` (`slug`),
  KEY `status` (`status`),
  KEY `category` (`category`),
  KEY `created_at` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

mysqli_query($link, $create_blogs_table);

// Create contacts table if it doesn't exist
$create_contacts_table = "CREATE TABLE IF NOT EXISTS `contacts` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `name` varchar(100) NOT NULL,
    `phone` varchar(20) NOT NULL,
    `subject` varchar(200) NOT NULL,
    `message` text NOT NULL,
    `preferred_contact` varchar(20) NOT NULL,
    `ip_address` varchar(45) DEFAULT NULL,
    `status` enum('new','replied','resolved') DEFAULT 'new',
    `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

mysqli_query($link, $create_contacts_table);

// Get today's date
date_default_timezone_set('Asia/Kolkata');
$today = date('Y-m-d');

// Get admin name
$admin_name = $_SESSION['admin_name'] ?? 'Admin';

// Handle AJAX requests for blog data
if (isset($_GET['action']) && $_GET['action'] === 'get_blog' && isset($_GET['id'])) {
    header('Content-Type: application/json');
    $blog_id = intval($_GET['id']);
    
    $blog = getBlogByIdAdmin($link, $blog_id);
    
    if ($blog) {
        echo json_encode([
            'success' => true,
            'blog' => $blog
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Blog not found'
        ]);
    }
    exit;
}

// Initialize variables with default values
$today_amount = 0;
$today_entries = [];
$all_entries = [];
$today_users = [];
$total_users = 0;

// Get today's total amount
$today_amount = 0;
$res = mysqli_query($link, "SELECT SUM(amount) as total FROM entries WHERE DATE(entry_time) = '$today'");
if ($res && $row = mysqli_fetch_assoc($res)) {
    $today_amount = $row['total'] ?? 0;
} else {
    error_log("Failed to get today's amount: " . mysqli_error($link));
}

// Get today's entries
$today_entries = [];
$res = mysqli_query($link, "SELECT * FROM entries WHERE DATE(entry_time) = '$today'");
if ($res) {
    while ($row = mysqli_fetch_assoc($res)) {
        $today_entries[] = $row;
    }
} else {
    error_log("Failed to get today's entries: " . mysqli_error($link));
}

// Get all entries
$all_entries = [];
$res = mysqli_query($link, "SELECT * FROM entries ORDER BY entry_time DESC LIMIT 100");
if ($res) {
    while ($row = mysqli_fetch_assoc($res)) {
        $all_entries[] = $row;
    }
} else {
    error_log("Failed to get all entries: " . mysqli_error($link));
}

// Create sessions table for tracking active users
$create_sessions_table = "CREATE TABLE IF NOT EXISTS `active_sessions` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `username` varchar(50) NOT NULL,
  `session_id` varchar(255) NOT NULL,
  `login_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `last_activity` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `ip_address` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `session_id` (`session_id`),
  KEY `user_id` (`user_id`),
  KEY `last_activity` (`last_activity`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

if (!mysqli_query($link, $create_sessions_table)) {
    error_log("Failed to create active_sessions table: " . mysqli_error($link));
}

// Clean up old sessions (older than 30 minutes of inactivity)
$cleanup_sessions = "DELETE FROM active_sessions WHERE last_activity < DATE_SUB(NOW(), INTERVAL 30 MINUTE)";
mysqli_query($link, $cleanup_sessions);

// Get today's users (only count users that exist in both entries and users tables)
// Get currently active users (from active sessions)
$today_users = [];
$res = mysqli_query($link, "
    SELECT DISTINCT s.username, s.login_time, s.last_activity
    FROM active_sessions s 
    INNER JOIN users u ON s.username = u.username 
    WHERE s.last_activity > DATE_SUB(NOW(), INTERVAL 30 MINUTE)
    ORDER BY s.last_activity DESC
");
if ($res) {
    while ($row = mysqli_fetch_assoc($res)) {
        $today_users[] = $row['username'];
    }
} else {
    error_log("Failed to get active users: " . mysqli_error($link));
}

// Get total users
$total_users = 0;
$res = mysqli_query($link, "SELECT COUNT(DISTINCT username) as total FROM users");
if ($res && $row = mysqli_fetch_assoc($res)) {
    $total_users = $row['total'];
} else {
    error_log("Failed to get total users: " . mysqli_error($link));
}
// SIMPLE TEST HANDLER - REMOVED (no longer needed)

// Handle add result
$msg = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check specifically for add_result_submit
    if (isset($_POST['add_result_submit'])) {
        // Log for debugging
        error_log("ADD RESULT: Form submitted");
        
        // Check database connection first
        if (!isset($link) || !$link) {
            error_log("Database connection error");
            $msg = "Database connection error";
        } else {
            $result_date = $_POST['result_date'] ?? '';
            $game = $_POST['game'] ?? '';
            $result_number = $_POST['result_number'] ?? '';
            
            // Validate inputs
            if (empty($result_date) || empty($game) || empty($result_number)) {
                error_log("Missing required fields - Date: '$result_date', Game: '$game', Number: '$result_number'");
                $msg = "missing";
            } else {
                // Check if results table exists, create if not
                $check_table = mysqli_query($link, "SHOW TABLES LIKE 'results'");
                if (!$check_table) {
                    error_log("Error checking for results table: " . mysqli_error($link));
                    $msg = "dberror";
                } else if (mysqli_num_rows($check_table) == 0) {
                    error_log("Creating results table");
                    $create_table = "CREATE TABLE results (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        result_date DATE NOT NULL,
                        game VARCHAR(50) NOT NULL,
                        result_number VARCHAR(10) NOT NULL,
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                    )";
                    if (!mysqli_query($link, $create_table)) {
                        error_log("Failed to create results table: " . mysqli_error($link));
                        $msg = "dberror";
                    }
                }
                
                // Insert the data
                if (empty($msg)) {
                    $sql = "INSERT INTO results (result_date, game, result_number) VALUES (?, ?, ?)";
                    if ($stmt = mysqli_prepare($link, $sql)) {
                        mysqli_stmt_bind_param($stmt, 'sss', $result_date, $game, $result_number);
                        if (mysqli_stmt_execute($stmt)) {
                            error_log("Result added successfully: Date=$result_date, Game=$game, Number=$result_number");
                            mysqli_stmt_close($stmt);
                            $msg = "success";
                        } else {
                            error_log("Execute error: " . mysqli_stmt_error($stmt));
                            mysqli_stmt_close($stmt);
                            $msg = "error";
                        }
                    } else {
                        error_log("Prepare error: " . mysqli_error($link));
                        $msg = "dberror";
                    }
                }
            }
        }
        
        // Set a session variable for the message and redirect to prevent resubmission
        if (!empty($msg)) {
            $_SESSION['result_msg'] = $msg;
            // Redirect back to the add_result section to stay on the same form
            header("Location: admin-dashboard.php?show_section=add_result&msg=" . urlencode($msg));
            exit;
        }
    } else {
        // Not an add_result_submit - could be other form submissions
        // Log if needed for debugging other forms
    }
}

// Handle edit/update/delete for copy report
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Edit/update/delete logic for copy report
    if (isset($_POST['delete_copy_entry'])) {
        $id = intval($_POST['copy_id']);
        mysqli_query($link, "DELETE FROM entries_copy WHERE id = $id");
    }
    if (isset($_POST['update_copy_entry'])) {
        $id = intval($_POST['copy_id']);
        $amount = intval($_POST['amount']);
        $number = $_POST['number'];
        mysqli_query($link, "UPDATE entries_copy SET amount = $amount, number = '$number' WHERE id = $id");
    }
    // Generate copy report
    if (isset($_POST['generate_copy_report'])) {
        // Copy today's entries to entries_copy table
        mysqli_query($link, "DELETE FROM entries_copy WHERE DATE(entry_time) = '$today'");
        foreach ($today_entries as $entry) {
            $sql = "INSERT INTO entries_copy (userid, username, game, type, subtype, number, amount, entry_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            if ($stmt = mysqli_prepare($link, $sql)) {
                mysqli_stmt_bind_param($stmt, 'isssssis',
                    $entry['userid'],
                    $entry['username'],
                    $entry['game'],
                    $entry['type'],
                    $entry['subtype'],
                    $entry['number'],
                    $entry['amount'],
                    $entry['entry_time']
                );
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);
            }
        }
    }
    // Share on WhatsApp
    if (isset($_POST['share_whatsapp'])) {
        // Insert updated entries_copy into another table (entries_shared)
        $shared_entries = [];
        $res = mysqli_query($link, "SELECT * FROM entries_copy WHERE DATE(entry_time) = '$today'");
        while ($row = mysqli_fetch_assoc($res)) {
            $shared_entries[] = $row;
        }
        foreach ($shared_entries as $entry) {
            $sql = "INSERT INTO entries_shared (userid, username, game, type, subtype, number, amount, entry_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            if ($stmt = mysqli_prepare($link, $sql)) {
                mysqli_stmt_bind_param($stmt, 'isssssis',
                    $entry['userid'],
                    $entry['username'],
                    $entry['game'],
                    $entry['type'],
                    $entry['subtype'],
                    $entry['number'],
                    $entry['amount'],
                    $entry['entry_time']
                );
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);
            }
        }
        // Prepare WhatsApp message
        $wa_message = "Today's Entries:\n";
        foreach ($shared_entries as $entry) {
            $wa_message .= "{$entry['username']} | {$entry['game']} | {$entry['type']} | {$entry['subtype']} | {$entry['number']} | {$entry['amount']}\n";
        }
        $wa_message .= "Total Amount: $today_amount";
        $wa_message = urlencode($wa_message);
        $wa_number = "919759907027";
        $wa_url = "https://wa.me/$wa_number?text=$wa_message";
        header("Location: $wa_url");
        exit;
    }
}

// Handle Blog Operations
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Save new blog post
    if (isset($_POST['save_blog'])) {
        $featured_image = '';
        
        // Handle image upload
        if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
            $upload_result = handleImageUpload($_FILES['featured_image']);
            if ($upload_result['success']) {
                $featured_image = $upload_result['filename'];
            }
        }
        
        $blog_data = [
            'title' => $_POST['blog_title'] ?? '',
            'meta_title' => $_POST['blog_meta_title'] ?? '',
            'meta_description' => $_POST['blog_meta_description'] ?? '',
            'excerpt' => $_POST['blog_excerpt'] ?? '',
            'content' => $_POST['blog_content'] ?? '',
            'featured_image' => $featured_image,
            'category' => $_POST['blog_category'] ?? '',
            'tags' => $_POST['blog_tags'] ?? '',
            'author' => $admin_name,
            'status' => $_POST['blog_status'] ?? 'draft'
        ];
        
        // Validate required fields
        if (empty($blog_data['title']) || empty($blog_data['excerpt']) || empty($blog_data['content']) || empty($blog_data['category'])) {
            header("Location: admin-dashboard.php?show_section=create_blog&msg=blog_error");
            exit;
        }
        
        if (saveBlogPost($link, $blog_data)) {
            header("Location: admin-dashboard.php?show_section=blog_management&msg=blog_saved");
        } else {
            header("Location: admin-dashboard.php?show_section=create_blog&msg=blog_error");
        }
        exit;
    }
    
    // Update existing blog
    if (isset($_POST['update_blog'])) {
        $blog_id = intval($_POST['blog_id']);
        $featured_image = $_POST['existing_image'] ?? '';
        
        // Handle new image upload
        if (isset($_FILES['featured_image']) && $_FILES['featured_image']['error'] === UPLOAD_ERR_OK) {
            $upload_result = handleImageUpload($_FILES['featured_image']);
            if ($upload_result['success']) {
                $featured_image = $upload_result['filename'];
            }
        }
        
        $blog_data = [
            'title' => $_POST['blog_title'],
            'meta_title' => $_POST['blog_meta_title'],
            'meta_description' => $_POST['blog_meta_description'],
            'excerpt' => $_POST['blog_excerpt'],
            'content' => $_POST['blog_content'],
            'featured_image' => $featured_image,
            'category' => $_POST['blog_category'],
            'tags' => $_POST['blog_tags'],
            'status' => $_POST['blog_status']
        ];
        
        if (updateBlog($link, $blog_id, $blog_data)) {
            header("Location: admin-dashboard.php?show_section=blog_management&msg=blog_updated");
        } else {
            header("Location: admin-dashboard.php?show_section=edit_blog&id=$blog_id&msg=blog_error");
        }
        exit;
    }
    
    // Delete blog
    if (isset($_POST['delete_blog'])) {
        $blog_id = intval($_POST['blog_id']);
        if (deleteBlog($link, $blog_id)) {
            header("Location: admin-dashboard.php?show_section=blog_management&msg=blog_deleted");
        } else {
            header("Location: admin-dashboard.php?show_section=blog_management&msg=blog_error");
        }
        exit;
    }
}

// Get all blogs for management
$all_blogs = [];
try {
    $all_blogs = getAllBlogsAdmin($link, 50, 0); // Get first 50 blogs for admin
    if (!is_array($all_blogs)) {
        $all_blogs = [];
    }
} catch (Exception $e) {
    error_log("Error getting blogs for admin: " . $e->getMessage());
    $all_blogs = [];
}

// Get blog statistics for dashboard
$blog_stats = [];
try {
    $blog_stats = getBlogStats($link);
    
    // Ensure all required keys exist with default values
    $blog_stats = array_merge([
        'total_blogs' => 0,
        'total_published' => 0,
        'total_drafts' => 0,
        'total_views' => 0,
        'total_likes' => 0,
        'most_popular' => ['title' => 'No blogs yet', 'views' => 0]
    ], $blog_stats);
    
} catch (Exception $e) {
    error_log("Error getting blog stats: " . $e->getMessage());
    // Provide safe default values
    $blog_stats = [
        'total_blogs' => 0,
        'total_published' => 0,
        'total_drafts' => 0,
        'total_views' => 0,
        'total_likes' => 0,
        'most_popular' => ['title' => 'No blogs yet', 'views' => 0]
    ];
}

// Get contact form statistics
$contact_stats = [
    'total_contacts' => 0,
    'new_contacts' => 0,
    'replied_contacts' => 0,
    'today_contacts' => 0
];

// Get total contacts
try {
    $result = mysqli_query($link, "SELECT COUNT(*) as total FROM contacts");
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $contact_stats['total_contacts'] = (int)$row['total'];
    }
} catch (Exception $e) {
    error_log("Error getting total contacts: " . $e->getMessage());
}

// Get new contacts (status = 'new')
try {
    $result = mysqli_query($link, "SELECT COUNT(*) as total FROM contacts WHERE status = 'new'");
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $contact_stats['new_contacts'] = (int)$row['total'];
    }
} catch (Exception $e) {
    error_log("Error getting new contacts: " . $e->getMessage());
}

// Get replied contacts
try {
    $result = mysqli_query($link, "SELECT COUNT(*) as total FROM contacts WHERE status IN ('replied', 'resolved')");
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $contact_stats['replied_contacts'] = (int)$row['total'];
    }
} catch (Exception $e) {
    error_log("Error getting replied contacts: " . $e->getMessage());
}

// Get today's contacts
try {
    $result = mysqli_query($link, "SELECT COUNT(*) as total FROM contacts WHERE DATE(created_at) = CURDATE()");
    if ($result && $row = mysqli_fetch_assoc($result)) {
        $contact_stats['today_contacts'] = (int)$row['total'];
    }
} catch (Exception $e) {
    error_log("Error getting today's contacts: " . $e->getMessage());
}

// Handle contact status updates
if (isset($_POST['update_contact_status']) && isset($_POST['contact_id']) && isset($_POST['new_status'])) {
    $contact_id = intval($_POST['contact_id']);
    $new_status = $_POST['new_status'];
    
    $stmt = mysqli_prepare($link, "UPDATE contacts SET status = ? WHERE id = ?");
    mysqli_stmt_bind_param($stmt, 'si', $new_status, $contact_id);
    
    if (mysqli_stmt_execute($stmt)) {
        header("Location: admin-dashboard.php?show_section=contact_management&msg=status_updated");
    } else {
        header("Location: admin-dashboard.php?show_section=contact_management&msg=status_error");
    }
    exit;
}

$show_section = $_POST['show_section'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- CRITICAL: Define functions IMMEDIATELY to prevent "not defined" errors -->
    <script>
        // Define functions in global scope IMMEDIATELY - BEFORE any HTML loads
        window.showSection = function(sectionId) {
            console.log('showSection called with:', sectionId);
            
            // Hide all sections
            const sections = document.querySelectorAll('.content-section');
            sections.forEach(section => {
                section.classList.remove('active');
            });
            
            // Show target section
            const targetSection = document.getElementById(sectionId);
            if (targetSection) {
                targetSection.classList.add('active');
                console.log('Section switched to:', sectionId);
            } else {
                console.error('Section not found:', sectionId);
            }
            
            // Reset blog form when switching to create_blog section
            if (sectionId === 'create_blog') {
                resetBlogForm();
            }
        };

        // Also define without window prefix for backward compatibility
        function showSection(sectionId) {
            return window.showSection(sectionId);
        }

        // Reset blog form to create mode
        window.resetBlogForm = function() {
            console.log('Resetting blog form...');
            
            // Reset form title
            const formTitle = document.getElementById('form-title');
            if (formTitle) {
                formTitle.innerHTML = '<i class="fas fa-pen"></i> Create New Blog Post';
            }
            
            // Clear all form fields
            const fields = ['blog_id', 'blog_title', 'blog_excerpt'];
            fields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) field.value = '';
            });
            
            // Reset CKEditor if it exists
            if (typeof CKEDITOR !== 'undefined' && CKEDITOR.instances.blog_content) {
                CKEDITOR.instances.blog_content.setData('');
            }
        };

        function resetBlogForm() {
            return window.resetBlogForm();
        }

        // Blog management functions - CRITICAL: Define early to prevent "not defined" errors
        window.editBlog = function(blogId) {
            console.log('Edit blog called with ID:', blogId);
            
            // Check if required elements exist
            const createBlogSection = document.getElementById('create_blog');
            const formTitle = document.getElementById('form-title');
            const blogIdField = document.getElementById('blog_id');
            
            console.log('Elements check:', {
                createBlogSection: !!createBlogSection,
                formTitle: !!formTitle,
                blogIdField: !!blogIdField
            });
            
            if (!createBlogSection || !formTitle || !blogIdField) {
                console.error('Required elements missing for edit blog');
                alert('Error: Blog edit form elements are missing');
                return;
            }
            
            // Use the global showSection function
            if (typeof showSection === 'function') {
                showSection('create_blog');
            } else {
                console.error('showSection function not available');
                alert('Error: Navigation function not available');
                return;
            }
            
            // Change form title to Edit mode
            formTitle.innerHTML = '<i class="fas fa-edit"></i> Edit Blog Post';
            
            // Set form ID for editing
            blogIdField.value = blogId;
            
            // Change submit button for edit mode
            const submitBtn = document.querySelector('.blog-form button[type="submit"]');
            if (submitBtn) {
                submitBtn.name = 'update_blog';
                submitBtn.value = '1';
                submitBtn.innerHTML = '<i class="fas fa-save"></i> Update Blog Post';
                console.log('Submit button changed to update mode');
            } else {
                console.error('Submit button not found!');
                alert('Error: Submit button not found');
                return;
            }
            
            // Load blog data via AJAX
            console.log('Fetching blog data...');
            fetch('admin-dashboard.php?action=get_blog&id=' + blogId)
                .then(response => {
                    console.log('Response status:', response.status);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log('Received data:', data);
                    if (data.success) {
                        // Fill form with blog data
                        const fields = {
                            'blog_title': data.blog.title || '',
                            'blog_excerpt': data.blog.excerpt || '',
                            'blog_category': data.blog.category || '',
                            'blog_status': data.blog.status || 'draft',
                            'blog_tags': data.blog.tags || '',
                            'blog_meta_title': data.blog.meta_title || '',
                            'blog_meta_description': data.blog.meta_description || ''
                        };
                        
                        // Fill each field
                        Object.keys(fields).forEach(fieldId => {
                            const field = document.getElementById(fieldId);
                            if (field) {
                                field.value = fields[fieldId];
                                console.log(`Set ${fieldId} to:`, fields[fieldId]);
                            } else {
                                console.warn(`Field ${fieldId} not found`);
                            }
                        });
                        
                        // Set CKEditor content
                        if (window.blogEditor) {
                            window.blogEditor.setData(data.blog.content || '');
                            console.log('CKEditor content set');
                        } else {
                            // Fallback for regular textarea
                            const contentField = document.getElementById('blog_content');
                            if (contentField) {
                                contentField.value = data.blog.content || '';
                                console.log('Textarea content set');
                            }
                        }
                        
                        // Set existing image for edit mode
                        const existingImageField = document.getElementById('existing_image');
                        if (existingImageField) {
                            existingImageField.value = data.blog.featured_image || '';
                        }
                        
                        console.log('Blog data loaded successfully');
                    } else {
                        console.error('Failed to load blog data:', data.message);
                        alert('❌ Failed to load blog data: ' + (data.message || 'Unknown error'));
                    }
                })
                .catch(error => {
                    console.error('Error loading blog data:', error);
                    alert('❌ Error loading blog data: ' + error.message);
                });
            
            console.log('Switching to edit mode for blog ID:', blogId);
        };

        window.deleteBlogPost = function(blogId) {
            console.log('Delete blog called with ID:', blogId);
            if (confirm('Are you sure you want to delete this blog post? This action cannot be undone.')) {
                console.log('User confirmed deletion');
                
                try {
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.action = 'admin-dashboard.php';
                    form.style.display = 'none';
                    
                    const actionInput = document.createElement('input');
                    actionInput.name = 'delete_blog';
                    actionInput.value = '1';
                    form.appendChild(actionInput);
                    
                    const idInput = document.createElement('input');
                    idInput.name = 'blog_id';
                    idInput.value = blogId;
                    form.appendChild(idInput);
                    
                    console.log('Form created with:', {
                        delete_blog: actionInput.value,
                        blog_id: idInput.value
                    });
                    
                    document.body.appendChild(form);
                    console.log('Submitting delete form...');
                    form.submit();
                } catch (error) {
                    console.error('Error creating delete form:', error);
                    alert('❌ Error deleting blog: ' + error.message);
                }
            } else {
                console.log('User cancelled deletion');
            }
        };

        window.previewBlog = function(blogId) {
            console.log('Preview blog called with ID:', blogId);
            
            // Get blog data to access slug
            fetch('admin-dashboard.php?action=get_blog&id=' + blogId)
            .then(response => response.json())
            .then(data => {
                if (data.success && data.blog && data.blog.slug) {
                    const url = '../blog/' + data.blog.slug;
                    console.log('Opening URL:', url);
                    window.open(url, '_blank');
                } else {
                    // Fallback to old URL format
                    const url = '../blog-details.php?id=' + blogId;
                    console.log('Opening fallback URL:', url);
                    window.open(url, '_blank');
                }
            })
            .catch(error => {
                console.error('Error fetching blog data:', error);
                // Fallback to old URL format
                const url = '../blog-details.php?id=' + blogId;
                window.open(url, '_blank');
            });
        };

        // Also define without window prefix for compatibility
        function editBlog(blogId) {
            return window.editBlog(blogId);
        }

        function deleteBlogPost(blogId) {
            return window.deleteBlogPost(blogId);
        }

        function previewBlog(blogId) {
            return window.previewBlog(blogId);
        }

        console.log('✅ EARLY LOAD: Global functions defined - showSection, resetBlogForm, editBlog, deleteBlogPost, previewBlog');
    </script>
    
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="default-src 'self' https: data: 'unsafe-inline' 'unsafe-eval'; script-src 'self' https: 'unsafe-inline' 'unsafe-eval'; style-src 'self' https: 'unsafe-inline'; img-src 'self' https: data:;">
    <title>Admin Dashboard | Shubank Gaming</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: #333;
        }

        /* Header */
        .admin-header {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
            padding: 1rem 0;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .header-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 2rem;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .admin-brand {
            display: flex;
            align-items: center;
            gap: 1rem;
            color: white;
        }

        .admin-avatar {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            font-weight: 700;
            color: white;
            border: 2px solid rgba(255, 255, 255, 0.3);
        }

        .admin-info h2 {
            font-size: 1.2rem;
            font-weight: 700;
            margin-bottom: 0.25rem;
        }

        .admin-role {
            font-size: 0.9rem;
            color: rgba(255, 255, 255, 0.8);
            font-weight: 500;
        }

        .header-stats {
            display: flex;
            gap: 2rem;
            align-items: center;
        }

        .stat-item {
            text-align: center;
            color: white;
        }

        .stat-value {
            font-size: 1.5rem;
            font-weight: 800;
            display: block;
            color: #4facfe;
        }

        .stat-label {
            font-size: 0.8rem;
            opacity: 0.9;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .header-actions {
            display: flex;
            gap: 1rem;
            align-items: center;
        }

        .refresh-btn {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            padding: 0.75rem;
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .refresh-btn:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }

        .logout-btn {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .logout-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(239, 68, 68, 0.3);
        }

        /* Main Content */
        .main-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
        }

        /* Dashboard Cards */
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .dashboard-card {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            padding: 2rem;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
            cursor: pointer;
        }

        .dashboard-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #4facfe 0%, #00f2fe 100%);
        }

        .dashboard-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            background: rgba(255, 255, 255, 0.15);
        }

        .card-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 1.5rem;
        }

        .card-title {
            color: white;
            font-size: 1rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .card-icon {
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
        }

        .card-value {
            font-size: 2.5rem;
            font-weight: 800;
            color: white;
            margin-bottom: 0.5rem;
        }

        .card-description {
            color: rgba(255, 255, 255, 0.8);
            font-size: 0.9rem;
            margin-bottom: 1.5rem;
        }

        .card-action {
            width: 100%;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            border: none;
            color: white;
            padding: 0.75rem 1rem;
            border-radius: 12px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .card-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(79, 172, 254, 0.3);
        }

        /* Content Sections */
        .content-section {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border-radius: 20px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            padding: 2rem;
            margin-bottom: 2rem;
            display: none;
        }

        .content-section.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .section-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }

        .section-title {
            color: white;
            font-size: 1.5rem;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .back-btn {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .back-btn:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        /* Tables */
        .table-container {
            overflow-x: auto;
            border-radius: 12px;
            background: rgba(255, 255, 255, 0.05);
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
            background: transparent;
        }

        .data-table th,
        .data-table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            color: white;
        }

        .data-table th {
            background: rgba(255, 255, 255, 0.1);
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-size: 0.9rem;
        }

        .data-table tbody tr:hover {
            background: rgba(255, 255, 255, 0.05);
        }

        .status-badge {
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }

        .status-badge.active {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status-badge.new {
            background: #ffeaa7;
            color: #d63031;
            border: 1px solid #fdcb6e;
        }

        /* Professional Forms */
        .form-container {
            max-width: 700px;
            margin: 0 auto;
            background: linear-gradient(145deg, rgba(30, 58, 138, 0.25) 0%, rgba(67, 56, 202, 0.15) 50%, rgba(30, 58, 138, 0.25) 100%);
            backdrop-filter: blur(25px);
            border: 1px solid rgba(79, 172, 254, 0.25);
            border-radius: 24px;
            padding: 2.5rem;
            box-shadow: 
                0 25px 50px rgba(0, 0, 0, 0.4),
                0 8px 25px rgba(79, 172, 254, 0.15),
                inset 0 1px 0 rgba(79, 172, 254, 0.2);
            position: relative;
            overflow: hidden;
        }

        .form-container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(90deg, #4facfe, #00f2fe, #9f4afe, #4facfe);
            background-size: 300% 100%;
            animation: gradientShift 3s ease-in-out infinite;
        }

        @keyframes gradientShift {
            0%, 100% { background-position: 0% 0%; }
            50% { background-position: 100% 0%; }
        }

        .form-group {
            margin-bottom: 2rem;
            position: relative;
            opacity: 1 !important; /* Ensure visibility */
            transform: translateY(0) !important; /* Ensure position */
        }

        /* Specific styles for Add Result form */
        #add-result-form .form-group {
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            transform: none !important;
        }

        .form-label {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            color: #ffffff;
            font-weight: 700;
            margin-bottom: 0.75rem;
            font-size: 1.1rem;
            text-transform: uppercase;
            letter-spacing: 1.2px;
            text-shadow: 0 2px 8px rgba(79, 172, 254, 0.3);
            position: relative;
        }

        .form-label i {
            font-size: 1.1rem;
            color: #4facfe;
            background: linear-gradient(135deg, rgba(79, 172, 254, 0.2), rgba(0, 242, 254, 0.2));
            padding: 0.5rem;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(79, 172, 254, 0.2);
        }

        .form-input,
        .form-select {
            width: 100%;
            padding: 1.25rem 1.5rem;
            height: 60px;
            background: rgba(255, 255, 255, 0.95);
            border: 2px solid rgba(79, 172, 254, 0.3);
            border-radius: 16px;
            color: #2c3e50;
            font-size: 1.1rem;
            font-weight: 500;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            backdrop-filter: blur(15px);
            box-shadow: 
                0 4px 15px rgba(0, 0, 0, 0.1),
                inset 0 1px 0 rgba(255, 255, 255, 0.8);
            position: relative;
            z-index: 1;
            display: flex;
            align-items: center;
        }

        .form-input::before,
        .form-select::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, rgba(79, 172, 254, 0.1), rgba(0, 242, 254, 0.1));
            border-radius: 16px;
            opacity: 0;
            transition: opacity 0.4s ease;
            z-index: -1;
        }

        .form-select {
            cursor: pointer;
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%234facfe' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6,9 12,15 18,9'%3e%3c/polyline%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right 1.5rem center;
            background-size: 1rem;
            padding-right: 3.5rem;
        }

        .form-select option {
            background: #ffffff !important;
            color: #2c3e50 !important;
            padding: 0.75rem 1rem !important;
            border: none !important;
            font-weight: 500 !important;
            font-size: 1rem !important;
        }

        .form-select option:hover,
        .form-select option:focus,
        .form-select option:checked {
            background: #4facfe !important;
            color: white !important;
        }

        /* Ensure dropdown works in all browsers */
        .form-select::-ms-expand {
            display: none;
        }

        .form-input:focus,
        .form-select:focus {
            outline: none;
            border-color: rgba(79, 172, 254, 0.8);
            background: rgba(255, 255, 255, 1);
            box-shadow: 
                0 0 0 4px rgba(79, 172, 254, 0.15),
                0 8px 25px rgba(79, 172, 254, 0.2),
                inset 0 1px 0 rgba(255, 255, 255, 0.9);
            transform: translateY(-2px);
        }

        .form-input:hover,
        .form-select:hover {
            border-color: rgba(79, 172, 254, 0.4);
            transform: translateY(-1px);
            box-shadow: 
                0 10px 30px rgba(0, 0, 0, 0.2),
                inset 0 1px 0 rgba(255, 255, 255, 0.15);
        }

        .form-input::placeholder {
            color: rgba(44, 62, 80, 0.5);
            font-weight: 400;
            font-style: italic;
        }

        .submit-btn {
            width: 100%;
            height: 60px;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 50%, #667eea 100%) !important;
            background-size: 200% 100%;
            border: none !important;
            color: white !important;
            padding: 1.25rem 2rem;
            border-radius: 16px;
            font-weight: 700;
            font-size: 1.1rem;
            cursor: pointer !important;
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
            text-transform: uppercase;
            letter-spacing: 1.2px;
            margin-top: 2rem;
            box-shadow: 
                0 8px 25px rgba(79, 172, 254, 0.4),
                0 4px 16px rgba(0, 0, 0, 0.15);
            position: relative;
            overflow: hidden;
            pointer-events: auto !important;
            opacity: 1 !important;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.75rem;
        }

        .submit-btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s ease;
        }

        .submit-btn:hover {
            background: linear-gradient(135deg, #00f2fe 0%, #4facfe 50%, #667eea 100%) !important;
            background-position: 100% 0;
            transform: translateY(-3px) scale(1.02);
            box-shadow: 
                0 15px 40px rgba(79, 172, 254, 0.6),
                0 8px 25px rgba(0, 0, 0, 0.2);
        }

        .submit-btn:hover::before {
            left: 100%;
        }

        .submit-btn:active {
            transform: translateY(-2px) scale(1.01);
            transition: all 0.1s ease;
        }

        .submit-btn i {
            margin-right: 0.75rem;
            font-size: 1.2rem;
        }

        /* Enhanced visual feedback */
        .form-group:hover .form-label {
            /* Removed color change on hover for better readability */
            text-shadow: 0 0 10px rgba(79, 172, 254, 0.5);
        }

        .form-group:hover .form-label i {
            background: linear-gradient(135deg, rgba(79, 172, 254, 0.3), rgba(0, 242, 254, 0.3));
            box-shadow: 0 6px 20px rgba(79, 172, 254, 0.4);
        }

        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }

        .btn {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 600;
            font-size: 0.85rem;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
        }

        .btn-update {
            background: #4facfe;
            color: white;
        }

        .btn-delete {
            background: #ef4444;
            color: white;
        }

        .btn-whatsapp {
            background: #25d366;
            color: white;
        }

        .btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        }

        /* Alerts */
        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-weight: 500;
        }

        .alert-success {
            background: rgba(34, 197, 94, 0.2);
            border: 1px solid rgba(34, 197, 94, 0.3);
            color: #bbf7d0;
        }

        .alert-error {
            background: rgba(239, 68, 68, 0.2);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #fecaca;
        }

        /* Mobile Responsiveness */
        @media (max-width: 768px) {
            .header-content {
                flex-direction: column;
                text-align: center;
            }

            .header-stats {
                gap: 1rem;
            }

            .main-content {
                padding: 1rem;
            }

            .dashboard-grid {
                grid-template-columns: 1fr;
                gap: 1rem;
            }

            .dashboard-card {
                padding: 1.5rem;
            }

            .card-value {
                font-size: 2rem;
            }

            .data-table th,
            .data-table td {
                padding: 0.75rem 0.5rem;
                font-size: 0.9rem;
            }

            .action-buttons {
                flex-direction: column;
            }

            .section-header {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }

            /* Enhanced Form Mobile Styles */
            .form-container {
                padding: 1.5rem;
                margin: 1rem;
                border-radius: 16px;
            }

            .form-group {
                margin-bottom: 1.5rem;
            }

            .form-label {
                font-size: 0.9rem;
                letter-spacing: 0.5px;
                gap: 0.5rem;
            }

            .form-label i {
                font-size: 1rem;
                padding: 0.4rem;
            }

            .form-input,
            .form-select {
                padding: 1rem 1.25rem;
                font-size: 1rem;
                border-radius: 12px;
            }

            .form-select {
                background-size: 1rem;
                padding-right: 3.5rem;
            }

            .submit-btn {
                padding: 1.25rem 1.5rem;
                font-size: 1rem;
                letter-spacing: 1px;
                border-radius: 14px;
            }
        }

        @media (max-width: 480px) {
            .main-content {
                padding: 0.5rem;
            }

            .dashboard-card {
                padding: 1rem;
            }

            .card-value {
                font-size: 1.75rem;
            }

            .data-table {
                font-size: 0.8rem;
            }

            .data-table th,
            .data-table td {
                padding: 0.5rem 0.25rem;
            }

            /* Extra Small Screen Form Enhancements */
            .form-container {
                padding: 1.25rem;
                margin: 0.5rem;
                border-radius: 12px;
            }

            .form-group {
                margin-bottom: 1.25rem;
            }

            .form-label {
                font-size: 0.85rem;
                flex-direction: column;
                align-items: flex-start;
                gap: 0.5rem;
            }

            .form-label i {
                align-self: center;
                font-size: 0.9rem;
                padding: 0.35rem;
            }

            .form-input,
            .form-select {
                padding: 0.9rem 1rem;
                font-size: 0.95rem;
                border-radius: 10px;
            }

            .form-select {
                background-size: 0.9rem;
                padding-right: 3rem;
                background-position: right 1rem center;
            }

            .submit-btn {
                padding: 1.1rem 1.25rem;
                font-size: 0.95rem;
                letter-spacing: 0.8px;
                border-radius: 12px;
                margin-top: 1.5rem;
            }

            .submit-btn i {
                margin-right: 0.5rem;
                font-size: 1rem;
            }
        }

        /* Enhanced Form Validation & Interaction Styles */
        .form-input:valid,
        .form-select:valid {
            border-color: rgba(34, 197, 94, 0.6);
            box-shadow: 
                0 0 0 2px rgba(34, 197, 94, 0.1),
                0 8px 25px rgba(0, 0, 0, 0.15),
                inset 0 1px 0 rgba(255, 255, 255, 0.1);
        }

        .form-input:invalid:not(:placeholder-shown),
        .form-select:invalid:not(:placeholder-shown) {
            border-color: rgba(239, 68, 68, 0.6);
            animation: shake 0.4s ease-in-out;
        }

        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-4px); }
            75% { transform: translateX(4px); }
        }

        .form-input:required:invalid::after {
            content: '⚠️';
            position: absolute;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #ef4444;
        }

        /* Enhanced Submit Button States */
        .submit-btn:disabled {
            background: linear-gradient(135deg, #22c55e 0%, #16a34a 50%, #15803d 100%) !important;
            cursor: pointer !important;
            transform: none;
            box-shadow: 0 12px 35px rgba(34, 197, 94, 0.4), 0 4px 16px rgba(0, 0, 0, 0.2);
            pointer-events: auto !important;
            opacity: 1 !important;
        }

        .submit-btn.needs-validation {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 50%, #b45309 100%) !important;
            box-shadow: 0 12px 35px rgba(245, 158, 11, 0.4), 0 4px 16px rgba(0, 0, 0, 0.2);
        }

        .submit-btn.loading {
            position: relative;
            color: transparent;
        }

        .submit-btn.loading::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            width: 20px;
            height: 20px;
            margin: -10px 0 0 -10px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top: 2px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        /* Form Success/Error States */
        .form-success {
            padding: 1rem;
            background: linear-gradient(135deg, rgba(34, 197, 94, 0.2), rgba(16, 185, 129, 0.1));
            border: 1px solid rgba(34, 197, 94, 0.3);
            border-radius: 12px;
            color: #bbf7d0;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .form-error {
            padding: 1rem;
            background: linear-gradient(135deg, rgba(239, 68, 68, 0.2), rgba(220, 38, 38, 0.1));
            border: 1px solid rgba(239, 68, 68, 0.3);
            border-radius: 12px;
            color: #fecaca;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        /* Input Focus Ring Enhancement */
        .form-group:focus-within .form-label {
            color: #60a5fa;
            text-shadow: 0 0 15px rgba(96, 165, 250, 0.6);
            transform: translateY(-2px);
            transition: all 0.3s ease;
        }

        .form-group:focus-within .form-label i {
            background: linear-gradient(135deg, rgba(79, 172, 254, 0.4), rgba(0, 242, 254, 0.4));
            box-shadow: 0 8px 25px rgba(79, 172, 254, 0.5);
            transform: scale(1.1);
        }

        /* Professional Hover Effects */
        .form-container:hover {
            box-shadow: 
                0 25px 50px rgba(0, 0, 0, 0.35),
                0 6px 20px rgba(0, 0, 0, 0.15),
                inset 0 1px 0 rgba(255, 255, 255, 0.25);
            transform: translateY(-2px);
            transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }

        /* Loading States */
        .loading {
            opacity: 0.6;
            pointer-events: none;
        }

        .spinner {
            width: 20px;
            height: 20px;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-top: 2px solid white;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Utility Classes */
        .text-center { text-align: center; }
        .mb-1 { margin-bottom: 1rem; }
        .mb-2 { margin-bottom: 2rem; }
        .mt-1 { margin-top: 1rem; }
        .mt-2 { margin-top: 2rem; }
        .flex { display: flex; }
        .justify-between { justify-content: space-between; }
        .items-center { align-items: center; }
        .gap-1 { gap: 1rem; }

        /* Blog Management Styles */
        .blog-form-container {
            background: white;
            border-radius: 12px;
            padding: 24px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }

        .blog-form {
            max-width: 100%;
        }

        .form-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 30px;
        }

        .form-column,
        .form-sidebar {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
            gap: 6px;
        }

        .form-label {
            font-weight: 600;
            color: #2c3e50;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .form-input,
        .form-select,
        .form-textarea {
            padding: 12px;
            border: 2px solid #e9ecef;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
            background: #f8f9fa;
            color: #2c3e50;
        }

        .form-input:focus,
        .form-select:focus,
        .form-textarea:focus {
            outline: none;
            border-color: #3498db;
            background: white;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
            color: #2c3e50;
        }

        .form-textarea {
            resize: vertical;
            min-height: 100px;
        }

        .form-input::placeholder,
        .form-textarea::placeholder {
            color: #6c757d;
            opacity: 1;
        }

        .form-textarea-rich {
            min-height: 400px;
        }

        .form-file {
            padding: 8px;
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            background: #f8f9fa;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .form-file:hover {
            border-color: #3498db;
            background: #fff;
        }

        .form-help {
            font-size: 12px;
            color: #6c757d;
            margin-top: 4px;
        }

        .sidebar-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 16px;
            border: 1px solid #e9ecef;
        }

        .sidebar-title {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .form-actions {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            margin-top: 24px;
            padding-top: 20px;
            border-top: 1px solid #e9ecef;
        }

        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 6px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            text-decoration: none;
            font-size: 14px;
        }

        .btn-primary {
            background: linear-gradient(135deg, #3498db 0%, #2c3e50 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
            color: white;
            text-decoration: none;
        }

        .btn-secondary {
            background: #f8f9fa;
            color: #495057;
            border: 1px solid #dee2e6;
        }

        .btn-secondary:hover {
            background: #e9ecef;
            color: #495057;
            text-decoration: none;
        }

        .btn-danger {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
        }

        .btn-danger:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(231, 76, 60, 0.4);
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 12px;
        }

        /* Blog Management */
        .blog-management-container {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        }

        .blog-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            padding: 24px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            border-bottom: 1px solid #dee2e6;
        }

        .stat-card {
            background: white;
            padding: 16px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            gap: 12px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .stat-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, #3498db 0%, #2c3e50 100%);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 18px;
        }

        .stat-number {
            font-size: 24px;
            font-weight: 700;
            color: #2c3e50;
        }

        .stat-label {
            font-size: 14px;
            color: #6c757d;
            font-weight: 500;
        }

        .blog-list {
            padding: 24px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #6c757d;
        }

        .empty-state i {
            font-size: 64px;
            color: #dee2e6;
            margin-bottom: 16px;
        }

        .empty-state h3 {
            font-size: 20px;
            margin-bottom: 8px;
            color: #495057;
        }

        .empty-state p {
            margin-bottom: 20px;
        }

        .blog-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 24px;
        }

        .blog-item {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
            transition: all 0.3s ease;
            border: 1px solid #e9ecef;
        }

        .blog-item:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
        }

        .blog-image {
            height: 200px;
            position: relative;
            overflow: hidden;
            border-radius: 8px;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        }

        .blog-image img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            object-position: center;
            transition: transform 0.3s ease;
        }
        
        .blog-image:hover img {
            transform: scale(1.05);
        }

        .blog-placeholder {
            width: 100%;
            height: 100%;
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #adb5bd;
            font-size: 48px;
        }

        .blog-status {
            position: absolute;
            top: 12px;
            right: 12px;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 10px;
            font-weight: 600;
            text-transform: uppercase;
        }

        .blog-status.published {
            background: rgba(34, 197, 94, 0.9);
            color: white;
        }

        .blog-status.draft {
            background: rgba(251, 191, 36, 0.9);
            color: #92400e;
        }

        .blog-content {
            padding: 16px;
        }

        .blog-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
            font-size: 12px;
        }

        .blog-category {
            background: #e9ecef;
            color: #495057;
            padding: 2px 6px;
            border-radius: 4px;
            font-weight: 600;
        }

        .blog-date {
            color: #6c757d;
        }

        .blog-title {
            font-size: 16px;
            font-weight: 600;
            color: #2c3e50;
            margin-bottom: 8px;
            line-height: 1.3;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .blog-excerpt {
            color: #6c757d;
            font-size: 14px;
            line-height: 1.4;
            margin-bottom: 12px;
        }

        .blog-stats {
            display: flex;
            gap: 16px;
            margin-bottom: 12px;
            font-size: 12px;
            color: #6c757d;
        }

        .blog-stats span {
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .blog-actions {
            display: flex;
            gap: 6px;
            flex-wrap: wrap;
        }

        .header-actions {
            display: flex;
            gap: 12px;
            align-items: center;
        }

        /* Responsive Design */
        @media (max-width: 1024px) {
            .form-grid {
                grid-template-columns: 1fr;
            }

            .form-sidebar {
                order: -1;
            }
        }

        @media (max-width: 768px) {
            .blog-grid {
                grid-template-columns: 1fr;
            }

            .blog-stats {
                grid-template-columns: 1fr;
            }

            .form-actions {
                flex-direction: column;
            }

            .header-actions {
                flex-direction: column;
                width: 100%;
            }

            .blog-actions {
                flex-direction: column;
            }
        }

        /* Alert Styles */
        .alert {
            padding: 12px 16px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .alert-success {
            background: #d1edff;
            color: #0c5460;
            border: 1px solid #b6effb;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        /* CKEditor Customization */
        .ck-editor__editable {
            min-height: 400px !important;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif !important;
        }

        .ck.ck-editor {
            border-radius: 8px !important;
            border: 2px solid #e9ecef !important;
            overflow: hidden;
        }

        .ck.ck-editor:focus-within {
            border-color: #3498db !important;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1) !important;
        }

        .ck.ck-toolbar {
            border-bottom: 1px solid #e9ecef !important;
            background: #f8f9fa !important;
        }

        .ck.ck-content {
            color: #2c3e50 !important;
        }

        /* Contact Management Styles */
        .new-inquiry {
            background-color: #fff3cd !important;
            border-left: 4px solid #ffc107 !important;
        }

        .message-preview {
            max-width: 200px;
            word-wrap: break-word;
            cursor: pointer;
        }

        /* Professional Contact Form Inquiries Styles */
        #contact_management {
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.05) 0%, rgba(255, 255, 255, 0.02) 100%);
            border-radius: 16px;
            padding: 2rem;
            margin: 2rem 0;
            border: 1px solid rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
            padding-bottom: 1rem;
            border-bottom: 2px solid rgba(255, 255, 255, 0.1);
        }

        .section-title {
            font-size: 2rem;
            font-weight: 700;
            color: white;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .section-title i {
            font-size: 1.5rem;
            color: #4facfe;
            background: rgba(79, 172, 254, 0.2);
            padding: 0.5rem;
            border-radius: 12px;
        }

        .section-stats {
            display: flex;
            gap: 1rem;
            margin-bottom: 0;
            flex-wrap: wrap;
        }

        .stat-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 1rem 1.5rem;
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0.05) 100%);
            border-radius: 12px;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
            min-width: 90px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            transition: all 0.3s ease;
        }

        .stat-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
        }

        .stat-label {
            font-size: 0.85rem;
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 0.5rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-weight: 500;
        }

        .stat-value {
            font-size: 1.5rem;
            font-weight: 700;
            color: white;
        }

        /* Enhanced Table Styles */
        .table-container {
            overflow-x: auto;
            border-radius: 16px;
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.08) 0%, rgba(255, 255, 255, 0.03) 100%);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            margin-top: 1.5rem;
        }

        .admin-table {
            width: 100%;
            border-collapse: collapse;
            background: transparent;
            font-size: 0.95rem;
        }

        .admin-table th {
            padding: 1.25rem 1rem;
            text-align: left;
            background: linear-gradient(135deg, rgba(79, 172, 254, 0.2) 0%, rgba(102, 126, 234, 0.2) 100%);
            color: white;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-size: 0.85rem;
            border-bottom: 2px solid rgba(255, 255, 255, 0.1);
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .admin-table th:first-child {
            border-top-left-radius: 16px;
            padding-left: 1.5rem;
        }

        .admin-table th:last-child {
            border-top-right-radius: 16px;
            padding-right: 1.5rem;
        }

        .admin-table td {
            padding: 1rem;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
            color: #2c3e50;
            vertical-align: middle;
            font-weight: 500;
        }

        .admin-table td:first-child {
            padding-left: 1.5rem;
            font-weight: 700;
            color: #3498db;
        }

        .admin-table td:last-child {
            padding-right: 1.5rem;
        }

        .admin-table tbody tr {
            transition: all 0.3s ease;
            border-left: 3px solid transparent;
        }

        .admin-table tbody tr:hover {
            background: linear-gradient(135deg, rgba(79, 172, 254, 0.1) 0%, rgba(102, 126, 234, 0.05) 100%);
            border-left-color: #4facfe;
            transform: translateX(2px);
        }

        .admin-table tbody tr.new-inquiry {
            background: linear-gradient(135deg, rgba(255, 193, 7, 0.2) 0%, rgba(255, 193, 7, 0.1) 100%);
            border-left-color: #ffc107;
        }

        .admin-table tbody tr.new-inquiry:hover {
            background: linear-gradient(135deg, rgba(255, 193, 7, 0.25) 0%, rgba(255, 193, 7, 0.15) 100%);
        }

        .admin-table tbody tr.new-inquiry td {
            color: #2c3e50;
            font-weight: 600;
        }

        /* Enhanced Contact Method Badges */
        .contact-method-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            border: 1px solid transparent;
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .contact-method-email {
            background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
            color: white;
            border-color: rgba(33, 150, 243, 0.3);
        }

        .contact-method-phone {
            background: linear-gradient(135deg, #9c27b0 0%, #673ab7 100%);
            color: white;
            border-color: rgba(156, 39, 176, 0.3);
        }

        .contact-method-whatsapp {
            background: linear-gradient(135deg, #25d366 0%, #128c7e 100%);
            color: white;
            border-color: rgba(37, 211, 102, 0.3);
        }

        /* Enhanced Status Badges */
        .status-badge {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            border: 1px solid transparent;
        }

        .status-new {
            background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
            color: white;
            border-color: rgba(255, 152, 0, 0.3);
        }

        .status-new::before {
            content: "🔥";
            font-size: 0.9rem;
        }

        .status-replied {
            background: linear-gradient(135deg, #4caf50 0%, #388e3c 100%);
            color: white;
            border-color: rgba(76, 175, 80, 0.3);
        }

        .status-replied::before {
            content: "✅";
            font-size: 0.9rem;
        }

        .status-resolved {
            background: linear-gradient(135deg, #00bcd4 0%, #0097a7 100%);
            color: white;
            border-color: rgba(0, 188, 212, 0.3);
        }

        .status-resolved::before {
            content: "🎯";
            font-size: 0.9rem;
        }

        /* Message Preview Enhancement */
        .message-preview {
            max-width: 200px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            cursor: help;
            padding: 0.5rem;
            background: rgba(52, 152, 219, 0.08);
            border-radius: 8px;
            border-left: 3px solid #3498db;
            color: #2c3e50;
            font-weight: 500;
        }

        .message-preview:hover {
            background: rgba(52, 152, 219, 0.15);
            white-space: normal;
            max-width: 300px;
            transition: all 0.3s ease;
            color: #1f4e79;
        }

        /* Phone Number Link Enhancement */
        .admin-table td a[href^="tel:"] {
            color: #2980b9;
            text-decoration: none;
            font-weight: 600;
            padding: 0.25rem 0.5rem;
            border-radius: 6px;
            background: rgba(52, 152, 219, 0.1);
            transition: all 0.3s ease;
        }

        .admin-table td a[href^="tel:"]:hover {
            background: rgba(52, 152, 219, 0.2);
            color: #1f4e79;
            transform: scale(1.05);
        }

        /* Empty State Enhancement */
        .admin-table tbody tr td[colspan] {
            text-align: center;
            padding: 4rem 2rem;
            background: linear-gradient(135deg, rgba(255, 255, 255, 0.05) 0%, rgba(255, 255, 255, 0.02) 100%);
            color: #7f8c8d;
        }

        .admin-table tbody tr td[colspan] i {
            display: block;
            font-size: 4rem;
            margin-bottom: 1rem;
            color: #bdc3c7;
        }

        .admin-table tbody tr td[colspan] div {
            font-size: 1.2rem;
            font-weight: 600;
            color: #7f8c8d;
        }

        /* Alert Messages Enhancement */
        .alert {
            padding: 1rem 1.5rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
            border: 1px solid transparent;
            backdrop-filter: blur(10px);
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }

        .alert-success {
            background: linear-gradient(135deg, rgba(76, 175, 80, 0.15) 0%, rgba(76, 175, 80, 0.08) 100%);
            color: #4caf50;
            border-color: rgba(76, 175, 80, 0.3);
        }

        .alert-danger {
            background: linear-gradient(135deg, rgba(244, 67, 54, 0.15) 0%, rgba(244, 67, 54, 0.08) 100%);
            color: #f44336;
            border-color: rgba(244, 67, 54, 0.3);
        }

        /* Responsive Design for Contact Management */
        @media (max-width: 1200px) {
            .section-header {
                flex-direction: column;
                gap: 1rem;
                align-items: flex-start;
            }

            .section-stats {
                width: 100%;
                justify-content: center;
            }
        }

        @media (max-width: 768px) {
            #contact_management {
                padding: 1rem;
                margin: 1rem 0;
            }

            .section-title {
                font-size: 1.5rem;
            }

            .section-stats {
                grid-template-columns: repeat(2, 1fr);
                gap: 0.75rem;
            }

            .stat-item {
                padding: 0.75rem 1rem;
                min-width: auto;
            }

            .admin-table th,
            .admin-table td {
                padding: 0.75rem 0.5rem;
                font-size: 0.85rem;
            }

            .admin-table th:first-child,
            .admin-table td:first-child {
                padding-left: 1rem;
            }

            .admin-table th:last-child,
            .admin-table td:last-child {
                padding-right: 1rem;
            }

            .message-preview {
                max-width: 120px;
            }

            .contact-method-badge,
            .status-badge {
                font-size: 0.75rem;
                padding: 0.35rem 0.75rem;
            }
        }

        @media (max-width: 480px) {
            .section-stats {
                grid-template-columns: 1fr;
            }

            .table-container {
                margin: 0 -1rem;
                border-radius: 0;
            }

            .admin-table {
                font-size: 0.8rem;
            }

            .admin-table th,
            .admin-table td {
                padding: 0.5rem 0.25rem;
            }
        }

        .stat-value {
            font-size: 1.5em;
            font-weight: bold;
        }

        .pagination {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-top: 20px;
        }

        .page-btn {
            padding: 8px 12px;
            background: white;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-decoration: none;
            color: #333;
            transition: all 0.3s ease;
        }

        .page-btn:hover {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }

        .page-btn.active {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }

        @media (max-width: 768px) {
            .section-stats {
                flex-wrap: wrap;
                gap: 10px;
            }
            
            .stat-item {
                min-width: 60px;
                padding: 8px 10px;
            }
            
            .admin-table {
                font-size: 0.85em;
            }
            
            .message-preview {
                max-width: 150px;
            }
        }

        /* Blog Form Mobile Responsiveness */
        @media (max-width: 1024px) {
            .form-grid {
                grid-template-columns: 1fr;
                gap: 20px;
            }
            
            .form-sidebar {
                order: -1; /* Show sidebar above main content on smaller screens */
            }
        }

        @media (max-width: 768px) {
            .blog-form-container {
                padding: 16px;
                margin: 10px;
                border-radius: 8px;
            }
            
            .form-grid {
                gap: 15px;
            }
            
            .form-group {
                gap: 4px;
            }
            
            .form-label {
                font-size: 13px;
            }
            
            .form-input,
            .form-select,
            .form-textarea {
                padding: 12px;
                font-size: 16px; /* Prevents zoom on iOS */
            }
            
            .sidebar-section {
                padding: 15px;
            }
            
            .sidebar-title {
                font-size: 14px;
            }
            
            /* CKEditor mobile optimization */
            .ck-editor__editable {
                min-height: 300px !important;
                font-size: 16px !important;
            }
            
            .ck-toolbar {
                flex-wrap: wrap !important;
            }
            
            .ck-toolbar__items {
                flex-wrap: wrap !important;
            }
            
            /* Form buttons mobile */
            .blog-form button {
                padding: 12px 20px;
                font-size: 16px;
            }
        }

        @media (max-width: 480px) {
            .blog-form-container {
                padding: 12px;
                margin: 5px;
            }
            
            .form-input,
            .form-select,
            .form-textarea {
                padding: 10px;
            }
            
            .ck-editor__editable {
                min-height: 250px !important;
                font-size: 16px !important;
            }
            
            .blog-form button {
                width: 100%;
                margin-bottom: 10px;
            }
            
            .sidebar-section {
                padding: 12px;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="admin-header">
        <div class="header-content">
            <div class="admin-brand">
                <div class="admin-avatar">
                    <?php echo strtoupper(substr($admin_name, 0, 1)); ?>
                </div>
                <div class="admin-info">
                    <h2><?php echo htmlspecialchars($admin_name); ?></h2>
                    <div class="admin-role">System Administrator</div>
                </div>
            </div>

            <div class="header-stats">
                <div class="stat-item">
                    <span class="stat-value">₹<?php echo number_format($today_amount ?? 0); ?></span>
                    <span class="stat-label">Today's Total</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value"><?php echo count($today_entries ?? []); ?></span>
                    <span class="stat-label">Today's Entries</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value"><?php echo count($today_users ?? []); ?></span>
                    <span class="stat-label">Active Users</span>
                </div>
            </div>

            <div class="header-actions">
                <button class="refresh-btn" onclick="location.reload()">
                    <i class="fas fa-sync-alt"></i>
                    <span>Refresh</span>
                </button>
                <a href="admin-logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>Logout</span>
                </a>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <main class="main-content">
        <!-- Dashboard Overview -->
        <div id="dashboard-overview" class="content-section active">
            <div class="dashboard-grid">
                <!-- Today's Entries Card -->
                <div class="dashboard-card">
                    <div class="card-header">
                        <h3 class="card-title">Today's Entries</h3>
                        <div class="card-icon">
                            <i class="fas fa-calendar-day"></i>
                        </div>
                    </div>
                    <div class="card-value"><?php echo count($today_entries ?? []); ?></div>
                    <div class="card-description">Entries submitted today</div>
                    <button class="card-action" onclick="showSection('today_entries')">
                        <i class="fas fa-eye"></i> View Details
                    </button>
                </div>

                <!-- All Entries Card -->
                <div class="dashboard-card">
                    <div class="card-header">
                        <h3 class="card-title">All Entries</h3>
                        <div class="card-icon">
                            <i class="fas fa-list"></i>
                        </div>
                    </div>
                    <div class="card-value"><?php echo count($all_entries ?? []); ?></div>
                    <div class="card-description">Total system entries</div>
                    <button class="card-action" onclick="showSection('all_entries')">
                        <i class="fas fa-eye"></i> View All
                    </button>
                </div>

                <!-- Today's Active Users Card -->
                <div class="dashboard-card">
                    <div class="card-header">
                        <h3 class="card-title">Active Users</h3>
                        <div class="card-icon">
                            <i class="fas fa-users"></i>
                        </div>
                    </div>
                    <div class="card-value"><?php echo count($today_users ?? []); ?></div>
                    <div class="card-description">Currently logged in</div>
                    <button class="card-action" onclick="showSection('today_users')">
                        <i class="fas fa-eye"></i> View Active
                    </button>
                </div>

                <!-- Today's New Users Card -->
                <div class="dashboard-card" style="background: linear-gradient(135deg, #fd7e14 0%, #e83e8c 100%);">
                    <div class="card-header">
                        <h3 class="card-title" style="color: white;">New Users Today</h3>
                        <div class="card-icon" style="color: white;">
                            <i class="fas fa-user-plus"></i>
                        </div>
                    </div>
                    <div class="card-value" style="color: white;">
                        <?php 
                        // Get today's new registered users count
                        $today_new_users_count = 0;
                        // First check if created_at column exists
                        $check_column = mysqli_query($link, "SHOW COLUMNS FROM users LIKE 'created_at'");
                        if ($check_column && mysqli_num_rows($check_column) > 0) {
                            $res = mysqli_query($link, "SELECT COUNT(*) as count FROM users WHERE DATE(created_at) = '$today'");
                            if ($res && $row = mysqli_fetch_assoc($res)) {
                                $today_new_users_count = $row['count'];
                            }
                        } else {
                            // If created_at doesn't exist, show message instead
                            $today_new_users_count = "N/A";
                        }
                        echo $today_new_users_count;
                        ?>
                    </div>
                    <div class="card-description" style="color: rgba(255,255,255,0.9);">Registered today</div>
                    <button class="card-action" onclick="showSection('today_new_users')" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);">
                        <i class="fas fa-eye"></i> View New
                    </button>
                </div>

                <!-- Total Users Card -->
                <div class="dashboard-card">
                    <div class="card-header">
                        <h3 class="card-title">Total Users</h3>
                        <div class="card-icon">
                            <i class="fas fa-user-friends"></i>
                        </div>
                    </div>
                    <div class="card-value"><?php echo $total_users ?? 0; ?></div>
                    <div class="card-description">All registered users</div>
                    <button class="card-action" onclick="showSection('total_users')">
                        <i class="fas fa-eye"></i> View All Users
                    </button>
                </div>

                <!-- Add Result Card -->
                <div class="dashboard-card">
                    <div class="card-header">
                        <h3 class="card-title">Add Results</h3>
                        <div class="card-icon">
                            <i class="fas fa-plus-circle"></i>
                        </div>
                    </div>
                    <div class="card-value"><i class="fas fa-trophy"></i></div>
                    <div class="card-description">Add game results</div>
                    <button class="card-action" onclick="showSection('add_result')">
                        <i class="fas fa-plus"></i> Add Result
                    </button>
                </div>

                <!-- Copy Report Card -->
                <div class="dashboard-card">
                    <div class="card-header">
                        <h3 class="card-title">Copy Report</h3>
                        <div class="card-icon">
                            <i class="fas fa-copy"></i>
                        </div>
                    </div>
                    <div class="card-value"><i class="fas fa-clipboard-list"></i></div>
                    <div class="card-description">Generate daily report</div>
                    <button class="card-action" onclick="showSection('generate_copy_report')">
                        <i class="fas fa-file-alt"></i> Generate Report
                    </button>
                </div>

                <!-- Shared Entries Card -->
                <div class="dashboard-card" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">
                    <div class="card-header">
                        <h3 class="card-title" style="color: white;">Today's Shared</h3>
                        <div class="card-icon" style="color: white;">
                            <i class="fas fa-share-alt"></i>
                        </div>
                    </div>
                    <div class="card-value" style="color: white;">
                        <?php 
                        // Get today's shared entries count
                        $today_shared_count = 0;
                        $res = mysqli_query($link, "SELECT COUNT(*) as count FROM entries_shared WHERE DATE(entry_time) = '$today'");
                        if ($res && $row = mysqli_fetch_assoc($res)) {
                            $today_shared_count = $row['count'];
                        }
                        echo $today_shared_count;
                        ?>
                    </div>
                    <div class="card-description" style="color: rgba(255,255,255,0.9);">Today's shared entries</div>
                    <button class="card-action" onclick="showSection('today_shared_entries')" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);">
                        <i class="fas fa-eye"></i> View Today's
                    </button>
                </div>

                <!-- All Shared Entries Card -->
                <div class="dashboard-card" style="background: linear-gradient(135deg, #17a2b8 0%, #6f42c1 100%);">
                    <div class="card-header">
                        <h3 class="card-title" style="color: white;">All Shared</h3>
                        <div class="card-icon" style="color: white;">
                            <i class="fas fa-database"></i>
                        </div>
                    </div>
                    <div class="card-value" style="color: white;">
                        <?php 
                        // Get all shared entries count
                        $all_shared_count = 0;
                        // Check if entries_shared table exists
                        $check_table = mysqli_query($link, "SHOW TABLES LIKE 'entries_shared'");
                        if ($check_table && mysqli_num_rows($check_table) > 0) {
                            $res = mysqli_query($link, "SELECT COUNT(*) as count FROM entries_shared");
                            if ($res && $row = mysqli_fetch_assoc($res)) {
                                $all_shared_count = $row['count'];
                            }
                        }
                        echo $all_shared_count;
                        ?>
                    </div>
                    <div class="card-description" style="color: rgba(255,255,255,0.9);">Total shared entries</div>
                    <button class="card-action" onclick="showSection('all_shared_entries')" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);">
                        <i class="fas fa-eye"></i> View All
                    </button>
                </div>

                <!-- Blog Management Cards -->
                <div class="dashboard-card" style="background: linear-gradient(135deg, #6f42c1 0%, #e83e8c 100%);">
                    <div class="card-header">
                        <h3 class="card-title" style="color: white;">Create Blog</h3>
                        <div class="card-icon" style="color: white;">
                            <i class="fas fa-pen"></i>
                        </div>
                    </div>
                    <div class="card-value" style="color: white;"><i class="fas fa-plus-circle"></i></div>
                    <div class="card-description" style="color: rgba(255,255,255,0.9);">Write new blog post</div>
                    <button class="card-action" onclick="showSection('create_blog')" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);">
                        <i class="fas fa-edit"></i> Create Post
                    </button>
                </div>

                <div class="dashboard-card" style="background: linear-gradient(135deg, #20c997 0%, #17a2b8 100%);">
                    <div class="card-header">
                        <h3 class="card-title" style="color: white;">Manage Blogs</h3>
                        <div class="card-icon" style="color: white;">
                            <i class="fas fa-list"></i>
                        </div>
                    </div>
                    <div class="card-value" style="color: white;"><?php echo $blog_stats['total_blogs'] ?? 0; ?></div>
                    <div class="card-description" style="color: rgba(255,255,255,0.9);">Total blog posts</div>
                    <button class="card-action" onclick="showSection('blog_management')" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);">
                        <i class="fas fa-cogs"></i> Manage Posts
                    </button>
                </div>

                <!-- Contact Management Card -->
                <div class="dashboard-card" style="background: linear-gradient(135deg, #fd7e14 0%, #dc3545 100%);">
                    <div class="card-header">
                        <h3 class="card-title" style="color: white;">Contact Inquiries</h3>
                        <div class="card-icon" style="color: white;">
                            <i class="fas fa-envelope"></i>
                        </div>
                    </div>
                    <div class="card-value" style="color: white;"><?php echo $contact_stats['total_contacts']; ?></div>
                    <div class="card-description" style="color: rgba(255,255,255,0.9);">
                        <?php echo $contact_stats['new_contacts']; ?> new inquiries
                    </div>
                    <button class="card-action" onclick="showSection('contact_management')" style="background: rgba(255,255,255,0.2); color: white; border: 1px solid rgba(255,255,255,0.3);">
                        <i class="fas fa-comments"></i> View Inquiries
                    </button>
                </div>
            </div>
        </div>

        <!-- Add Result Section -->
        <div id="add_result" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-plus-circle"></i>
                    Add Game Results
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <?php 
            // Check for messages from session or GET parameters
            $display_msg = '';
            if (isset($_SESSION['result_msg'])) {
                $display_msg = $_SESSION['result_msg'];
                unset($_SESSION['result_msg']); // Clear the message
            } elseif (isset($_GET['msg'])) {
                $display_msg = $_GET['msg'];
            }
            
            if (!empty($display_msg)) { ?>
                <?php if ($display_msg === 'success') { ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        Result added successfully!
                    </div>
                <?php } elseif ($display_msg === 'error') { ?>
                    <div class="alert alert-error">
                        <i class="fas fa-exclamation-triangle"></i>
                        Error adding result. Please try again.
                    </div>
                <?php } elseif ($display_msg === 'dberror') { ?>
                    <div class="alert alert-error">
                        <i class="fas fa-database"></i>
                        Database error occurred.
                    </div>
                <?php } elseif ($display_msg === 'missing') { ?>
                    <div class="alert alert-error">
                        <i class="fas fa-exclamation-circle"></i>
                        Please fill in all required fields.
                    </div>
                <?php } ?>
            <?php } ?>

            <div class="form-container">
                <form method="post" action="admin-dashboard.php" id="add-result-form">
                    <input type="hidden" name="show_section" value="add_result">
                    
                    <div class="form-group">
                        <label for="result_date" class="form-label">
                            <i class="fas fa-calendar"></i> Date
                        </label>
                        <input type="date" name="result_date" id="result_date" class="form-input" required
                               value="<?php echo date('Y-m-d'); ?>" aria-label="Select result date">
                    </div>

                    <div class="form-group">
                        <label for="game" class="form-label">
                            <i class="fas fa-gamepad"></i> Game
                        </label>
                        <select name="game" id="game" class="form-select" required aria-label="Select Game">
                            <option value="">Select Game</option>
                            <option value="disawar">Disawar</option>
                            <option value="dl_bazaar">DL Bazaar</option>
                            <option value="shri_ganesh">Shri Ganesh</option>
                            <option value="faridabad">Faridabad</option>
                            <option value="ghaziabad">Ghaziabad</option>
                            <option value="radhey_radhey">Radhey Radhey</option>
                            <option value="gali">Gali</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="result_number" class="form-label">
                            <i class="fas fa-hashtag"></i> Result Number
                        </label>
                        <input type="text" name="result_number" id="result_number" class="form-input" 
                               placeholder="Enter result number" required pattern="[0-9]+" 
                               title="Please enter only numbers" aria-label="Enter result number">
                    </div>

                    <button type="submit" name="add_result_submit" value="1" class="submit-btn" id="add-result-btn">
                        <i class="fas fa-plus"></i>
                        Add Result
                    </button>
                </form>
                
                <script>
                // Enhanced form handling with detailed debugging
                document.addEventListener('DOMContentLoaded', function() {
                    const form = document.getElementById('add-result-form');
                    if (form) {
                        console.log('✅ Add result form found and ready');
                        console.log('Form action:', form.action);
                        console.log('Form method:', form.method);
                        
                        // Check all form elements
                        const dateField = form.querySelector('[name="result_date"]');
                        const gameField = form.querySelector('[name="game"]');
                        const numberField = form.querySelector('[name="result_number"]');
                        const submitBtn = form.querySelector('[name="add_result_submit"]');
                        
                        console.log('Form fields found:');
                        console.log('- Date field:', dateField ? '✅' : '❌');
                        console.log('- Game field:', gameField ? '✅' : '❌');
                        console.log('- Number field:', numberField ? '✅' : '❌');
                        console.log('- Submit button:', submitBtn ? '✅' : '❌');
                        
                        // Add submit event listener with debugging
                        form.addEventListener('submit', function(e) {
                            console.log('=== FORM SUBMISSION TRIGGERED ===');
                            console.log('Event:', e);
                            console.log('Form element:', this);
                            console.log('Form action:', this.action);
                            console.log('Form method:', this.method);
                            console.log('Form data being submitted:');
                            
                            const formData = new FormData(this);
                            for (let [key, value] of formData.entries()) {
                                console.log(`${key}: ${value}`);
                            }
                            
                            // Validate required fields
                            const date = formData.get('result_date');
                            const game = formData.get('game');
                            const number = formData.get('result_number');
                            const submitName = formData.get('add_result_submit');
                            
                            console.log('Validation check:');
                            console.log('- Date:', date ? '✅' : '❌ MISSING');
                            console.log('- Game:', game ? '✅' : '❌ MISSING');
                            console.log('- Number:', number ? '✅' : '❌ MISSING');
                            console.log('- Submit name:', submitName ? '✅' : '❌ MISSING');
                            
                            if (!date || !game || !number) {
                                console.log('❌ FORM VALIDATION FAILED - Missing required fields');
                                alert('Please fill in all required fields');
                                e.preventDefault();
                                return false;
                            }
                            
                            console.log('✅ Form validation passed, submitting...');
                            console.log('🚀 SUBMITTING FORM TO SERVER NOW');
                            
                            // Show loading state
                            if (submitBtn) {
                                submitBtn.disabled = true;
                                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Adding...';
                            }
                            
                            // Explicitly submit the form
                            console.log('FORCING FORM SUBMISSION');
                            // DO NOT prevent default - allow normal submission
                        });
                        
                        // Add click handler to submit button for additional debugging
                        if (submitBtn) {
                            submitBtn.addEventListener('click', function(e) {
                                console.log('Add Result button clicked');
                                console.log('Button name:', this.name);
                                console.log('Button value:', this.value);
                                console.log('Button type:', this.type);
                                
                                // Ensure the button name/value gets included
                                const existingHidden = form.querySelector('input[name="add_result_submit"]');
                                if (!existingHidden) {
                                    const hiddenInput = document.createElement('input');
                                    hiddenInput.type = 'hidden';
                                    hiddenInput.name = 'add_result_submit';
                                    hiddenInput.value = '1';
                                    form.appendChild(hiddenInput);
                                    console.log('Added hidden input for add_result_submit');
                                } else {
                                    console.log('Hidden input already exists');
                                }
                                
                                // Validate form before submission
                                const dateField = form.querySelector('[name="result_date"]');
                                const gameField = form.querySelector('[name="game"]');
                                const numberField = form.querySelector('[name="result_number"]');
                                
                                if (!dateField?.value || !gameField?.value || !numberField?.value) {
                                    console.log('❌ Validation failed - missing fields');
                                    alert('Please fill in all required fields');
                                    e.preventDefault();
                                    return false;
                                }
                                
                                console.log('✅ Validation passed, triggering form submission');
                                
                                // Trigger form submission manually if needed
                                setTimeout(() => {
                                    console.log('Manual form submission triggered');
                                    form.submit();
                                }, 100);
                            });
                        }
                        
                    } else {
                        console.log('❌ Add result form NOT found');
                    }
                });
                </script>
            </div>
        </div>

        <!-- Today's Entries Section -->
        <div id="today_entries" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-calendar-day"></i>
                    Today's Entries (<?php echo count($today_entries); ?>)
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-user"></i> User</th>
                            <th><i class="fas fa-gamepad"></i> Game</th>
                            <th><i class="fas fa-tag"></i> Type</th>
                            <th><i class="fas fa-layer-group"></i> Subtype</th>
                            <th><i class="fas fa-hashtag"></i> Number</th>
                            <th><i class="fas fa-rupee-sign"></i> Amount</th>
                            <th><i class="fas fa-clock"></i> Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($today_entries)) { ?>
                            <?php foreach ($today_entries as $entry) { ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($entry['username']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['game']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['type']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['subtype']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['number']); ?></td>
                                    <td>₹<?php echo number_format($entry['amount']); ?></td>
                                    <td><?php echo date('H:i:s', strtotime($entry['entry_time'])); ?></td>
                                </tr>
                            <?php } ?>
                        <?php } else { ?>
                            <tr>
                                <td colspan="7" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No entries found for today
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- All Entries Section -->
        <div id="all_entries" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-list"></i>
                    All Entries (<?php echo count($all_entries); ?>)
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-user"></i> User</th>
                            <th><i class="fas fa-gamepad"></i> Game</th>
                            <th><i class="fas fa-tag"></i> Type</th>
                            <th><i class="fas fa-layer-group"></i> Subtype</th>
                            <th><i class="fas fa-hashtag"></i> Number</th>
                            <th><i class="fas fa-rupee-sign"></i> Amount</th>
                            <th><i class="fas fa-clock"></i> Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($all_entries)) { ?>
                            <?php foreach ($all_entries as $entry) { ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($entry['username']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['game']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['type']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['subtype']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['number']); ?></td>
                                    <td>₹<?php echo number_format($entry['amount']); ?></td>
                                    <td><?php echo date('M j, H:i', strtotime($entry['entry_time'])); ?></td>
                                </tr>
                            <?php } ?>
                        <?php } else { ?>
                            <tr>
                                <td colspan="7" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No entries found
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
        <!-- Copy Report Section -->
        <div id="generate_copy_report" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-copy"></i>
                    Copy Report - Today's Entries
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-user"></i> User</th>
                            <th><i class="fas fa-gamepad"></i> Game</th>
                            <th><i class="fas fa-tag"></i> Type</th>
                            <th><i class="fas fa-layer-group"></i> Subtype</th>
                            <th><i class="fas fa-hashtag"></i> Number</th>
                            <th><i class="fas fa-rupee-sign"></i> Amount</th>
                            <th><i class="fas fa-clock"></i> Time</th>
                            <th><i class="fas fa-cogs"></i> Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $copy_entries = [];
                        $res = mysqli_query($link, "SELECT * FROM entries_copy WHERE DATE(entry_time) = '$today'");
                        while ($row = mysqli_fetch_assoc($res)) {
                            $copy_entries[] = $row;
                        }
                        
                        if (!empty($copy_entries)) {
                            foreach ($copy_entries as $entry) { ?>
                                <tr>
                                    <form method="post" style="display: contents;">
                                        <input type="hidden" name="copy_id" value="<?php echo $entry['id']; ?>">
                                        <input type="hidden" name="show_section" value="generate_copy_report">\n                                        
                                        <td><?php echo htmlspecialchars($entry['username']); ?></td>
                                        <td><?php echo htmlspecialchars($entry['game']); ?></td>
                                        <td><?php echo htmlspecialchars($entry['type']); ?></td>
                                        <td><?php echo htmlspecialchars($entry['subtype']); ?></td>
                                        <td>
                                            <input type="text" name="number" value="<?php echo htmlspecialchars($entry['number']); ?>" 
                                                   class="form-input" style="width: 80px; padding: 0.5rem;">
                                        </td>
                                        <td>
                                            <input type="text" name="amount" value="<?php echo htmlspecialchars($entry['amount']); ?>" 
                                                   class="form-input" style="width: 80px; padding: 0.5rem;">
                                        </td>
                                        <td><?php echo date('H:i:s', strtotime($entry['entry_time'])); ?></td>
                                        <td>
                                            <div class="action-buttons">
                                                <button type="submit" name="update_copy_entry" class="btn btn-update">
                                                    <i class="fas fa-save"></i> Update
                                                </button>
                                                <button type="submit" name="delete_copy_entry" class="btn btn-delete" 
                                                        onclick="return confirm('Delete this entry?');">
                                                    <i class="fas fa-trash"></i> Delete
                                                </button>
                                            </div>
                                        </td>
                                    </form>
                                </tr>
                            <?php }
                        } else { ?>
                            <tr>
                                <td colspan="8" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No entries found for today. Generate report first.
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>

            <div class="flex justify-between items-center mt-2">
                <form method="post">
                    <button type="submit" name="generate_copy_report" value="1" class="btn btn-update">
                        <i class="fas fa-sync"></i>
                        Generate Report
                    </button>
                    <input type="hidden" name="show_section" value="generate_copy_report">
                </form>
                
                <?php if (!empty($copy_entries)) { ?>
                    <form method="post">
                        <button type="submit" name="share_whatsapp" class="btn btn-whatsapp">
                            <i class="fab fa-whatsapp"></i>
                            Send on WhatsApp
                        </button>
                    </form>
                <?php } ?>
            </div>
        </div>

        <!-- Shared Entries Section -->
        <div id="shared_entries" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-share-alt"></i>
                    Shared Entries from Database
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-hashtag"></i> ID</th>
                            <th><i class="fas fa-user"></i> User</th>
                            <th><i class="fas fa-gamepad"></i> Game</th>
                            <th><i class="fas fa-tag"></i> Type</th>
                            <th><i class="fas fa-layer-group"></i> Subtype</th>
                            <th><i class="fas fa-hashtag"></i> Number</th>
                            <th><i class="fas fa-rupee-sign"></i> Amount</th>
                            <th><i class="fas fa-clock"></i> Entry Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        // Create entries_shared table if it doesn't exist
                        $create_shared_table = "CREATE TABLE IF NOT EXISTS `entries_shared` (
                            `id` int(11) NOT NULL AUTO_INCREMENT,
                            `userid` int(11) NOT NULL,
                            `username` varchar(50) NOT NULL,
                            `game` varchar(50) NOT NULL,
                            `type` varchar(50) NOT NULL,
                            `subtype` varchar(50) NOT NULL,
                            `number` varchar(20) NOT NULL,
                            `amount` int(11) NOT NULL,
                            `entry_time` timestamp NOT NULL DEFAULT current_timestamp(),
                            PRIMARY KEY (`id`),
                            KEY `userid` (`userid`),
                            KEY `username` (`username`),
                            KEY `entry_time` (`entry_time`)
                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
                        
                        mysqli_query($link, $create_shared_table);
                        
                        // Get shared entries (show all, not just today's)
                        $shared_entries = [];
                        $res = mysqli_query($link, "SELECT * FROM entries_shared ORDER BY entry_time DESC LIMIT 100");
                        if ($res) {
                            while ($row = mysqli_fetch_assoc($res)) {
                                $shared_entries[] = $row;
                            }
                        }
                        
                        if (!empty($shared_entries)) {
                            foreach ($shared_entries as $entry) { ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($entry['id']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['username']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['game']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['type']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['subtype']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['number']); ?></td>
                                    <td>₹<?php echo htmlspecialchars($entry['amount']); ?></td>
                                    <td><?php echo date('Y-m-d H:i:s', strtotime($entry['entry_time'])); ?></td>
                                </tr>
                            <?php }
                        } else { ?>
                            <tr>
                                <td colspan="8" class="text-center" style="padding: 3rem; color: rgba(255,255,255,0.7);">
                                    <i class="fas fa-database" style="font-size: 3rem; margin-bottom: 1rem; display: block;"></i>
                                    <div style="font-size: 1.2rem; font-weight: 600;">No shared entries found</div>
                                    <div style="font-size: 0.9rem; margin-top: 0.5rem;">Shared entries will appear here when data is shared via WhatsApp</div>
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>

            <?php if (!empty($shared_entries)) { ?>
                <div class="flex justify-between items-center mt-2">
                    <div style="color: rgba(255,255,255,0.8); font-size: 0.9rem;">
                        <i class="fas fa-info-circle"></i>
                        Showing last 100 shared entries from the database
                    </div>
                    <div style="color: rgba(255,255,255,0.9); font-weight: 600;">
                        Total Shared Entries: <?php echo count($shared_entries); ?>
                    </div>
                </div>
            <?php } ?>
        </div>

        <!-- Today's Shared Entries Section -->
        <div id="today_shared_entries" class="content-section" style="display: none;">
            <h2>Today's Shared Entries</h2>
            <?php
            // Check if entries_shared table exists
            $check_table = mysqli_query($link, "SHOW TABLES LIKE 'entries_shared'");
            if ($check_table && mysqli_num_rows($check_table) > 0) {
                $today_shared_query = "SELECT es.*, c.name as contact_name 
                                     FROM entries_shared es 
                                     LEFT JOIN contacts c ON es.contact_id = c.id 
                                     WHERE DATE(es.entry_time) = '$today' 
                                     ORDER BY es.entry_time DESC";
                $today_shared_result = mysqli_query($link, $today_shared_query);
            } else {
                $today_shared_result = false;
            }
            ?>
            <div class="data-table">
                <table>
                    <thead>
                        <tr>
                            <th>Contact Name</th>
                            <th>Entry Text</th>
                            <th>Shared At</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($today_shared_result && mysqli_num_rows($today_shared_result) > 0): ?>
                            <?php while ($row = mysqli_fetch_assoc($today_shared_result)): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($row['contact_name'] ?? 'Unknown'); ?></td>
                                    <td><?php echo htmlspecialchars(substr($row['entry_text'], 0, 100)) . (strlen($row['entry_text']) > 100 ? '...' : ''); ?></td>
                                    <td><?php echo date('h:i A', strtotime($row['entry_time'])); ?></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="3" style="text-align: center; color: #666;">
                                    <?php if (!$check_table || mysqli_num_rows($check_table) == 0): ?>
                                        Entries shared table not found
                                    <?php else: ?>
                                        No shared entries today
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <button class="btn-back" onclick="showDashboard()">Back to Dashboard</button>
        </div>

        <!-- All Shared Entries Section -->
        <div id="all_shared_entries" class="content-section" style="display: none;">
            <h2>All Shared Entries</h2>
            <?php
            // Check if entries_shared table exists
            $check_table = mysqli_query($link, "SHOW TABLES LIKE 'entries_shared'");
            if ($check_table && mysqli_num_rows($check_table) > 0) {
                $all_shared_query = "SELECT es.*, c.name as contact_name 
                                   FROM entries_shared es 
                                   LEFT JOIN contacts c ON es.contact_id = c.id 
                                   ORDER BY es.entry_time DESC 
                                   LIMIT 100";
                $all_shared_result = mysqli_query($link, $all_shared_query);
            } else {
                $all_shared_result = false;
            }
            ?>
            <div class="data-table">
                <table>
                    <thead>
                        <tr>
                            <th>Contact Name</th>
                            <th>Entry Text</th>
                            <th>Shared Date</th>
                            <th>Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($all_shared_result && mysqli_num_rows($all_shared_result) > 0): ?>
                            <?php while ($row = mysqli_fetch_assoc($all_shared_result)): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($row['contact_name'] ?? 'Unknown'); ?></td>
                                    <td><?php echo htmlspecialchars(substr($row['entry_text'], 0, 100)) . (strlen($row['entry_text']) > 100 ? '...' : ''); ?></td>
                                    <td><?php echo date('M d, Y', strtotime($row['entry_time'])); ?></td>
                                    <td><?php echo date('h:i A', strtotime($row['entry_time'])); ?></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="4" style="text-align: center; color: #666;">
                                    <?php if (!$check_table || mysqli_num_rows($check_table) == 0): ?>
                                        Entries shared table not found
                                    <?php else: ?>
                                        No shared entries found
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <button class="btn-back" onclick="showDashboard()">Back to Dashboard</button>
        </div>

        <!-- Today's New Users Section -->
        <div id="today_new_users" class="content-section" style="display: none;">
            <h2>Today's New Registered Users</h2>
            <?php
            // Check if created_at column exists before querying
            $check_column = mysqli_query($link, "SHOW COLUMNS FROM users LIKE 'created_at'");
            if ($check_column && mysqli_num_rows($check_column) > 0) {
                $today_new_users_query = "SELECT * FROM users WHERE DATE(created_at) = '$today' ORDER BY created_at DESC";
                $today_new_users_result = mysqli_query($link, $today_new_users_query);
            } else {
                $today_new_users_result = false;
            }
            ?>
            <div class="data-table">
                <table>
                    <thead>
                        <tr>
                            <th>Username</th>
                            <th>Email</th>
                            <?php if ($check_column && mysqli_num_rows($check_column) > 0): ?>
                            <th>Registration Time</th>
                            <?php endif; ?>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if ($today_new_users_result && mysqli_num_rows($today_new_users_result) > 0): ?>
                            <?php while ($row = mysqli_fetch_assoc($today_new_users_result)): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($row['username']); ?></td>
                                    <td><?php echo htmlspecialchars($row['email']); ?></td>
                                    <?php if (isset($row['created_at'])): ?>
                                    <td><?php echo date('h:i A', strtotime($row['created_at'])); ?></td>
                                    <?php endif; ?>
                                    <td><span class="status-badge active">New</span></td>
                                </tr>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="<?php echo ($check_column && mysqli_num_rows($check_column) > 0) ? '4' : '3'; ?>" style="text-align: center; color: #666;">
                                    <?php if (!$check_column || mysqli_num_rows($check_column) == 0): ?>
                                        Users table doesn't have creation date column
                                    <?php else: ?>
                                        No new users registered today
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            <button class="btn-back" onclick="showDashboard()">Back to Dashboard</button>
        </div>

        <!-- Existing Sections Continue -->
        <div id="today_users" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-users"></i>
                    Currently Active Users (<?php echo count($today_users); ?>)
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-id-card"></i> User ID</th>
                            <th><i class="fas fa-user"></i> Username</th>
                            <th><i class="fas fa-phone"></i> User Number</th>
                            <th><i class="fas fa-calendar"></i> Registered Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        if (!empty($today_users)) {
                            $usernames = array_map(function($u) use ($link) {
                                return mysqli_real_escape_string($link, $u);
                            }, $today_users);
                            $usernames_str = "'" . implode("','", $usernames) . "'";
                            $res = mysqli_query($link, "SELECT id, username, usernumber, reg_date FROM users WHERE username IN ($usernames_str)");
                            while ($row = mysqli_fetch_assoc($res)) { ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($row['id']); ?></td>
                                    <td><?php echo htmlspecialchars($row['username']); ?></td>
                                    <td><?php echo htmlspecialchars($row['usernumber']); ?></td>
                                    <td><?php echo date('M j, Y', strtotime($row['reg_date'])); ?></td>
                                </tr>
                            <?php }
                        } else { ?>
                            <tr>
                                <td colspan="4" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No users currently active
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Total Users Section -->
        <div id="total_users" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-user-friends"></i>
                    All Registered Users (<?php echo $total_users; ?>)
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-id-card"></i> User ID</th>
                            <th><i class="fas fa-user"></i> Username</th>
                            <th><i class="fas fa-phone"></i> User Number</th>
                            <th><i class="fas fa-calendar"></i> Registered Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $res = mysqli_query($link, "SELECT id, username, usernumber, reg_date FROM users ORDER BY reg_date DESC");
                        if (mysqli_num_rows($res) > 0) {
                            while ($row = mysqli_fetch_assoc($res)) { ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($row['id']); ?></td>
                                    <td><?php echo htmlspecialchars($row['username']); ?></td>
                                    <td><?php echo htmlspecialchars($row['usernumber']); ?></td>
                                    <td><?php echo date('M j, Y', strtotime($row['reg_date'])); ?></td>
                                </tr>
                            <?php }
                        } else { ?>
                            <tr>
                                <td colspan="4" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No users found
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- View Shared Entries Section -->
        <div id="view_copy_report" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-share"></i>
                    Today's Shared Entries
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th><i class="fas fa-user"></i> User</th>
                            <th><i class="fas fa-gamepad"></i> Game</th>
                            <th><i class="fas fa-tag"></i> Type</th>
                            <th><i class="fas fa-layer-group"></i> Subtype</th>
                            <th><i class="fas fa-hashtag"></i> Number</th>
                            <th><i class="fas fa-rupee-sign"></i> Amount</th>
                            <th><i class="fas fa-clock"></i> Time</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $shared_entries = [];
                        $res = mysqli_query($link, "SELECT * FROM entries_shared WHERE DATE(entry_time) = '$today'");
                        while ($row = mysqli_fetch_assoc($res)) {
                            $shared_entries[] = $row;
                        }
                        
                        if (!empty($shared_entries)) {
                            foreach ($shared_entries as $entry) { ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($entry['username']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['game']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['type']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['subtype']); ?></td>
                                    <td><?php echo htmlspecialchars($entry['number']); ?></td>
                                    <td>₹<?php echo number_format($entry['amount']); ?></td>
                                    <td><?php echo date('H:i:s', strtotime($entry['entry_time'])); ?></td>
                                </tr>
                            <?php }
                        } else { ?>
                            <tr>
                                <td colspan="7" class="text-center">
                                    <i class="fas fa-info-circle"></i>
                                    No shared entries found for today
                                </td>
                            </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Create Blog Section -->
        <div id="create_blog" class="content-section">
            <div class="section-header">
                <h2 class="section-title" id="form-title">
                    <i class="fas fa-pen"></i>
                    Create New Blog Post
                </h2>
                <button class="back-btn" onclick="showSection('dashboard-overview')">
                    <i class="fas fa-arrow-left"></i>
                    Back to Dashboard
                </button>
            </div>

            <?php if (isset($_GET['msg'])) { ?>
                <?php if ($_GET['msg'] === 'blog_saved') { ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        Blog post saved successfully!
                    </div>
                <?php } elseif ($_GET['msg'] === 'blog_error') { ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i>
                        Error saving blog post. Please try again.
                    </div>
                <?php } ?>
            <?php } ?>

            <div class="blog-form-container">
                <form method="POST" action="admin-dashboard.php" enctype="multipart/form-data" class="blog-form" onsubmit="return submitBlogForm()">
                    <!-- Hidden fields -->
                    <input type="hidden" id="blog_id" name="blog_id" value="">
                    <input type="hidden" id="blog_slug" name="blog_slug" value="">
                    <input type="hidden" id="existing_image" name="existing_image" value="">
                    
                    <div class="form-grid">
                        <!-- Left Column -->
                        <div class="form-column">
                            <div class="form-group">
                                <label for="blog_title" class="form-label">
                                    <i class="fas fa-heading"></i> Blog Title *
                                </label>
                                <input type="text" id="blog_title" name="blog_title" class="form-input" required 
                                       placeholder="Enter an engaging blog title..." maxlength="500">
                            </div>

                            <div class="form-group">
                                <label for="blog_excerpt" class="form-label">
                                    <i class="fas fa-align-left"></i> Excerpt *
                                </label>
                                <textarea id="blog_excerpt" name="blog_excerpt" class="form-textarea" required 
                                          placeholder="Write a brief excerpt (2-3 sentences) that will appear in blog listings..." rows="3"></textarea>
                            </div>

                            <div class="form-group">
                                <label for="blog_content" class="form-label">
                                    <i class="fas fa-edit"></i> Content *
                                </label>
                                <textarea id="blog_content" name="blog_content" class="form-textarea-rich"></textarea>
                            </div>
                        </div>

                        <!-- Right Column -->
                        <div class="form-sidebar">
                            <div class="sidebar-section">
                                <h3 class="sidebar-title">
                                    <i class="fas fa-cogs"></i> Post Settings
                                </h3>
                                
                                <div class="form-group">
                                    <label for="blog_category" class="form-label">Category *</label>
                                    <select id="blog_category" name="blog_category" class="form-select" required>
                                        <option value="">Select Category</option>
                                        <option value="strategies">Strategies</option>
                                        <option value="market-analysis">Market Analysis</option>
                                        <option value="tips">Tips & Tricks</option>
                                        <option value="news">Latest News</option>
                                        <option value="tutorials">Tutorials</option>
                                        <option value="general">General</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label for="blog_status" class="form-label">Status *</label>
                                    <select id="blog_status" name="blog_status" class="form-select" required>
                                        <option value="draft">Draft</option>
                                        <option value="published">Published</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <label for="blog_tags" class="form-label">Tags</label>
                                    <input type="text" id="blog_tags" name="blog_tags" class="form-input" 
                                           placeholder="strategy, analysis, tips (comma separated)">
                                    <small class="form-help">Separate tags with commas</small>
                                </div>
                            </div>

                            <div class="sidebar-section">
                                <h3 class="sidebar-title">
                                    <i class="fas fa-image"></i> Featured Image
                                </h3>
                                
                                <div class="form-group">
                                    <label for="featured_image" class="form-label">Upload Image</label>
                                    <input type="file" id="featured_image" name="featured_image" class="form-file" 
                                           accept="image/jpeg,image/png,image/gif,image/webp">
                                    <small class="form-help">Max 5MB. JPEG, PNG, GIF, WebP supported.</small>
                                </div>

                                <!-- Current image preview for editing -->
                                <div id="current-image-preview" style="margin-bottom: 15px;"></div>

                                <div class="image-preview" id="imagePreview" style="display: none;">
                                    <img id="previewImg" src="" alt="Preview" style="width: 100%; border-radius: 8px;">
                                </div>
                            </div>

                            <div class="sidebar-section">
                                <h3 class="sidebar-title">
                                    <i class="fas fa-search"></i> SEO Settings
                                </h3>
                                
                                <div class="form-group">
                                    <label for="blog_meta_title" class="form-label">Meta Title</label>
                                    <input type="text" id="blog_meta_title" name="blog_meta_title" class="form-input" 
                                           placeholder="SEO title for search engines..." maxlength="60">
                                    <small class="form-help">Recommended: 50-60 characters</small>
                                </div>

                                <div class="form-group">
                                    <label for="blog_meta_description" class="form-label">Meta Description</label>
                                    <textarea id="blog_meta_description" name="blog_meta_description" class="form-textarea" 
                                              placeholder="Brief description for search engines..." rows="3" maxlength="160"></textarea>
                                    <small class="form-help">Recommended: 150-160 characters</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="form-actions">
                        <button type="submit" name="save_blog" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Blog Post
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="showSection('dashboard-overview')">
                            <i class="fas fa-times"></i> Cancel
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Blog Management Section -->
        <div id="blog_management" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-list"></i>
                    Blog Management
                </h2>
                <div class="header-actions">
                    <button class="btn btn-primary" onclick="showSection('create_blog')">
                        <i class="fas fa-plus"></i> New Post
                    </button>
                    <button class="back-btn" onclick="showSection('dashboard-overview')">
                        <i class="fas fa-arrow-left"></i>
                        Back to Dashboard
                    </button>
                </div>
            </div>

            <?php if (isset($_GET['msg'])) { ?>
                <?php if ($_GET['msg'] === 'blog_updated') { ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        Blog post updated successfully!
                    </div>
                <?php } elseif ($_GET['msg'] === 'blog_deleted') { ?>
                    <div class="alert alert-success">
                        <i class="fas fa-check-circle"></i>
                        Blog post deleted successfully!
                    </div>
                <?php } elseif ($_GET['msg'] === 'blog_error') { ?>
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle"></i>
                        Error processing blog post. Please try again.
                    </div>
                <?php } ?>
            <?php } ?>

            <div class="blog-management-container">
                <div class="blog-stats">
                    <div class="stat-card">
                        <div class="stat-icon"><i class="fas fa-file-alt"></i></div>
                        <div class="stat-info">
                            <div class="stat-number"><?php echo $blog_stats['total_blogs']; ?></div>
                            <div class="stat-label">Total Posts</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon"><i class="fas fa-eye"></i></div>
                        <div class="stat-info">
                            <div class="stat-number"><?php echo number_format($blog_stats['total_views']); ?></div>
                            <div class="stat-label">Total Views</div>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon"><i class="fas fa-heart"></i></div>
                        <div class="stat-info">
                            <div class="stat-number"><?php echo number_format($blog_stats['total_likes']); ?></div>
                            <div class="stat-label">Total Likes</div>
                        </div>
                    </div>
                </div>

                <div class="blog-list">
                    <?php if (empty($all_blogs)) { ?>
                        <div class="empty-state">
                            <i class="fas fa-pen-alt"></i>
                            <h3>No Blog Posts Yet</h3>
                            <p>Create your first blog post to get started!</p>
                            <button class="btn btn-primary" onclick="showSection('create_blog')">
                                <i class="fas fa-plus"></i> Create First Post
                            </button>
                        </div>
                    <?php } else { ?>
                        <div class="blog-grid">
                            <?php foreach ($all_blogs as $blog) { ?>
                                <div class="blog-item">
                                    <div class="blog-image">
                                        <?php if (!empty($blog['featured_image'])) { ?>
                                            <img src="../uploads/blog/<?php echo htmlspecialchars($blog['featured_image']); ?>" alt="<?php echo htmlspecialchars($blog['title']); ?>">
                                        <?php } else { ?>
                                            <div class="blog-placeholder">
                                                <i class="fas fa-image"></i>
                                            </div>
                                        <?php } ?>
                                        <div class="blog-status <?php echo htmlspecialchars($blog['status']); ?>">
                                            <?php echo ucfirst(htmlspecialchars($blog['status'])); ?>
                                        </div>
                                    </div>
                                    
                                    <div class="blog-content">
                                        <div class="blog-meta">
                                            <span class="blog-category"><?php echo ucfirst(str_replace('-', ' ', htmlspecialchars($blog['category']))); ?></span>
                                            <span class="blog-date"><?php echo date('M j, Y', strtotime($blog['created_at'])); ?></span>
                                        </div>
                                        
                                        <h3 class="blog-title"><?php echo htmlspecialchars($blog['title']); ?></h3>
                                        <p class="blog-excerpt"><?php echo htmlspecialchars(substr($blog['excerpt'], 0, 100)) . (strlen($blog['excerpt']) > 100 ? '...' : ''); ?></p>
                                        
                                        <div class="blog-stats">
                                            <span><i class="fas fa-eye"></i> <?php echo intval($blog['views']); ?></span>
                                            <span><i class="fas fa-heart"></i> <?php echo intval($blog['likes']); ?></span>
                                        </div>
                                        
                                        <div class="blog-actions">
                                            <button class="btn btn-sm btn-primary" onclick="editBlog(<?php echo intval($blog['id']); ?>)">
                                                <i class="fas fa-edit"></i> Edit
                                            </button>
                                            <a href="../blog/<?php echo htmlspecialchars($blog['slug']); ?>" target="_blank" class="btn btn-sm btn-secondary">
                                                <i class="fas fa-external-link-alt"></i> View
                                            </a>
                                            <button class="btn btn-sm btn-danger" onclick="deleteBlogPost(<?php echo intval($blog['id']); ?>)">
                                                <i class="fas fa-trash"></i> Delete
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            <?php } ?>
                        </div>
                    <?php } ?>
                </div>
            </div>
        </div>

        <!-- Contact Management Section -->
        <div id="contact_management" class="content-section">
            <div class="section-header">
                <h2 class="section-title">
                    <i class="fas fa-envelope"></i>
                    Contact Form Inquiries
                </h2>
                <div class="section-stats">
                    <div class="stat-item">
                        <span class="stat-label">Total</span>
                        <span class="stat-value"><?php echo $contact_stats['total_contacts']; ?></span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">New</span>
                        <span class="stat-value" style="color: #dc3545;"><?php echo $contact_stats['new_contacts']; ?></span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">Replied</span>
                        <span class="stat-value" style="color: #28a745;"><?php echo $contact_stats['replied_contacts']; ?></span>
                    </div>
                    <div class="stat-item">
                        <span class="stat-label">Today</span>
                        <span class="stat-value" style="color: #17a2b8;"><?php echo $contact_stats['today_contacts']; ?></span>
                    </div>
                </div>
            </div>
            
            <?php if (isset($_GET['msg'])): ?>
                <div class="alert alert-<?php echo ($_GET['msg'] === 'status_updated') ? 'success' : 'danger'; ?>">
                    <?php 
                    switch($_GET['msg']) {
                        case 'status_updated': echo '✅ Contact status updated successfully!'; break;
                        case 'status_error': echo '❌ Error updating contact status. Please try again.'; break;
                    }
                    ?>
                </div>
            <?php endif; ?>

            <div class="table-container">
                <table class="admin-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Phone</th>
                            <th>Subject</th>
                            <th>Message</th>
                            <th>Contact Method</th>
                            <th>Status</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        // Get all contacts with pagination
                        $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
                        $per_page = 20;
                        $offset = ($page - 1) * $per_page;
                        
                        $contacts_query = "SELECT * FROM contacts ORDER BY created_at DESC LIMIT $per_page OFFSET $offset";
                        $contacts_result = mysqli_query($link, $contacts_query);
                        
                        if ($contacts_result && mysqli_num_rows($contacts_result) > 0):
                            while ($contact = mysqli_fetch_assoc($contacts_result)):
                        ?>
                        <tr class="<?php echo ($contact['status'] === 'new') ? 'new-inquiry' : ''; ?>">
                            <td><?php echo $contact['id']; ?></td>
                            <td>
                                <strong><?php echo htmlspecialchars($contact['name']); ?></strong>
                            </td>
                            <td>
                                <a href="tel:<?php echo htmlspecialchars($contact['phone']); ?>">
                                    <?php echo htmlspecialchars($contact['phone']); ?>
                                </a>
                            </td>
                            <td><?php echo htmlspecialchars($contact['subject']); ?></td>
                            <td>
                                <div class="message-preview" title="<?php echo htmlspecialchars($contact['message']); ?>">
                                    <?php echo htmlspecialchars(substr($contact['message'], 0, 100)) . (strlen($contact['message']) > 100 ? '...' : ''); ?>
                                </div>
                            </td>
                            <td>
                                <span class="contact-method-badge contact-method-<?php echo $contact['preferred_contact']; ?>">
                                    <?php 
                                    switch($contact['preferred_contact']) {
                                        case 'phone': echo '📞 Phone'; break;
                                        case 'whatsapp': echo '💬 WhatsApp'; break;
                                        default: echo ucfirst($contact['preferred_contact']);
                                    }
                                    ?>
                                </span>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $contact['status']; ?>">
                                    <?php echo ucfirst($contact['status']); ?>
                                </span>
                            </td>
                            <td><?php echo date('M j, Y H:i', strtotime($contact['created_at'])); ?></td>
                        </tr>
                        <?php 
                            endwhile;
                        else:
                        ?>
                        <tr>
                            <td colspan="8" style="text-align: center; padding: 40px; color: #666;">
                                <i class="fas fa-inbox" style="font-size: 48px; margin-bottom: 15px; opacity: 0.5;"></i>
                                <div>No contact inquiries found.</div>
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            <?php
            $total_result = mysqli_query($link, "SELECT COUNT(*) as total FROM contacts");
            $total_row = mysqli_fetch_assoc($total_result);
            $total_contacts = $total_row['total'];
            $total_pages = ceil($total_contacts / $per_page);
            
            if ($total_pages > 1):
            ?>
            <div class="pagination">
                <?php if ($page > 1): ?>
                <a href="?show_section=contact_management&page=<?php echo $page - 1; ?>" class="page-btn">← Previous</a>
                <?php endif; ?>
                
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                <a href="?show_section=contact_management&page=<?php echo $i; ?>" 
                   class="page-btn <?php echo ($i === $page) ? 'active' : ''; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>
                
                <?php if ($page < $total_pages): ?>
                <a href="?show_section=contact_management&page=<?php echo $page + 1; ?>" class="page-btn">Next →</a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </div>
    </main>

    <script>
        // Functions are already defined in head - just add initialization code here
            document.getElementById('blog_category').value = '';
            document.getElementById('blog_status').value = 'draft';
            document.getElementById('blog_tags').value = '';
            document.getElementById('blog_meta_title').value = '';
            document.getElementById('blog_meta_description').value = '';
            
            // Reset CKEditor
            if (window.blogEditor) {
                window.blogEditor.setData('');
            }
            
            // Clear image previews
            const currentImagePreview = document.getElementById('current-image-preview');
            if (currentImagePreview) {
                currentImagePreview.innerHTML = '';
            }
            
            const imagePreview = document.getElementById('imagePreview');
            if (imagePreview) {
                imagePreview.style.display = 'none';
            }
            
            // Reset file input
            const fileInput = document.getElementById('featured_image');
            if (fileInput) {
                fileInput.value = '';
            }
        }

        // Auto-refresh functionality
        let autoRefresh = false;
        function toggleAutoRefresh() {
            autoRefresh = !autoRefresh;
            if (autoRefresh) {
                setInterval(() => {
                    if (document.getElementById('dashboard-overview').classList.contains('active')) {
                        location.reload();
                    }
                }, 30000); // Refresh every 30 seconds
            }
        }

        // Handle URL parameters for showing specific sections
        document.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const sectionToShow = urlParams.get('show_section');
            
            if (sectionToShow) {
                showSection(sectionToShow);
            }

            // Set today's date as default for date inputs
            const dateInputs = document.querySelectorAll('input[type="date"]');
            const today = new Date().toISOString().split('T')[0];
            dateInputs.forEach(input => {
                if (!input.value) {
                    input.value = today;
                }
            });
        });

        // Simple form validation
        function validateForm(form) {
            const requiredFields = form.querySelectorAll('[required]');
            let valid = true;
            
            requiredFields.forEach(field => {
                if (!field.value.trim()) {
                    field.style.borderColor = '#ef4444';
                    valid = false;
                } else {
                    field.style.borderColor = '';
                }
            });
            
            return valid;
        }

        // Add simple form submission handlers
        document.addEventListener('DOMContentLoaded', function() {
            // Form submission handling - EXCLUDE add-result-form as it has its own handler
            const forms = document.querySelectorAll('form:not(#add-result-form)');
            forms.forEach(form => {
                form.addEventListener('submit', function(e) {
                    console.log('General form submitted:', this.id || 'unnamed form');
                    
                    // Skip add-result form - it has its own dedicated handler
                    if (this.id === 'add-result-form' || this.querySelector('button[name="add_result_submit"]')) {
                        console.log('Skipping add-result form - has dedicated handler');
                        return true;
                    }
                    
                    // Skip validation for blog forms - they have their own submitBlogForm validation
                    if (this.querySelector('button[name="save_blog"]') || this.querySelector('button[name="update_blog"]') || this.classList.contains('blog-form')) {
                        console.log('Blog form - allowing submission (has own validation)');
                        return true;
                    }
                    
                    // For other forms, use basic validation
                    if (!validateForm(this)) {
                        e.preventDefault();
                        alert('Please fill in all required fields.');
                        return false;
                    }
                });
            });
        });

        // Submit button handling - simplified
        const submitButtons = document.querySelectorAll('button[type="submit"]');
        submitButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                console.log('Submit button clicked:', this.name);
                
                // For add result button, just log and allow normal submission
                if (this.name === 'add_result_submit') {
                    const form = this.closest('form');
                    if (form && !form.checkValidity()) {
                        console.log('Form validation failed - browser will show errors');
                        return; // Let browser handle validation
                    }
                    console.log('Add result button - form valid, submitting...');
                    // Don't prevent default - let form submit normally
                }
            });
        });
            
            // Refresh button
            const refreshBtn = document.querySelector('.refresh-btn');
            if (refreshBtn) {
                refreshBtn.addEventListener('click', function() {
                    location.reload();
                });
            }
        });

        // Auto-hide alerts after 5 seconds
        document.addEventListener('DOMContentLoaded', function() {
            document.querySelectorAll('.alert').forEach(alert => {
                setTimeout(() => {
                    alert.style.opacity = '0';
                    setTimeout(() => {
                        alert.remove();
                    }, 300);
                }, 5000);
            });
        });
        document.querySelectorAll('.alert').forEach(alert => {
            setTimeout(() => {
                alert.style.opacity = '0';
                setTimeout(() => {
                    alert.remove();
                }, 300);
            }, 5000);
        });

        // Blog Management Functions
        function toggleBlogForm() {
            const form = document.getElementById('blog-create-form');
            const management = document.getElementById('blog-management');
            
            if (form.style.display === 'none' || !form.style.display) {
                form.style.display = 'block';
                management.style.display = 'none';
                document.getElementById('form-title').textContent = 'Create New Blog Post';
                clearBlogForm();
            } else {
                form.style.display = 'none';
                management.style.display = 'block';
            }
        }

        function clearBlogForm() {
            document.getElementById('blog_title').value = '';
            document.getElementById('blog_category').value = '';
            document.getElementById('blog_excerpt').value = '';
            document.getElementById('blog_meta_title').value = '';
            document.getElementById('blog_meta_description').value = '';
            document.getElementById('blog_tags').value = '';
            document.getElementById('blog_status').value = 'draft';
            document.getElementById('featured_image').value = '';
            
            // Clear CKEditor content
            if (typeof blogEditor !== 'undefined' && blogEditor) {
                blogEditor.setData('');
            } else {
                document.getElementById('blog_content').value = '';
            }
            
            // Clear edit mode
            document.getElementById('blog_id').value = '';
            document.getElementById('form-title').textContent = 'Create New Blog Post';
            
            // Reset submit button for create mode
            const submitBtn = document.querySelector('button[name="update_blog"], button[name="save_blog"]');
            if (submitBtn) {
                submitBtn.name = 'save_blog';
                submitBtn.innerHTML = '<i class="fas fa-save"></i> Save Blog Post';
                console.log('Submit button reset to create mode');
            }
        }

        // Blog management functions already defined in early script block
        // Auto-generate meta title from blog title
        const titleInput = document.getElementById('blog_title');
        const metaTitleInput = document.getElementById('blog_meta_title');
        
        if (titleInput && metaTitleInput) {
            titleInput.addEventListener('input', function() {
                if (!metaTitleInput.value || metaTitleInput.value === titleInput.dataset.oldValue) {
                    metaTitleInput.value = this.value;
                    titleInput.dataset.oldValue = this.value;
                }
            });
        }

        // Character counter for meta description
        function updateCharCount() {
            const textarea = document.getElementById('blog_meta_description');
            const counter = document.getElementById('meta-desc-count');
            const current = textarea.value.length;
            const max = 160;
            
            counter.textContent = `${current}/${max}`;
            counter.style.color = current > max ? '#e74c3c' : current > 140 ? '#f39c12' : '#27ae60';
        }

        // Image preview
        function previewImage(input) {
            const preview = document.getElementById('image-preview');
            const file = input.files[0];
            
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.innerHTML = `<img src="${e.target.result}" alt="Preview" style="max-width: 200px; max-height: 200px; border-radius: 8px; object-fit: cover;">`;
                };
                reader.readAsDataURL(file);
            } else {
                preview.innerHTML = '<div style="width: 200px; height: 150px; background: #f8f9fa; border: 2px dashed #dee2e6; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: #adb5bd;"><i class="fas fa-image" style="font-size: 32px;"></i></div>';
            }
        }

        // Form validation and submission
        function validateBlogForm() {
            console.log('validateBlogForm() called');
            
            const title = document.getElementById('blog_title').value.trim();
            const excerpt = document.getElementById('blog_excerpt').value.trim();
            const category = document.getElementById('blog_category').value.trim();
            let content = '';
            
            console.log('Title:', title);
            console.log('Excerpt:', excerpt);
            console.log('Category:', category);
            
            // Get content from CKEditor or fallback textarea
            if (typeof blogEditor !== 'undefined' && blogEditor) {
                content = blogEditor.getData().trim();
                // Remove empty HTML tags
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = content;
                const textContent = tempDiv.textContent || tempDiv.innerText || '';
                content = textContent.trim();
                console.log('Content from CKEditor (text only):', content.length + ' characters');
            } else {
                content = document.getElementById('blog_content').value.trim();
                console.log('Content from textarea:', content.length + ' characters');
            }
            
            // Validate all required fields
            if (!title) {
                alert('Please enter a blog title.');
                console.log('Validation failed: No title');
                document.getElementById('blog_title').focus();
                return false;
            }
            
            if (!excerpt) {
                alert('Please enter a blog excerpt.');
                console.log('Validation failed: No excerpt');
                document.getElementById('blog_excerpt').focus();
                return false;
            }
            
            if (!content || content.length < 10) {
                alert('Please enter substantial blog content (at least 10 characters).');
                console.log('Validation failed: No content or too short');
                if (typeof blogEditor !== 'undefined' && blogEditor) {
                    blogEditor.editing.view.focus();
                } else {
                    document.getElementById('blog_content').focus();
                }
                return false;
            }
            
            if (!category) {
                alert('Please select a category.');
                console.log('Validation failed: No category');
                document.getElementById('blog_category').focus();
                return false;
            }
            
            console.log('Blog form validation successful');
            return true;
        }

        // Submit blog form with CKEditor content
        function submitBlogForm() {
            console.log('submitBlogForm() called');
            
            try {
                // Determine if we're in edit mode
                const blogId = document.getElementById('blog_id').value;
                const isEditMode = blogId && blogId.trim() !== '';
                console.log('Edit mode:', isEditMode, 'Blog ID:', blogId);
                
                // Validate form first
                if (!validateBlogForm()) {
                    console.log('Blog form validation failed');
                    return false;
                }
                
                console.log('Blog form validation passed');

                // Ensure CKEditor content is saved to textarea before submission
                if (typeof blogEditor !== 'undefined' && blogEditor) {
                    const editorContent = blogEditor.getData();
                    document.getElementById('blog_content').value = editorContent;
                    console.log('Blog content captured:', editorContent.length + ' characters');
                } else {
                    console.log('No CKEditor found, using textarea content directly');
                }

                // Auto-generate slug from title if empty
                const title = document.getElementById('blog_title').value.trim();
                const slugField = document.getElementById('blog_slug');
                if (slugField && !slugField.value.trim()) {
                    const slug = title.toLowerCase()
                        .replace(/[^a-z0-9\s-]/g, '')
                        .replace(/\s+/g, '-')
                        .replace(/-+/g, '-')
                        .replace(/^-+|-+$/g, '');
                    slugField.value = slug;
                    console.log('Generated slug:', slug);
                }

                // Ensure the submit button has the correct name attribute
                const submitBtn = document.querySelector('button[type="submit"]');
                if (submitBtn) {
                    if (isEditMode) {
                        submitBtn.name = 'update_blog';
                        submitBtn.value = '1';
                        console.log('Set button name to update_blog for edit mode');
                    } else {
                        submitBtn.name = 'save_blog';
                        submitBtn.value = '1';
                        console.log('Set button name to save_blog for create mode');
                    }
                    
                    // Show loading state
                    submitBtn.disabled = true;
                    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ' + (isEditMode ? 'Updating...' : 'Saving...');
                }

                console.log('Form submission proceeding for', isEditMode ? 'UPDATE' : 'CREATE');
                return true;
                
            } catch (error) {
                console.error('Error in submitBlogForm:', error);
                alert('An error occurred while preparing the form. Please try again.');
                return false;
            }
        }

        // Make functions available globally for form access
        window.validateBlogForm = validateBlogForm;
        window.submitBlogForm = submitBlogForm;

        // Debug function to test form functionality
        function testBlogForm() {
            console.log('=== BLOG FORM DEBUG TEST ===');
            console.log('Form element:', document.querySelector('.blog-form'));
            console.log('Title field:', document.getElementById('blog_title'));
            console.log('Excerpt field:', document.getElementById('blog_excerpt'));
            console.log('Content field:', document.getElementById('blog_content'));
            console.log('Category field:', document.getElementById('blog_category'));
            console.log('Submit button:', document.querySelector('button[name="save_blog"]'));
            console.log('CKEditor instance:', typeof blogEditor !== 'undefined' ? blogEditor : 'Not loaded');
            
            // Test if functions exist
            console.log('validateBlogForm function:', typeof validateBlogForm);
            console.log('submitBlogForm function:', typeof submitBlogForm);
            console.log('===========================');
        }

        // Make test function available globally for console debugging
        window.testBlogForm = testBlogForm;
    </script>

    <!-- CKEditor 5 - Free Rich Text Editor -->
    <script src="https://cdn.ckeditor.com/ckeditor5/40.0.0/classic/ckeditor.js"></script>
    <script>
        // Initialize CKEditor 5 Rich Text Editor
        let blogEditor;
        document.addEventListener('DOMContentLoaded', function() {
            if (document.getElementById('blog_content')) {
                ClassicEditor
                    .create(document.querySelector('#blog_content'), {
                        toolbar: [
                            'heading', '|',
                            'bold', 'italic', '|',
                            'link', '|',
                            'bulletedList', 'numberedList', '|',
                            'outdent', 'indent', '|',
                            'blockQuote', 'insertTable', '|',
                            'undo', 'redo'
                        ],
                        language: 'en',
                        table: {
                            contentToolbar: [
                                'tableColumn',
                                'tableRow',
                                'mergeTableCells'
                            ]
                        },
                        heading: {
                            options: [
                                { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' },
                                { model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' },
                                { model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' },
                                { model: 'heading3', view: 'h3', title: 'Heading 3', class: 'ck-heading_heading3' }
                            ]
                        },
                        link: {
                            decorators: {
                                openInNewTab: {
                                    mode: 'manual',
                                    label: 'Open in a new tab',
                                    attributes: {
                                        target: '_blank',
                                        rel: 'noopener noreferrer'
                                    }
                                }
                            }
                        }
                    })
                    .then(editor => {
                        blogEditor = editor;
                        window.blogEditor = editor; // Make globally accessible
                        
                        // Update the hidden textarea when content changes
                        editor.model.document.on('change:data', () => {
                            document.getElementById('blog_content').value = editor.getData();
                        });
                        
                        // Add form submit handler to ensure content is captured
                        const blogForm = document.querySelector('.blog-form');
                        if (blogForm) {
                            blogForm.addEventListener('submit', function(e) {
                                // Ensure CKEditor content is captured before submission
                                document.getElementById('blog_content').value = editor.getData();
                                console.log('Form submit: CKEditor content captured');
                            });
                        }
                        
                        console.log('CKEditor initialized successfully');
                        
                        // Style the editor
                        editor.editing.view.change(writer => {
                            writer.setStyle('min-height', '400px', editor.editing.view.document.getRoot());
                            writer.setStyle('font-family', '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, sans-serif', editor.editing.view.document.getRoot());
                        });
                    })
                    .catch(error => {
                        console.error('Error initializing CKEditor:', error);
                        // Fallback to regular textarea if editor fails
                        document.getElementById('blog_content').style.display = 'block';
                        document.getElementById('blog_content').style.minHeight = '400px';
                    });
            }
        });

        // Enhanced Form Functionality
        document.addEventListener('DOMContentLoaded', function() {
            // Add real-time form validation
            const formInputs = document.querySelectorAll('.form-input, .form-select');
            const submitBtn = document.querySelector('.submit-btn');
            
            formInputs.forEach(input => {
                // Add focus/blur effects
                input.addEventListener('focus', function() {
                    this.parentElement.classList.add('focused');
                });
                
                input.addEventListener('blur', function() {
                    this.parentElement.classList.remove('focused');
                    validateField(this);
                });
                
                // Real-time validation
                input.addEventListener('input', function() {
                    validateField(this);
                    checkFormValidity();
                });
            });
            
            // Field validation function
            function validateField(field) {
                const formGroup = field.parentElement;
                formGroup.classList.remove('has-error', 'has-success');
                
                if (field.value.trim() === '' && field.hasAttribute('required')) {
                    formGroup.classList.add('has-error');
                    return false;
                } else if (field.value.trim() !== '') {
                    formGroup.classList.add('has-success');
                    return true;
                }
                return true;
            }
            
            // Check overall form validity
            function checkFormValidity() {
                const requiredFields = document.querySelectorAll('.form-input[required], .form-select[required]');
                let allValid = true;
                
                requiredFields.forEach(field => {
                    if (field.value.trim() === '') {
                        allValid = false;
                    }
                });
                
                if (submitBtn) {
                    // Always keep button clickable for add result form
                    submitBtn.disabled = false;
                    submitBtn.style.pointerEvents = 'auto';
                    submitBtn.style.opacity = '1';
                    
                    if (allValid) {
                        submitBtn.classList.remove('disabled');
                    } else {
                        submitBtn.classList.add('needs-validation');
                    }
                }
            }
            
            // Enhanced submit button with loading state
            if (submitBtn) {
                submitBtn.addEventListener('click', function(e) {
                    if (!this.disabled) {
                        this.classList.add('loading');
                        this.disabled = true;
                        
                        // Re-enable after form submission or timeout
                        setTimeout(() => {
                            this.classList.remove('loading');
                            this.disabled = false;
                        }, 3000);
                    }
                });
            }
            
            // Simplified form animations - ensure all fields are visible
            const formGroups = document.querySelectorAll('.form-group');
            formGroups.forEach((group, index) => {
                // Ensure immediate visibility for Add Result form
                if (group.closest('#add-result-form')) {
                    group.style.opacity = '1';
                    group.style.transform = 'translateY(0)';
                    group.style.transition = 'all 0.3s ease';
                    console.log('Made form group visible:', group);
                } else {
                    // Original animation for other forms
                    group.style.opacity = '0';
                    group.style.transform = 'translateY(20px)';
                    
                    setTimeout(() => {
                        group.style.transition = 'all 0.6s cubic-bezier(0.4, 0, 0.2, 1)';
                        group.style.opacity = '1';
                        group.style.transform = 'translateY(0)';
                    }, 100 * index);
                }
            });
            
            // Simple game dropdown setup
            const gameSelect = document.getElementById('game');
            if (gameSelect) {
                console.log('Game select found');
                
                // Ensure options are present
                if (gameSelect.options.length <= 1) {
                    console.log('Adding game options');
                    const games = [
                        {value: 'disawar', text: 'Disawar'},
                        {value: 'dl_bazaar', text: 'DL Bazaar'},
                        {value: 'shri_ganesh', text: 'Shri Ganesh'},
                        {value: 'faridabad', text: 'Faridabad'},
                        {value: 'ghaziabad', text: 'Ghaziabad'},
                        {value: 'radhey_radhey', text: 'Radhey Radhey'},
                        {value: 'gali', text: 'Gali'}
                    ];
                    
                    games.forEach(game => {
                        const option = document.createElement('option');
                        option.value = game.value;
                        option.textContent = game.text;
                        gameSelect.appendChild(option);
                    });
                }
            }
            
            // Enhanced form functionality with auto-reset after success
            document.addEventListener('DOMContentLoaded', function() {
                // Check URL parameters to auto-show section and reset form
                const urlParams = new URLSearchParams(window.location.search);
                const showSection = urlParams.get('show_section');
                const msg = urlParams.get('msg');
                
                // Auto-show section based on URL parameter
                if (showSection) {
                    console.log(`Auto-showing section: ${showSection}`);
                    window.showSection(showSection);
                    
                    // Handle section-specific logic
                    if (showSection === 'add_result') {
                        // If there was a success message, reset the form
                        if (msg === 'success') {
                            console.log('Success detected - resetting add result form');
                            const form = document.getElementById('add-result-form');
                            if (form) {
                                // Reset form fields
                                form.reset();
                                // Set date to today
                                const dateField = form.querySelector('[name="result_date"]');
                                if (dateField) {
                                    dateField.value = '<?php echo date('Y-m-d'); ?>';
                                }
                                console.log('Add result form reset successfully');
                            }
                        }
                    } else if (showSection === 'blog_management') {
                        // Handle blog management messages
                        if (msg === 'blog_updated') {
                            console.log('Blog updated successfully - staying in blog management');
                        } else if (msg === 'blog_deleted') {
                            console.log('Blog deleted successfully - staying in blog management');
                        } else if (msg === 'blog_saved') {
                            console.log('Blog saved successfully - staying in blog management');
                        }
                    } else if (showSection === 'create_blog') {
                        // Handle create blog messages
                        if (msg === 'blog_saved') {
                            console.log('Blog saved successfully - staying in create blog');
                        } else if (msg === 'blog_error') {
                            console.log('Blog error - staying in create blog for retry');
                        }
                    }
                }
                
                console.log('Section auto-show logic completed');
            });
        });
    </script>

    <style>
        /* Additional form state styles */
        .form-group.focused .form-label {
            color: #60a5fa !important;
            text-shadow: 0 0 15px rgba(96, 165, 250, 0.6);
        }
        
        .form-group.has-success .form-input,
        .form-group.has-success .form-select {
            border-color: rgba(34, 197, 94, 0.6) !important;
            box-shadow: 0 0 0 2px rgba(34, 197, 94, 0.1), 0 8px 25px rgba(0, 0, 0, 0.15) !important;
        }
        
        .form-group.has-error .form-input,
        .form-group.has-error .form-select {
            border-color: rgba(239, 68, 68, 0.6) !important;
            box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.1), 0 8px 25px rgba(0, 0, 0, 0.15) !important;
        }
        
        .submit-btn.disabled,
        .submit-btn.needs-validation {
            pointer-events: auto !important;
            cursor: pointer !important;
            opacity: 1 !important;
        }

        /* Override any conflicting button styles and ensure full functionality */
        button[type="submit"].submit-btn {
            pointer-events: auto !important;
            cursor: pointer !important;
            opacity: 1 !important;
            position: relative !important;
            z-index: 10 !important;
        }

        /* Ensure Add Result button specifically is always clickable */
        button[name="add_result_submit"] {
            pointer-events: auto !important;
            cursor: pointer !important;
            opacity: 1 !important;
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 50%, #667eea 100%) !important;
            border: none !important;
            color: white !important;
            position: relative !important;
            z-index: 10 !important;
        }

        button[name="add_result_submit"]:hover {
            background: linear-gradient(135deg, #00f2fe 0%, #4facfe 50%, #667eea 100%) !important;
            transform: translateY(-2px) !important;
            box-shadow: 0 8px 25px rgba(79, 172, 254, 0.4) !important;
        }

        button[name="add_result_submit"]:active {
            transform: translateY(0px) !important;
        }

        /* Placeholder styling - enhanced by unified form styling above */
    </style>
</body>
</html>