<?php
session_start();

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id'])) {
    header('Location: auth-system/login.php');
    exit;
}

if ($_SESSION['user_role'] !== 'admin') {
    header('Location: shop.php');
    exit;
}

require_once 'config/db.php';

// Use $connection from config/db.php
$conn = $connection;

if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

// Create consultations table if it doesn't exist
$create_table_sql = "CREATE TABLE IF NOT EXISTS consultations (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT,
    name VARCHAR(100),
    first_name VARCHAR(100),
    last_name VARCHAR(100),
    email VARCHAR(255) NOT NULL,
    phone VARCHAR(20),
    address TEXT,
    consultation_type VARCHAR(50),
    preferred_date DATE,
    preferred_time TIME,
    project_description TEXT,
    budget_range VARCHAR(50),
    source VARCHAR(50),
    verification_token VARCHAR(255),
    token_expiry DATETIME,
    verification_status ENUM('pending', 'approved', 'declined', 'scheduled', 'completed', 'cancelled') DEFAULT 'pending',
    status ENUM('pending', 'approved', 'declined', 'scheduled', 'completed', 'cancelled') DEFAULT 'pending',
    verified_at DATETIME,
    scheduled_at DATETIME,
    notes TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_user_id (user_id),
    INDEX idx_status (status),
    INDEX idx_email (email),
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)";

$conn->query($create_table_sql);

// Create notifications table if it doesn't exist
$create_notifications_table = "CREATE TABLE IF NOT EXISTS notifications (
    id INT PRIMARY KEY AUTO_INCREMENT,
    admin_id INT NOT NULL,
    consultation_id INT,
    type ENUM('approval', 'decline', 'new_request') DEFAULT 'new_request',
    message TEXT NOT NULL,
    status ENUM('unread', 'read') DEFAULT 'unread',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_admin_id (admin_id),
    INDEX idx_status (status),
    INDEX idx_created_at (created_at),
    FOREIGN KEY (admin_id) REFERENCES users(id) ON DELETE CASCADE,
    FOREIGN KEY (consultation_id) REFERENCES consultations(id) ON DELETE SET NULL
)";

$conn->query($create_notifications_table);

// Create database backups table if it doesn't exist
$create_backups_table = "CREATE TABLE IF NOT EXISTS database_backups (
    id INT PRIMARY KEY AUTO_INCREMENT,
    admin_id INT NOT NULL,
    filename VARCHAR(255) NOT NULL,
    filepath VARCHAR(500),
    size BIGINT,
    status ENUM('pending', 'completed', 'failed') DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_admin_id (admin_id),
    INDEX idx_status (status),
    INDEX idx_created_at (created_at),
    FOREIGN KEY (admin_id) REFERENCES users(id) ON DELETE CASCADE
)";

$conn->query($create_backups_table);

// Create service bookings table if it doesn't exist
$create_service_bookings_table = "CREATE TABLE IF NOT EXISTS service_bookings (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT DEFAULT NULL,
    service_id INT NOT NULL,
    service_name VARCHAR(255) NOT NULL,
    customer_name VARCHAR(255) NOT NULL,
    customer_email VARCHAR(255) NOT NULL,
    customer_phone VARCHAR(50) NOT NULL,
    address TEXT NOT NULL,
    city VARCHAR(100) DEFAULT '',
    pincode VARCHAR(20) DEFAULT '',
    area_sqft INT DEFAULT 0,
    preferred_date DATE DEFAULT NULL,
    preferred_time VARCHAR(50) DEFAULT '',
    budget_range VARCHAR(100) DEFAULT '',
    notes TEXT DEFAULT NULL,
    status VARCHAR(50) DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_user_id (user_id),
    INDEX idx_service_id (service_id),
    INDEX idx_status (status)
)";

$conn->query($create_service_bookings_table);

$user_id = $_SESSION['user_id'];
$admin_profile = ['name' => (string)($_SESSION['user_name'] ?? 'Administrator'), 'email' => '', 'phone' => ''];
$adminProfileStmt = $conn->prepare("SELECT name, email, phone FROM users WHERE id = ? LIMIT 1");
if ($adminProfileStmt) {
    $adminProfileStmt->bind_param('i', $user_id);
    $adminProfileStmt->execute();
    $adminProfileRes = $adminProfileStmt->get_result();
    if ($adminProfileRes && $adminProfileRes->num_rows > 0) {
        $adminRow = $adminProfileRes->fetch_assoc();
        $admin_profile['name'] = (string)($adminRow['name'] ?? $admin_profile['name']);
        $admin_profile['email'] = (string)($adminRow['email'] ?? '');
        $admin_profile['phone'] = (string)($adminRow['phone'] ?? '');
    }
    $adminProfileStmt->close();
}

$system_settings = [
    'site_name' => 'FAREN Interior Design',
    'contact_email' => 'contact@faren.com',
    'support_phone' => '+1 (555) 123-4567',
    'maintenance_mode' => '0'
];
$settingsTableExists = $conn->query("SHOW TABLES LIKE 'site_settings'");
if ($settingsTableExists && $settingsTableExists->num_rows > 0) {
    $settingsResult = $conn->query("SELECT setting_key, setting_value FROM site_settings WHERE setting_key IN ('site_name','contact_email','support_phone','maintenance_mode')");
    if ($settingsResult) {
        while ($settingRow = $settingsResult->fetch_assoc()) {
            $k = (string)($settingRow['setting_key'] ?? '');
            if (array_key_exists($k, $system_settings)) {
                $system_settings[$k] = (string)($settingRow['setting_value'] ?? $system_settings[$k]);
            }
        }
    }
}

// Get recent orders (limited to 10 for dashboard view). Support optional search via GET `q` (order id, name, phone, email).
$search_q = isset($_GET['q']) ? trim($_GET['q']) : '';
$like = "%" . $search_q . "%";
$search_id = is_numeric($search_q) ? intval($search_q) : 0;

$sql = "SELECT o.*, LOWER(COALESCE(NULLIF(TRIM(o.status), ''), 'pending')) AS order_status, u.name as customer_name, u.email as customer_email FROM orders o JOIN users u ON o.user_id = u.id";
if ($search_q !== '') {
    $sql .= " WHERE (o.id = ? OR u.name LIKE ? OR o.phone LIKE ? OR u.email LIKE ? )";
}
$sql .= " ORDER BY o.created_at DESC LIMIT 10";

$orders_query = $conn->prepare($sql);
if ($search_q !== '') {
    // bind: int, string, string, string
    $orders_query->bind_param('isss', $search_id, $like, $like, $like);
}
$orders_query->execute();
$orders_result = $orders_query->get_result();

// Get all consultations
$consultations_query = "
    SELECT id, first_name, last_name, email, phone, consultation_type, preferred_date, budget_range, status, created_at
    FROM consultations
    ORDER BY created_at DESC
    LIMIT 10
";

$consultations_result = $conn->query($consultations_query);
if (!$consultations_result) {
    $consultations_result = new stdClass();
    $consultations_result->num_rows = 0;
}

// Get recent service bookings
$service_bookings_query = "
    SELECT id, user_id, service_id, service_name, customer_name, customer_email, customer_phone,
           address, city, pincode, area_sqft, preferred_date, preferred_time, budget_range,
           notes, status, created_at, updated_at
    FROM service_bookings
    ORDER BY created_at DESC
    LIMIT 20
";

$service_bookings_result = $conn->query($service_bookings_query);
if (!$service_bookings_result) {
    error_log("Service bookings query failed: " . $conn->error);
    $service_bookings_result = $conn->query("SELECT id, user_id, service_id, service_name, customer_name, customer_email, customer_phone, address, city, pincode, area_sqft, preferred_date, preferred_time, budget_range, notes, status, created_at, updated_at FROM service_bookings WHERE 1=0");
}

// Get all users (excluding password field) - LIMIT to recent 20
$users_query = "
    SELECT id, name, email, phone, role, created_at
    FROM users
    ORDER BY created_at DESC
    LIMIT 20
";

$users_result = $conn->query($users_query);
if (!$users_result) {
    error_log("Users query failed: " . $conn->error);
    // Return empty result set
    $users_result = $conn->query("SELECT id, name, email, phone, role, created_at FROM users WHERE 1=0");
}

// Get statistics
$stats_query = $conn->query("
    SELECT 
        COUNT(*) as total_orders,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_orders,
        SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) as delivered_orders,
        0 as total_revenue
    FROM orders
");
$stats = $stats_query ? $stats_query->fetch_assoc() : ['total_orders' => 0, 'pending_orders' => 0, 'delivered_orders' => 0, 'total_revenue' => 0];

// Get consultations count
$consultations_count_query = $conn->query("SELECT COUNT(*) as total_consultations FROM consultations");
$consultations_count = $consultations_count_query ? $consultations_count_query->fetch_assoc() : ['total_consultations' => 0];

// Get service bookings count
$service_bookings_count_query = $conn->query("
    SELECT
        COUNT(*) AS total_bookings,
        SUM(CASE WHEN LOWER(COALESCE(NULLIF(TRIM(status), ''), 'pending')) = 'pending' THEN 1 ELSE 0 END) AS pending_bookings,
        SUM(CASE WHEN LOWER(COALESCE(NULLIF(TRIM(status), ''), 'pending')) IN ('confirmed', 'approved', 'scheduled') THEN 1 ELSE 0 END) AS scheduled_bookings,
        SUM(CASE WHEN LOWER(COALESCE(NULLIF(TRIM(status), ''), 'pending')) = 'completed' THEN 1 ELSE 0 END) AS completed_bookings
    FROM service_bookings
");
$service_bookings_count = $service_bookings_count_query ? $service_bookings_count_query->fetch_assoc() : [
    'total_bookings' => 0,
    'pending_bookings' => 0,
    'scheduled_bookings' => 0,
    'completed_bookings' => 0
];

// Get newsletter statistics
$newsletter_stats = [
    'confirmed_subscribers' => 0,
    'pending_subscribers' => 0,
    'sent_campaigns' => 0,
    'draft_campaigns' => 0,
    'total_subscribers' => 0
];

// Check if newsletter tables exist and get stats
$check_table = $conn->query("SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'newsletter_subscribers'");
if ($check_table && $check_table->num_rows > 0) {
    $stats_sql = "SELECT 
        (SELECT COUNT(*) FROM newsletter_subscribers WHERE status = 'confirmed') as confirmed_subscribers,
        (SELECT COUNT(*) FROM newsletter_subscribers WHERE status = 'pending') as pending_subscribers,
        (SELECT COUNT(*) FROM newsletter_campaigns WHERE status = 'sent') as sent_campaigns,
        (SELECT COUNT(*) FROM newsletter_campaigns WHERE status = 'draft') as draft_campaigns,
        (SELECT COUNT(*) FROM newsletter_subscribers) as total_subscribers";
    
    $newsletter_stats_result = $conn->query($stats_sql);
    if ($newsletter_stats_result) {
        $newsletter_stats = $newsletter_stats_result->fetch_assoc();
    }
}

// Extract product definitions from shop.php (simple static parse of data- attributes)
$products = [];
$shop_file = __DIR__ . '/shop.php';
if (file_exists($shop_file)) {
    $shop_content = @file_get_contents($shop_file);
    if ($shop_content !== false) {
        // find all data-* attribute occurrences, then deduplicate by product id
        preg_match_all('/data-product-id=["\'](\d+)["\'][^>]*data-name=["\']([^"\']+)["\'][^>]*data-price=["\']([^"\']+)["\'][^>]*data-image=["\']([^"\']+)["\']/', $shop_content, $matches, PREG_SET_ORDER);
        $map = [];
        foreach ($matches as $m) {
            $id = $m[1];
            // keep the last occurrence for each id (overwrites duplicates)
            $map[$id] = [
                'id' => $id,
                'name' => html_entity_decode($m[2]),
                'price' => $m[3],
                'image' => $m[4]
            ];
        }
        // convert map to indexed array
        $products = array_values($map);
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Admin Dashboard - Interior Design</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawesome.min.css">
    <link rel="stylesheet" href="assets/css/style.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-color: #8b6f47;
            --primary-dark: #6b5738;
            --secondary-color: #d4a574;
            --accent-gold: #c9a876;
            --bg-light: #f9f7f4;
            --bg-white: #ffffff;
            --text-dark: #2c2c2c;
            --text-light: #666666;
            --border-color: #e8e3dd;
            --shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.08);
            --shadow-md: 0 4px 16px rgba(0, 0, 0, 0.12);
            --shadow-lg: 0 12px 32px rgba(0, 0, 0, 0.15);
        }

        body {
            background: linear-gradient(135deg, var(--bg-light) 0%, #faf8f5) fixed;
            font-family: 'Segoe UI', 'Poppins', sans-serif;
            color: var(--text-dark);
            line-height: 1.6;
        }

        .admin-wrapper {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .admin-header {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            color: white;
            padding: 24px 0;
            box-shadow: var(--shadow-lg);
            margin-top: 260px;
            position: relative;
            z-index: 99;
        }

        .admin-header::after {
            content: '';
            position: absolute;
            bottom: -2px;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(90deg, var(--secondary-color), transparent);
        }

        .admin-header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 40px;
            gap: 20px;
        }

        .admin-header h1 {
            font-size: 28px;
            font-weight: 700;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 15px;
            letter-spacing: -0.5px;
        }

        .admin-header-right {
            display: flex;
            align-items: center;
            gap: 24px;
            flex-wrap: wrap;
            justify-content: flex-end;
        }

        .admin-user-info {
            text-align: right;
            font-size: 14px;
        }

        .admin-user-info p {
            margin: 0;
            opacity: 0.95;
        }

        .admin-user-name {
            font-weight: 600;
            font-size: 15px;
            margin-bottom: 4px;
        }

        .logout-btn {
            background: var(--secondary-color);
            color: white;
            border: 2px solid var(--secondary-color);
            padding: 10px 24px;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            display: inline-block;
            font-size: 14px;
            white-space: nowrap;
        }

        .logout-btn:hover {
            background: var(--primary-color);
            border-color: var(--primary-color);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .logout-btn:active {
            transform: translateY(0);
        }

        /* Notification Bell Styles */
        .notification-bell-container {
            position: relative;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .notification-bell {
            background: none;
            border: none;
            color: white;
            font-size: 20px;
            cursor: pointer;
            position: relative;
            padding: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            transition: all 0.3s ease;
        }

        .notification-bell:hover {
            background: rgba(255, 255, 255, 0.1);
            transform: scale(1.1);
        }

        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #ef4444;
            color: white;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: 700;
            box-shadow: 0 2px 8px rgba(239, 68, 68, 0.4);
            animation: pulse-badge 2s infinite;
        }

        @keyframes pulse-badge {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }

        .notification-panel {
            position: absolute;
            top: calc(100% + 10px);
            right: 0;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.15);
            width: 380px;
            max-height: 500px;
            z-index: 1000;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            animation: slideIn 0.3s ease;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .notification-header {
            background: linear-gradient(135deg, #8b6f47 0%, #6b5738 100%);
            color: white;
            padding: 16px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #e0e0e0;
        }

        .notification-header h3 {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
        }

        .mark-all-btn {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 6px 12px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s ease;
        }

        .mark-all-btn:hover {
            background: rgba(255, 255, 255, 0.3);
        }

        .notification-list {
            overflow-y: auto;
            flex: 1;
            max-height: 420px;
        }

        .notification-item {
            padding: 12px 16px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            gap: 12px;
            transition: all 0.2s ease;
            cursor: pointer;
        }

        .notification-item:hover {
            background: #f9f7f4;
        }

        .notification-item.unread {
            background: #fef3c7;
            border-left: 4px solid #d4a574;
        }

        .notification-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
            font-size: 18px;
        }

        .notification-icon.approval {
            background: #d4edda;
            color: #155724;
        }

        .notification-icon.decline {
            background: #f8d7da;
            color: #721c24;
        }

        .notification-icon.new {
            background: #cce5ff;
            color: #004085;
        }

        .notification-content {
            flex: 1;
            min-width: 0;
        }

        .notification-message {
            font-size: 14px;
            color: #333;
            font-weight: 500;
            margin-bottom: 4px;
        }

        .notification-time {
            font-size: 12px;
            color: #999;
        }

        .admin-main {
            flex: 1;
            padding: 40px 24px;
            max-width: 100%;
            margin: 0 auto;
            width: 100%;
        }

        .section-title {
            font-size: 24px;
            font-weight: 700;
            color: var(--text-dark);
            margin-bottom: 28px;
            padding-bottom: 16px;
            border-bottom: 3px solid var(--secondary-color);
            display: flex;
            align-items: center;
            gap: 12px;
            letter-spacing: -0.5px;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
            gap: 24px;
            margin-bottom: 48px;
        }

        .stat-card {
            background: var(--bg-white);
            padding: 28px;
            border-radius: 12px;
            box-shadow: var(--shadow-sm);
            border-left: 4px solid var(--secondary-color);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            right: 0;
            width: 100px;
            height: 100px;
            background: linear-gradient(135deg, var(--secondary-color), transparent);
            opacity: 0.05;
            border-radius: 50%;
            transform: translate(30%, -30%);
        }

        .stat-card:hover {
            transform: translateY(-8px);
            box-shadow: var(--shadow-lg);
            border-left-color: var(--primary-color);
        }

        .stat-value {
            font-size: 40px;
            font-weight: 700;
            color: var(--secondary-color);
            margin-bottom: 8px;
            display: block;
        }

        .stat-label {
            color: var(--text-light);
            font-size: 13px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .dashboard-section {
            margin-bottom: 48px;
        }

        .table-wrapper {
            background: var(--bg-white);
            border-radius: 12px;
            box-shadow: var(--shadow-sm);
            overflow: hidden;
            border: 1px solid var(--border-color);
            transition: all 0.3s ease;
        }

        .table-wrapper:hover {
            box-shadow: var(--shadow-md);
        }

        .table-wrapper .table-responsive {
            max-width: 100%;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }

        .admin-table {
            width: 100%;
            border-collapse: collapse;
        }

        .admin-table thead {
            background: linear-gradient(135deg, var(--bg-light), #f5f0eb);
            border-bottom: 2px solid var(--border-color);
        }

        .admin-table th {
            padding: 16px 20px;
            text-align: left;
            font-weight: 700;
            color: var(--text-dark);
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.8px;
            white-space: nowrap;
        }

        .admin-table td {
            padding: 14px 20px;
            border-bottom: 1px solid var(--border-color);
            font-size: 14px;
            color: var(--text-dark);
        }

        .admin-table tbody tr {
            transition: background 0.2s ease;
        }

        .admin-table tbody tr:hover {
            background: var(--bg-light);
        }

        .table-header {
            background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
            color: white;
            padding: 20px 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 20px;
        }

        .table-header h2 {
            font-size: 18px;
            font-weight: 700;
            margin: 0;
            flex: 1;
        }

        .filter-group {
            display: flex;
            gap: 15px;
            align-items: center;
            padding: 20px 30px;
            background: var(--bg-light);
            border-bottom: 1px solid var(--border-color);
            flex-wrap: wrap;
        }

        .filter-group label {
            font-weight: 600;
            color: var(--text-dark);
            margin: 0;
            font-size: 14px;
        }

        .filter-group select {
            padding: 10px 14px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: var(--bg-white);
            color: var(--text-dark);
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            font-weight: 500;
        }

        .filter-group select:focus {
            outline: none;
            border-color: var(--secondary-color);
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

        .table-responsive {
            overflow-x: auto;
        }

        .panels-container {
            display: flex;
            gap: 24px;
            align-items: flex-start;
        }

        .panel-nav {
            margin-top: -20px;
            width: 220px;
            min-width: 180px;
            background: transparent;
            padding: 8px 0;
            position: relative;
            z-index: 10;
            -webkit-overflow-scrolling: touch;
        }

        .panel-nav ul {
            list-style: none;
            padding: 0;
            margin: 0;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .panel-nav li {
            padding: 14px 18px;
            border-radius: 10px;
            cursor: pointer;
            color: var(--text-light);
            background: rgba(139, 111, 71, 0.05);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            font-weight: 500;
            font-size: 14px;
            border-left: 3px solid transparent;
        }

        .panel-nav li:hover {
            background: rgba(139, 111, 71, 0.12);
            color: var(--primary-color);
            border-left-color: var(--secondary-color);
            transform: translateX(4px);
        }

        .panel-nav li.active {
            background: linear-gradient(135deg, rgba(212, 165, 116, 0.15), rgba(212, 165, 116, 0.08));
            color: var(--primary-color);
            border-left-color: var(--secondary-color);
            font-weight: 600;
        }

        .panel-views {
            flex: 1;
            min-width: 0;
        }

        .panel-view {
            display: none;
        }

        .panel-view.active {
            display: block;
            animation: fadeInUp 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .config-wrap {
            width: 100%;
            max-width: 1100px;
            margin: 18px 0 0;
            display: grid;
            grid-template-columns: minmax(0, 1.6fr) minmax(280px, 1fr);
            gap: 18px;
            justify-content: start;
        }
        .config-card {
            background: #fff;
            border: 1px solid var(--border-color);
            border-radius: 12px;
            box-shadow: var(--shadow-sm);
            overflow: hidden;
        }
        .config-head {
            padding: 14px 18px;
            border-bottom: 1px solid #eee;
            font-size: 16px;
            font-weight: 700;
            color: var(--text-dark);
            background: linear-gradient(180deg, #fff, #fcfaf7);
        }
        .config-body {
            padding: 18px;
            display: grid;
            gap: 14px;
        }
        .config-field label {
            display: block;
            margin-bottom: 6px;
            font-weight: 600;
            color: #333;
            font-size: 13px;
        }
        .config-field input,
        .config-field select,
        .config-field textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            box-sizing: border-box;
            font-size: 14px;
            background: #fff;
        }
        .config-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 12px;
        }
        .config-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            flex-wrap: wrap;
        }
        .panel-view[data-panel="profile"] .dashboard-section,
        .panel-view[data-panel="settings"] .dashboard-section {
            width: 100%;
            max-width: none;
            margin-left: 0;
            margin-right: 0;
            padding-left: 0;
            padding-right: 0;
        }
        .panel-view[data-panel="profile"] .section-title,
        .panel-view[data-panel="settings"] .section-title,
        .panel-view[data-panel="profile"] .config-wrap,
        .panel-view[data-panel="settings"] .config-wrap {
            margin-left: 0 !important;
            margin-right: auto !important;
            justify-self: start;
        }
        @media (max-width: 980px) {
            .config-wrap { grid-template-columns: 1fr; }
        }
        @media (max-width: 768px) {
            .config-body { padding: 14px; }
            .config-row { grid-template-columns: 1fr; }
            .config-actions button { width: 100%; }
        }

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

        /* Override Bootstrap badge CSS variables to prevent conflicts */
        .badge {
            --bs-badge-color: inherit !important;
            --bs-badge-font-size: inherit !important;
        }

        /* Custom status tag - avoids Bootstrap .badge conflicts */
        .status-tag {
            display: inline-block !important;
            padding: 8px 16px;
            border-radius: 6px;
            font-weight: 600;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            white-space: nowrap;
            border: 1px solid transparent;
            line-height: 1.4;
            vertical-align: middle;
            visibility: visible !important;
            opacity: 1 !important;
        }

        .status-tag.tag-pending {
            background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
            color: #92400e;
            border-color: #fcd34d;
            box-shadow: 0 2px 8px rgba(253, 224, 71, 0.3);
        }

        .status-tag.tag-processing {
            background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
            color: #1e40af;
            border-color: #93c5fd;
            box-shadow: 0 2px 8px rgba(147, 197, 253, 0.3);
        }

        .status-tag.tag-shipped {
            background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
            color: #166534;
            border-color: #bbf7d0;
            box-shadow: 0 2px 8px rgba(187, 247, 208, 0.3);
        }

        .status-tag.tag-delivered {
            background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
            color: #065f46;
            border-color: #a7f3d0;
            box-shadow: 0 2px 8px rgba(167, 243, 208, 0.3);
        }

        .status-tag.tag-cancelled {
            background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
            color: #991b1b;
            border-color: #fecaca;
            box-shadow: 0 2px 8px rgba(254, 202, 202, 0.3);
        }

        .status-tag.tag-customer {
            background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
            color: #166534;
            border-color: #bbf7d0;
            box-shadow: 0 2px 8px rgba(187, 247, 208, 0.3);
        }

        .status-tag.tag-admin {
            background: linear-gradient(135deg, #e9d5ff 0%, #d8b4fe 100%);
            color: #6b21a8;
            border-color: #d8b4fe;
            box-shadow: 0 2px 8px rgba(216, 180, 254, 0.3);
        }

        .status-tag.tag-approved {
            background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
            color: #065f46;
            border-color: #a7f3d0;
            box-shadow: 0 2px 8px rgba(167, 243, 208, 0.3);
        }

        .status-tag.tag-declined {
            background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
            color: #991b1b;
            border-color: #fecaca;
            box-shadow: 0 2px 8px rgba(254, 202, 202, 0.3);
        }

        .status-tag.tag-scheduled {
            background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
            color: #1e40af;
            border-color: #93c5fd;
            box-shadow: 0 2px 8px rgba(147, 197, 253, 0.3);
        }

        .status-tag.tag-completed {
            background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%);
            color: #166534;
            border-color: #bbf7d0;
            box-shadow: 0 2px 8px rgba(187, 247, 208, 0.3);
        }

        .order-row {
            transition: all 0.3s ease;
            border-bottom: 1px solid #e5e7eb;
            background: #ffffff;
        }

        .order-row:hover {
            background: #f9fafb;
            box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
        }

        .order-row td {
            padding: 14px 12px;
            vertical-align: middle;
        }

        .action-buttons {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .btn-action {
            padding: 8px 14px;
            border-radius: 8px;
            text-decoration: none;
            font-size: 12px;
            font-weight: 600;
            border: none;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            text-transform: uppercase;
            letter-spacing: 0.5px;
            white-space: nowrap;
        }

        .btn-view {
            background: var(--secondary-color);
            color: white;
        }

        .btn-view:hover {
            background: var(--primary-color);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .btn-update {
            background: #3b82f6;
            color: white;
        }

        .btn-update:hover {
            background: #1d4ed8;
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

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

        .btn-delete:hover {
            background: #dc2626;
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .consultation-table td {
            vertical-align: top;
        }

        .consultation-table .action-buttons {
            min-width: 170px;
        }

        .booking-summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
            gap: 16px;
            padding: 18px 20px 10px;
        }

        .booking-summary-card {
            background: linear-gradient(135deg, #ffffff 0%, #f9f4ed 100%);
            border: 1px solid #ece3d6;
            border-radius: 16px;
            padding: 18px;
            box-shadow: 0 10px 24px rgba(139, 111, 71, 0.08);
        }

        .booking-summary-value {
            font-size: 28px;
            font-weight: 800;
            color: var(--primary-dark);
            line-height: 1;
            margin-bottom: 8px;
        }

        .booking-summary-label {
            font-size: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: #7b6a55;
            font-weight: 700;
        }

        .booking-cell-stack {
            display: flex;
            flex-direction: column;
            gap: 4px;
            min-width: 0;
        }

        .booking-cell-stack strong,
        .booking-cell-stack span,
        .booking-cell-stack small {
            overflow-wrap: anywhere;
        }

        .booking-meta-text {
            color: #6b7280;
            font-size: 12px;
        }

        .booking-notes-preview {
            max-width: 220px;
            color: #4b5563;
            white-space: normal;
            line-height: 1.5;
        }

        .booking-table .action-buttons {
            min-width: 150px;
        }

        .empty-state {
            text-align: center;
            padding: 60px 30px;
            color: var(--text-light);
        }

        .empty-state h3 {
            font-size: 20px;
            margin-bottom: 10px;
            color: var(--text-dark);
        }

        .empty-state p {
            margin: 0;
            font-size: 14px;
        }

        .admin-footer {
            background: var(--primary-dark);
            color: white;
            text-align: center;
            padding: 24px;
            margin-top: auto;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        .admin-footer p {
            margin: 0;
            font-size: 14px;
            opacity: 0.9;
        }

        /* ========== RESPONSIVE DESIGN ========== */

        /* TABLETS: 1024px and below */
        @media (max-width: 1024px) {
            .admin-header {
                margin-top: 120px;
            }

            .admin-header-content {
                padding: 0 30px;
                gap: 15px;
            }

            .admin-header h1 {
                font-size: 24px;
            }

            .admin-main {
                padding: 30px 20px;
                max-width: 100%;
            }

            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 20px;
                margin-bottom: 36px;
            }

            .stat-card {
                padding: 24px;
            }

            .stat-value {
                font-size: 36px;
            }

            .panels-container {
                gap: 20px;
            }

            .panel-nav {
                width: 180px;
                min-width: 160px;
            }

            .admin-table th,
            .admin-table td {
                padding: 12px 16px;
                font-size: 13px;
            }

            .table-header {
                padding: 18px 24px;
            }

            .filter-group {
                padding: 16px 24px;
            }
        }

        /* SMALL TABLETS & LARGE PHONES: 768px and below */
        @media (max-width: 768px) {
            .admin-header {
                padding: 18px 0;
                margin-top: 0;
            }

            .admin-header-content {
                flex-direction: column;
                padding: 0 20px;
                gap: 15px;
                align-items: stretch;
                text-align: center;
            }

            .admin-header h1 {
                font-size: 22px;
                justify-content: center;
            }

            .admin-header-right {
                flex-direction: column;
                width: 100%;
                align-items: center;
                gap: 12px;
            }

            .admin-user-info {
                text-align: center;
            }

            .logout-btn {
                width: 100%;
                padding: 12px 20px;
            }

            .admin-main {
                padding: 20px 16px;
            }

            .section-title {
                font-size: 20px;
                margin-bottom: 20px;
            }

            .stats-grid {
                grid-template-columns: 1fr;
                gap: 16px;
            }

            .stat-card {
                padding: 20px;
            }

            .stat-value {
                font-size: 32px;
            }

            .stat-label {
                font-size: 12px;
            }

            .panels-container {
                flex-direction: column;
                gap: 20px;
            }

            .panel-nav {
                width: 100%;
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
                padding-bottom: 8px;
            }

            .panel-nav ul {
                flex-direction: row;
                flex-wrap: nowrap;
                gap: 8px;
                padding: 8px;
                overflow-x: auto;
            }

            .panel-nav li {
                white-space: nowrap;
                flex: 0 0 auto;
                padding: 12px 14px;
                font-size: 13px;
            }

            .panel-views {
                padding: 0;
            }

            .table-responsive {
                font-size: 12px;
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            .admin-table {
                min-width: 100%;
            }

            .admin-table th,
            .admin-table td {
                padding: 10px 12px;
                font-size: 12px;
            }

            .table-header {
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;
                padding: 16px 20px;
            }

            .table-header h2 {
                font-size: 16px;
            }

            .table-header form {
                width: 100%;
                flex-wrap: wrap;
            }

            .table-header form input[type="search"] {
                width: 100% !important;
                min-width: 0;
                flex: 1 1 100%;
            }

            /* ===== CONSULTATION TABLE — MOBILE CARD LAYOUT ===== */
            .consultation-table {
                min-width: 100%;
            }

            .consultation-table thead {
                display: none;
            }

            .consultation-table tbody tr {
                display: block;
                background: #fff;
                border: 1px solid var(--border-color);
                border-radius: 10px;
                margin-bottom: 12px;
                padding: 14px 16px;
                box-shadow: 0 2px 6px rgba(0,0,0,0.04);
            }

            .consultation-table tbody td {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                width: 100%;
                border: none;
                padding: 6px 0;
                gap: 8px;
            }

            .consultation-table tbody td::before {
                content: attr(data-label);
                display: inline-block;
                font-size: 11px;
                font-weight: 700;
                color: var(--primary-dark);
                text-transform: uppercase;
                letter-spacing: 0.4px;
                min-width: 100px;
                flex-shrink: 0;
                padding-top: 2px;
            }

            .consultation-table tbody td[data-label="Actions"] {
                flex-direction: column;
                padding-top: 10px;
                border-top: 1px solid var(--border-color);
                margin-top: 6px;
            }

            .consultation-table tbody td[data-label="Actions"]::before {
                margin-bottom: 8px;
            }

            .consultation-table .action-buttons {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 8px;
                width: 100%;
            }

            .consultation-table .btn-action {
                text-align: center;
                padding: 10px 8px;
            }

            /* ===== ORDER TABLE — MOBILE CARD LAYOUT ===== */
            .order-table {
                min-width: 100%;
            }

            .order-table thead {
                display: none;
            }

            .order-table tbody tr {
                display: block;
                background: #fff;
                border: 1px solid var(--border-color);
                border-radius: 10px;
                margin-bottom: 12px;
                padding: 14px 16px;
                box-shadow: 0 2px 6px rgba(0,0,0,0.04);
            }

            .order-table tbody td {
                display: flex;
                justify-content: space-between;
                align-items: center;
                width: 100%;
                border: none;
                padding: 6px 0;
                gap: 8px;
            }

            .order-table tbody td::before {
                content: attr(data-label);
                display: inline-block;
                font-size: 11px;
                font-weight: 700;
                color: var(--primary-dark);
                text-transform: uppercase;
                letter-spacing: 0.4px;
                min-width: 80px;
                flex-shrink: 0;
            }

            .order-table tbody td[data-label="Actions"] {
                flex-direction: column;
                padding-top: 10px;
                border-top: 1px solid var(--border-color);
                margin-top: 6px;
            }

            .order-table tbody td[data-label="Actions"]::before {
                margin-bottom: 8px;
            }

            .order-table .action-buttons {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 8px;
                width: 100%;
            }

            .order-table .btn-action {
                text-align: center;
                padding: 10px 8px;
            }

            .booking-summary-grid {
                grid-template-columns: repeat(2, minmax(0, 1fr));
                padding: 16px 16px 0;
                gap: 12px;
            }

            .booking-summary-card {
                padding: 16px;
                border-radius: 14px;
            }

            .booking-summary-value {
                font-size: 22px;
            }

            .booking-table {
                min-width: 100%;
            }

            .booking-table thead {
                display: none;
            }

            .booking-table tbody tr {
                display: block;
                background: #fff;
                border: 1px solid var(--border-color);
                border-radius: 10px;
                margin-bottom: 12px;
                padding: 14px 16px;
                box-shadow: 0 2px 6px rgba(0,0,0,0.04);
            }

            .booking-table tbody td {
                display: flex;
                justify-content: space-between;
                align-items: flex-start;
                width: 100%;
                border: none;
                padding: 6px 0;
                gap: 10px;
            }

            .booking-table tbody td::before {
                content: attr(data-label);
                display: inline-block;
                font-size: 11px;
                font-weight: 700;
                color: var(--primary-dark);
                text-transform: uppercase;
                letter-spacing: 0.4px;
                min-width: 92px;
                flex-shrink: 0;
                padding-top: 2px;
            }

            .booking-table tbody td[data-label="Actions"] {
                flex-direction: column;
                padding-top: 10px;
                border-top: 1px solid var(--border-color);
                margin-top: 6px;
            }

            .booking-table tbody td[data-label="Actions"]::before {
                margin-bottom: 8px;
            }

            .booking-table .action-buttons {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 8px;
                width: 100%;
            }

            .booking-table .btn-action {
                text-align: center;
                padding: 10px 8px;
            }

            .booking-notes-preview {
                max-width: none;
            }

            /* ===== USERS TABLE — MOBILE CARD LAYOUT ===== */
            .admin-table:not(.order-table):not(.consultation-table) {
                min-width: 100%;
            }

            .admin-table:not(.order-table):not(.consultation-table) thead {
                display: none;
            }

            .admin-table:not(.order-table):not(.consultation-table) tbody tr {
                display: block;
                background: #fff;
                border: 1px solid var(--border-color);
                border-radius: 10px;
                margin-bottom: 12px;
                padding: 14px 16px;
                box-shadow: 0 2px 6px rgba(0,0,0,0.04);
            }

            .admin-table:not(.order-table):not(.consultation-table) tbody td {
                display: flex;
                justify-content: space-between;
                align-items: center;
                width: 100%;
                border: none;
                padding: 6px 0;
                gap: 8px;
            }

            .admin-table:not(.order-table):not(.consultation-table) tbody td::before {
                content: attr(data-label);
                display: inline-block;
                font-size: 11px;
                font-weight: 700;
                color: var(--primary-dark);
                text-transform: uppercase;
                letter-spacing: 0.4px;
                min-width: 90px;
                flex-shrink: 0;
            }

            .admin-table:not(.order-table):not(.consultation-table) tbody td:last-child {
                padding-top: 10px;
                border-top: 1px solid var(--border-color);
                margin-top: 6px;
                flex-direction: column;
            }

            .admin-table:not(.order-table):not(.consultation-table) .action-buttons {
                display: grid;
                grid-template-columns: 1fr 1fr;
                gap: 8px;
                width: 100%;
            }

            .admin-table:not(.order-table):not(.consultation-table) .btn-action {
                text-align: center;
                padding: 10px 8px;
            }

            /* Ensure status tags stay visible on mobile */
            .status-tag {
                font-size: 11px !important;
                padding: 6px 10px !important;
            }

            /* Responsive Service Form Styles */
            @media (max-width: 768px) {
                div[style*="grid-template-columns: 1fr 1fr"] {
                    grid-template-columns: 1fr !important;
                }

                div[style*="grid-template-columns: 1fr 1fr 1fr"] {
                    grid-template-columns: 1fr !important;
                }

                div[style*="grid-template-columns: 2fr 1fr 1fr auto"] {
                    grid-template-columns: 1fr !important;
                }

                div[style*="grid-template-columns: 1fr 2fr auto"] {
                    grid-template-columns: 1fr !important;
                }
            }

            @media (max-width: 480px) {
                div[style*="max-width: 900px"] {
                    max-width: 100% !important;
                    padding: 20px !important;
                }

                h3[style*="font-size: 28px"] {
                    font-size: 20px !important;
                }

                h4[style*="color: #1b8a67"] {
                    font-size: 16px !important;
                    margin-bottom: 15px !important;
                }

                input[style*="padding: 12px"],
                textarea[style*="padding: 12px"],
                select[style*="padding: 12px"] {
                    padding: 10px !important;
                    font-size: 13px !important;
                }

                input[style*="padding: 10px; border"],
                textarea[style*="padding: 10px; border"] {
                    padding: 8px !important;
                    font-size: 12px !important;
                }

                button[style*="padding: 12px 25px"] {
                    padding: 10px 15px !important;
                    font-size: 13px !important;
                }

                button[style*="padding: 10px 20px"] {
                    padding: 8px 12px !important;
                    font-size: 12px !important;
                    width: 100%;
                    margin-bottom: 8px;
                }
            }
            
            @media (max-width: 640px) {
                .filter-group {
                    flex-direction: column;
                    align-items: stretch;
                    gap: 12px;
                    padding: 14px 20px;
                }

                .filter-group select {
                    width: 100%;
                }

                .action-buttons {
                    gap: 6px;
                }

                .btn-action {
                    padding: 6px 10px;
                    font-size: 11px;
                    flex: 1;
                    text-align: center;
                }
            }

            /* SMALL PHONES: 480px and below */
            @media (max-width: 480px) {
            .admin-header {
                padding: 14px 0;
                margin-top: -50px !important;
            }

            .admin-header-content {
                padding: 0 16px;
                gap: 12px;
            }

            .admin-header h1 {
                font-size: 18px;
                gap: 10px;
            }

            .admin-user-name {
                font-size: 13px;
            }

            .admin-user-info p {
                font-size: 12px;
            }

            .logout-btn {
                padding: 10px 16px;
                font-size: 12px;
            }

            .admin-main {
                padding: 20px 12px;
            }

            .section-title {
                font-size: 18px;
                margin-bottom: 16px;
                padding-bottom: 12px;
            }

            .stats-grid {
                gap: 14px;
                margin-bottom: 24px;
            }

            .stat-card {
                padding: 16px;
            }

            .stat-value {
                font-size: 28px;
                margin-bottom: 6px;
            }

            .stat-label {
                font-size: 11px;
            }

            .panel-nav ul {
                gap: 6px;
                padding: 11px;
            }

            .panel-nav li {
                padding: 10px 12px;
                font-size: 12px;
                border-radius: 8px;
            }

            .dashboard-section {
                margin-bottom: 32px;
            }

            .table-header {
                padding: 14px 16px;
            }

            .table-header h2 {
                font-size: 15px;
            }

            .filter-group {
                padding: 12px 16px;
                gap: 10px;
            }

            .filter-group label {
                font-size: 12px;
            }

            .filter-group select {
                padding: 8px 10px;
                font-size: 12px;
            }

            .admin-table {
                min-width: 500px;
                font-size: 11px;
            }

            .admin-table th,
            .admin-table td {
                padding: 8px 10px;
                font-size: 11px;
            }

            .badge {
                padding: 4px 10px;
                font-size: 10px;
            }

            .action-buttons {
                gap: 4px;
                flex-direction: column;
            }

            .btn-action {
                padding: 6px 8px;
                font-size: 10px;
                width: 100%;
            }

            .empty-state {
                padding: 40px 20px;
            }

            .empty-state h3 {
                font-size: 16px;
            }

            .empty-state p {
                font-size: 12px;
            }

            .admin-footer {
                padding: 16px;
            }

            .admin-footer p {
                font-size: 12px;
            }
        }

        /* EXTRA SMALL: Below 360px */
        @media (max-width: 360px) {
            .admin-header {
                margin-top: 0 !important;
            }

            .admin-header h1 {
                font-size: 16px;
            }

            .admin-main {
                padding: 12px 10px;
            }

            .stats-grid {
                gap: 12px;
            }

            .stat-card {
                padding: 14px;
            }

            .stat-value {
                font-size: 24px;
            }

            .stat-label {
                font-size: 10px;
            }
        }

        /* User Details Modal Styles */
        body.user-modal-open,
        body.service-booking-modal-open {
            overflow: hidden;
        }

        .user-details-modal-overlay {
            position: fixed;
            inset: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(15, 23, 42, 0.72);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 10000;
            padding: clamp(12px, 3vw, 28px);
            overflow-y: auto;
            overscroll-behavior: contain;
            backdrop-filter: blur(4px);
            -webkit-backdrop-filter: blur(4px);
        }

        .user-details-modal {
            position: relative;
            background: #ffffff;
            border-radius: 20px;
            box-shadow: 0 24px 80px rgba(15, 23, 42, 0.28);
            width: min(100%, 760px);
            max-height: min(88vh, 920px);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            margin: auto;
            animation: slideUp 0.3s ease;
        }

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

        .user-modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 16px;
            padding: clamp(18px, 3vw, 26px);
            border-bottom: 1px solid #e5e7eb;
            background: linear-gradient(135deg, #fffaf4 0%, #ffffff 100%);
        }

        .user-modal-header h3 {
            margin: 0;
            font-size: clamp(20px, 2vw, 28px);
            color: #1f2937;
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .user-modal-header i {
            color: #d4a574;
            font-size: 24px;
        }

        .modal-close-btn {
            background: none;
            border: none;
            font-size: 24px;
            color: #666;
            cursor: pointer;
            transition: color 0.3s;
            padding: 0;
            width: 36px;
            height: 36px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
        }

        .modal-close-btn:hover {
            color: #333;
            background: #f5f5f5;
        }

        .user-modal-body {
            flex: 1;
            overflow-y: auto;
            padding: clamp(18px, 3vw, 28px);
            background: #ffffff;
        }

        .detail-section {
            margin-bottom: 28px;
        }

        .detail-section:last-child {
            margin-bottom: 0;
        }

        .detail-section h4 {
            font-size: 14px;
            font-weight: 700;
            color: #333;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin: 0 0 16px 0;
            padding-bottom: 12px;
            border-bottom: 2px solid #d4a574;
        }

        .detail-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 16px;
        }

        .detail-item {
            display: flex;
            flex-direction: column;
            gap: 6px;
            padding: 16px 18px;
            border: 1px solid #eceff3;
            border-radius: 14px;
            background: #f9fafb;
            min-width: 0;
        }

        .detail-item label {
            font-size: 12px;
            font-weight: 600;
            color: #999;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            margin-bottom: 6px;
        }

        .detail-item p {
            margin: 0;
            font-size: 15px;
            color: #333;
            line-height: 1.6;
            word-break: break-word;
            overflow-wrap: anywhere;
        }

        .user-modal-footer {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            padding: clamp(16px, 2.5vw, 24px);
            border-top: 1px solid #e5e7eb;
            background: #f8fafc;
            border-radius: 0 0 20px 20px;
            flex-wrap: wrap;
        }

        .user-modal-footer .btn-action {
            min-width: 132px;
            text-align: center;
        }

        @media (max-width: 600px) {
            .user-details-modal-overlay {
                padding: 12px;
                align-items: flex-end;
            }

            .user-details-modal {
                width: 100%;
                max-height: min(92vh, 100%);
                border-radius: 18px 18px 0 0;
            }

            .user-modal-header {
                padding: 16px;
            }

            .user-modal-header h3 {
                font-size: 22px;
            }

            .user-modal-body {
                padding: 16px;
            }

            .detail-grid {
                grid-template-columns: 1fr;
            }

            .user-modal-footer {
                padding: 16px;
            }

            .user-modal-footer .btn-action {
                width: 100%;
            }
        }

        /* ===== Modern Dashboard Redesign (Reference-aligned) ===== */
        body {
            background: #eef1f5 !important;
        }

        .admin-wrapper {
            min-height: 100vh;
            background: #eef1f5;
        }

        .admin-header {
            margin: 0 !important;
            background: transparent !important;
            box-shadow: none !important;
            padding: 18px 0 10px !important;
        }

        .admin-header::after {
            display: none !important;
        }

        .admin-header-content {
            background: #ffffff;
            border: 1px solid #e2e8f0;
            border-radius: 16px;
            padding: 18px 24px !important;
            box-shadow: 0 12px 30px rgba(16, 24, 40, 0.06);
        }

        .admin-title-group {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .admin-title-group h1 {
            margin: 0 !important;
            font-size: 40px;
            font-weight: 700;
            color: #1f2937;
        }

        .admin-title-group p {
            margin: 0;
            color: #6b7280;
            font-size: 16px;
        }

        .admin-user-info p {
            color: #4b5563;
        }

        .admin-avatar {
            width: 42px;
            height: 42px;
            border-radius: 999px;
            background: #5b6de8;
            color: #fff;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 18px;
        }

        .nav-toggle-btn {
            display: none;
            width: 42px;
            height: 42px;
            border: none;
            border-radius: 10px;
            background: #f3f4f6;
            color: #111827;
            cursor: pointer;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            flex: 0 0 auto;
        }

        @media (min-width: 993px) {
            .nav-toggle-btn {
                display: none !important;
            }
        }

        .admin-main {
            max-width: 100% !important;
            padding: 10px 24px 34px !important;
        }

        .panels-container {
            gap: 20px;
            align-items: stretch;
        }

        .panel-nav {
            margin-top: 0 !important;
            width: 260px !important;
            min-width: 260px !important;
            border-radius: 16px;
            padding: 18px 14px !important;
            background: linear-gradient(180deg, #8360c3 0%, #6a4cb2 36%, #5d4aa8 100%);
            box-shadow: 0 16px 34px rgba(79, 70, 229, 0.22);
            position: sticky !important;
            top: 12px;
            max-height: calc(100vh - 24px);
            overflow-y: auto;
        }

        .panel-nav li {
            color: rgba(255, 255, 255, 0.9) !important;
            background: transparent !important;
            border-left: 0 !important;
            border-radius: 10px !important;
            padding: 12px 14px !important;
            font-size: 16px !important;
            display: flex;
            align-items: center;
            gap: 10px;
            transform: none !important;
        }

        .panel-nav li::before {
            content: '\f0da';
            font-family: 'Font Awesome 6 Free';
            font-weight: 900;
            font-size: 11px;
            opacity: 0.85;
        }

        .panel-nav li:hover {
            color: #fff !important;
            background: rgba(255, 255, 255, 0.12) !important;
        }

        .panel-nav li.active {
            color: #fff !important;
            background: rgba(255, 255, 255, 0.22) !important;
            box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.18);
        }

        .panel-views {
            background: transparent;
        }

        .stats-grid {
            grid-template-columns: repeat(4, minmax(180px, 1fr)) !important;
            gap: 18px !important;
            margin-bottom: 28px !important;
        }

        .stat-card {
            border-left: 4px solid #5b6de8 !important;
            box-shadow: 0 10px 24px rgba(17, 24, 39, 0.08) !important;
            border-radius: 12px !important;
            min-height: 122px;
            padding: 22px 20px !important;
        }

        .stat-card:nth-child(2) { border-left-color: #10b981 !important; }
        .stat-card:nth-child(3) { border-left-color: #7c3aed !important; }
        .stat-card:nth-child(4) { border-left-color: #06b6d4 !important; }
        .stat-card:nth-child(5) { border-left-color: #22c55e !important; }

        .stat-card:hover {
            transform: translateY(-3px) !important;
        }

        .stat-value {
            font-size: 44px !important;
            color: #1f2937 !important;
            line-height: 1.1;
            margin-bottom: 8px !important;
        }

        .stat-label {
            font-size: 12px !important;
            color: #9ca3af !important;
        }

        .panel-nav-overlay {
            display: none;
        }

        body.nav-open {
            overflow: hidden;
        }

        @media (max-width: 1200px) {
            .stats-grid {
                grid-template-columns: repeat(3, minmax(170px, 1fr)) !important;
            }

            .admin-title-group h1 {
                font-size: 34px;
            }
        }

        @media (max-width: 992px) {
            .admin-header-content {
                padding: 14px 16px !important;
                flex-direction: row !important;
                align-items: center !important;
                text-align: left !important;
                justify-content: flex-start !important;
                gap: 10px !important;
            }

            .admin-title-group h1 {
                font-size: 28px;
            }

            .admin-title-group p {
                font-size: 14px;
            }

            .admin-header-right {
                flex-direction: row !important;
                width: auto !important;
                align-items: center !important;
                justify-content: flex-end !important;
                gap: 10px !important;
                margin-left: auto !important;
            }

            .logout-btn {
                width: auto !important;
                padding: 9px 12px !important;
            }

            .nav-toggle-btn {
                display: inline-flex;
            }

            .panel-nav {
                position: fixed !important;
                top: 0;
                left: -280px;
                bottom: 0;
                width: 260px !important;
                min-width: 260px !important;
                border-radius: 0;
                max-height: none;
                z-index: 1200;
                transition: left 0.25s ease;
                overflow: hidden;
            }

            .panel-nav ul {
                flex-direction: column !important;
                flex-wrap: nowrap !important;
                gap: 8px !important;
                overflow-y: auto !important;
                overflow-x: hidden !important;
                padding: 12px !important;
                height: 100%;
            }

            .panel-nav li {
                width: 100% !important;
                white-space: normal !important;
            }

            body.nav-open .panel-nav {
                left: 0;
            }

            .panel-nav-overlay {
                position: fixed;
                inset: 0;
                background: rgba(17, 24, 39, 0.45);
                z-index: 1100;
            }

            body.nav-open .panel-nav-overlay {
                display: block;
            }

            .panel-views {
                width: 100%;
            }

            .stats-grid {
                grid-template-columns: repeat(2, minmax(150px, 1fr)) !important;
            }
        }

        @media (max-width: 768px) {
            .admin-main {
                padding: 8px 12px 24px !important;
            }

            .admin-header-content {
                padding: 12px !important;
                gap: 8px !important;
            }

            .nav-toggle-btn {
                order: 1;
                margin-right: 2px;
            }

            .admin-title-group {
                order: 2;
                min-width: 0;
            }

            .admin-header-right {
                order: 3;
                margin-left: auto !important;
                gap: 6px !important;
            }

            .admin-header h1 {
                justify-content: flex-start !important;
                font-size: 20px !important;
            }

            .admin-title-group p {
                display: block !important;
                font-size: 12px !important;
            }

            .admin-header-right {
                gap: 8px !important;
            }

            .admin-user-info {
                display: none;
            }

            .stats-grid {
                grid-template-columns: 1fr !important;
                gap: 12px !important;
            }

            .section-title {
                font-size: 22px !important;
                margin-bottom: 18px !important;
            }
        }

    </style>
</head>
<body>
    
    <div class="admin-wrapper">
        <!-- Admin Header -->
        <div class="admin-header" style="margin:0px">
            <div class="admin-header-content">
                <button id="navToggleBtn" class="nav-toggle-btn" type="button" aria-label="Toggle Navigation">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="admin-title-group">
                    <h1>
                        <i class="fas fa-chart-pie"></i> Admin Dashboard
                    </h1>
                    <p>Welcome back, <?php echo htmlspecialchars($_SESSION['user_name'] ?? 'Administrator'); ?>!</p>
                </div>
                <div class="admin-header-right">
                    <!-- Notification Bell -->
                    <div class="notification-bell-container" style="position: relative; margin-right: 20px;">
                        <button id="notificationBell" class="notification-bell" title="Notifications">
                            <i class="fas fa-bell"></i>
                            <span id="notificationBadge" class="notification-badge" style="display: none;">0</span>
                        </button>
                        <div id="notificationPanel" class="notification-panel" style="display: none;">
                            <div class="notification-header">
                                <h3>Notifications</h3>
                                <button id="markAllReadBtn" class="mark-all-btn" title="Mark all as read">
                                    <i class="fas fa-check-double"></i>
                                </button>
                            </div>
                            <div id="notificationList" class="notification-list">
                                <p style="padding: 20px; text-align: center; color: #999;">Loading...</p>
                            </div>
                        </div>
                    </div>

                    <div class="admin-user-info">
                        <p class="admin-user-name"><?php echo htmlspecialchars($_SESSION['user_name']); ?></p>
                        <p>Administrator</p>
                    </div>
                    <div class="admin-avatar"><?php echo strtoupper(substr((string)($_SESSION['user_name'] ?? 'A'), 0, 1)); ?></div>
                    <a href="auth-system/logout.php" class="logout-btn">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>
        </div>
        <div id="panelNavOverlay" class="panel-nav-overlay"></div>

            <!-- Products Section removed (moved into panels below) -->

        <!-- Main Content -->
        <div class="admin-main">
            <!-- Panels: left nav and right views -->
            <div class="panels-container">
                <aside class="panel-nav" aria-label="Sections">
                    <ul>
                        <li data-target="overview" class="active" tabindex="0">Dashboard Overview</li>
                        <li data-target="orders" tabindex="0">Orders Management</li>
                        <li data-target="consultations" tabindex="0">Consultation Requests</li>
                        <li data-target="service-bookings" tabindex="0">Service Bookings</li>
                        <li data-target="users" tabindex="0">Users</li>
                        <li data-target="team" tabindex="0">Team Members</li>
                        <li data-target="services" tabindex="0">Services</li>
                        <li data-target="hero-slide" tabindex="0">Hero Slider</li>
                        <li data-target="profile" tabindex="0">Profile</li>
                        <li data-target="settings" tabindex="0">Settings</li>
                        <li data-target="products" tabindex="0">Products</li>
                        <li data-target="gallery" tabindex="0">Gallery</li>
                        <li data-target="projects" tabindex="0">Projects</li>
                        <li data-target="blog" tabindex="0">Blog</li>
                        <li data-target="newsletter" tabindex="0">Newsletter</li>
                    </ul>
                </aside>

                <div class="panel-views">
                    <div class="panel-view active" data-panel="overview">
                        <!-- Statistics Section -->
                        <h2 class="section-title">
                            <i class="fas fa-chart-bar"></i> Dashboard Overview
                        </h2>
                        <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-value"><?php echo $stats['total_orders'] ?? 0; ?></div>
                    <div class="stat-label">Total Orders</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $stats['pending_orders'] ?? 0; ?></div>
                    <div class="stat-label">Pending Orders</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $stats['delivered_orders'] ?? 0; ?></div>
                    <div class="stat-label">Delivered Orders</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value">&#8377;<?php echo number_format($stats['total_revenue'] ?? 0, 0); ?></div>
                    <div class="stat-label">Total Revenue</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $consultations_count['total_consultations'] ?? 0; ?></div>
                    <div class="stat-label">Total Consultations</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value"><?php echo $service_bookings_count['total_bookings'] ?? 0; ?></div>
                    <div class="stat-label">Service Bookings</div>
                </div>
            </div>

                    </div>

                    <div class="panel-view" data-panel="orders">
                        <!-- Orders Section -->
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-shopping-cart"></i> Orders Management
                            </h2>
            
                            <div class="table-wrapper">
                                <div class="table-header">
                                    <div>
                                        <h2>Recent Orders</h2>
                                        <p style="margin: 6px 0 0 0; font-size: 13px; opacity: 0.9;">Total: <strong><?php echo $stats['total_orders']; ?></strong> | Pending: <strong><?php echo $stats['pending_orders']; ?></strong> | Delivered: <strong><?php echo $stats['delivered_orders']; ?></strong></p>
                                    </div>
                                    <form method="get" action="" style="display:flex;align-items:center;gap:8px;">
                                        <input type="search" name="q" placeholder="Search by name, phone or order id" value="<?php echo htmlspecialchars($search_q ?? ''); ?>" style="padding:10px 14px;border:2px solid #fff;border-radius:8px;font-size:13px;width:250px;" />
                                        <button type="submit" class="btn-action btn-update" style="padding:10px 16px;font-size:12px;">Search</button>
                                        <?php if (!empty($search_q)): ?>
                                            <a href="admin-dashboard.php" class="btn-action btn-view" style="padding:10px 16px;font-size:12px;">Clear</a>
                                        <?php endif; ?>
                                    </form>
                                </div>
            
                                <div class="filter-group">
                                    <label for="statusFilter">Filter by Status:</label>
                                    <select id="statusFilter">
                                        <option value="">All Orders</option>
                                        <option value="pending">Pending</option>
                                        <option value="processing">Processing</option>
                                        <option value="shipped">Shipped</option>
                                        <option value="delivered">Delivered</option>
                                        <option value="cancelled">Cancelled</option>
                                    </select>
                                </div>
            
                                <?php if ($orders_result->num_rows === 0): ?>
                                    <div class="empty-state">
                                        <h3>No Orders Yet</h3>
                                        <p>No customer orders have been placed yet.</p>
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="admin-table order-table">
                                            <thead>
                                                <tr>
                                                    <th>Order ID</th>
                                                    <th>Customer</th>
                                                    <th>Email</th>
                                                    <th>Date</th>
                                                    <th>Total</th>
                                                    <th>Status</th>
                                                    <th>Payment</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($order = $orders_result->fetch_assoc()): ?>
                                                    <?php
                                                        $raw_status = (string)($order['order_status'] ?? ($order['status'] ?? ''));
                                                        $normalized_status = strtolower(trim($raw_status));
                                                        if ($normalized_status === '' || $normalized_status === 'null' || $normalized_status === '0') {
                                                            $normalized_status = 'pending';
                                                        }
                                                        $known_statuses = ['pending', 'processing', 'shipped', 'delivered', 'cancelled'];
                                                        $status = in_array($normalized_status, $known_statuses, true) ? $normalized_status : 'pending';
                                                        $labels = [
                                                            'pending' => 'Awaiting Action',
                                                            'processing' => 'Being Prepared',
                                                            'shipped' => 'In Transit',
                                                            'delivered' => 'Successfully Delivered',
                                                            'cancelled' => 'Order Cancelled'
                                                        ];
                                                        $title = ucfirst($status);
                                                        $label = $labels[$status] ?? 'Awaiting Action';
                                                    ?>
                                                    <tr class="order-row" data-status="<?php echo htmlspecialchars($status); ?>">
                                                        <td data-label="Order ID"><strong>#<?php echo htmlspecialchars($order['id']); ?></strong></td>
                                                        <td data-label="Customer"><?php echo htmlspecialchars($order['customer_name']); ?></td>
                                                        <td data-label="Email"><?php echo htmlspecialchars($order['customer_email']); ?></td>
                                                        <td data-label="Date"><?php echo date('M d, Y', strtotime($order['created_at'])); ?></td>
                                                        <td data-label="Total"><strong>Rs <?php echo number_format((float)($order['total'] ?? 0), 0); ?></strong></td>
                                                        <td data-label="Status">
                                                            <?php
                                                                $status_colors = [
                                                                    'pending' => ['bg' => '#fef3c7', 'color' => '#92400e', 'border' => '#fcd34d'],
                                                                    'processing' => ['bg' => '#dbeafe', 'color' => '#1e40af', 'border' => '#93c5fd'],
                                                                    'shipped' => ['bg' => '#dcfce7', 'color' => '#166534', 'border' => '#bbf7d0'],
                                                                    'delivered' => ['bg' => '#d1fae5', 'color' => '#065f46', 'border' => '#a7f3d0'],
                                                                    'cancelled' => ['bg' => '#fee2e2', 'color' => '#991b1b', 'border' => '#fecaca']
                                                                ];
                                                                $sc = $status_colors[$status] ?? $status_colors['pending'];
                                                            ?>
                                                            <span class="status-tag tag-<?php echo htmlspecialchars($status); ?>" style="background: <?php echo $sc['bg']; ?>; color: <?php echo $sc['color']; ?>; border: 2px solid <?php echo $sc['border']; ?>; padding: 8px 14px; border-radius: 20px; font-weight: 600; display: inline-block; font-size: 13px;">
                                                                <div style="font-weight: 700; font-size: 13px;"><?php echo htmlspecialchars($title); ?></div>
                                                                <div style="font-weight: 400; font-size: 10px; opacity: 0.8;"><?php echo htmlspecialchars($label); ?></div>
                                                            </span>
                                                        </td>
                                                        <td data-label="Payment"><?php echo ucfirst(str_replace('_', ' ', htmlspecialchars($order['payment_method'] ?? 'N/A'))); ?></td>
                                                        <td data-label="Actions">
                                                            <div class="action-buttons">
                                                                <a href="order-confirmation.php?order_id=<?php echo $order['id']; ?>" class="btn-action btn-view">View</a>
                                                                <button class="btn-action btn-update" onclick="updateStatus(<?php echo $order['id']; ?>)">Update</button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

            <div class="panel-view" data-panel="consultations">
                <!-- Consultations Section -->
                <div class="dashboard-section">
                    <h2 class="section-title">
                        <i class="fas fa-users"></i> Consultation Requests
                    </h2>

                    <div class="table-wrapper">
                        <div class="table-header">
                            <h2>Recent Consultations</h2>
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <label style="margin: 0; color: white; font-weight: 600; cursor: pointer; display: flex; align-items: center; gap: 8px;">
                                    <input type="checkbox" id="sendEmailToggle" checked style="width: 18px; height: 18px; cursor: pointer;">
                                    Send Email on Action
                                </label>
                            </div>
                        </div>

                        <?php if ($consultations_result->num_rows === 0): ?>
                            <div class="empty-state">
                                <h3>No Consultations</h3>
                                <p>No consultation requests have been submitted yet.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="admin-table consultation-table">
                                    <thead>
                                        <tr>
                                            <th>Name</th>
                                            <th>Email</th>
                                            <th>Phone</th>
                                            <th>Type</th>
                                            <th>Preferred Date</th>
                                            <th>Budget</th>
                                            <th>Status</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php while ($consultation = $consultations_result->fetch_assoc()): ?>
                                            <tr>
                                                <td data-label="Name"><strong><?php echo htmlspecialchars(($consultation['first_name'] ?? '') . ' ' . ($consultation['last_name'] ?? '')); ?></strong></td>
                                                <td data-label="Email"><?php echo htmlspecialchars($consultation['email'] ?? 'N/A'); ?></td>
                                                <td data-label="Phone"><?php echo htmlspecialchars($consultation['phone'] ?? 'N/A'); ?></td>
                                                <td data-label="Type"><?php echo ucfirst(str_replace('_', ' ', htmlspecialchars($consultation['consultation_type'] ?? 'N/A'))); ?></td>
                                                <td data-label="Preferred Date"><?php echo isset($consultation['preferred_date']) ? date('M d, Y', strtotime($consultation['preferred_date'])) : 'N/A'; ?></td>
                                                <td data-label="Budget"><?php echo htmlspecialchars($consultation['budget_range'] ?? 'N/A'); ?></td>
                                                <td data-label="Status">
                                                    <?php
                                                        $raw_status = (string)($consultation['status'] ?? '');
                                                        $status = strtolower(trim($raw_status));
                                                        if ($status === '' || $status === 'null' || $status === '0') {
                                                            $status = 'pending';
                                                        }
                                                        $allowed_consultation_status = ['pending', 'approved', 'declined', 'scheduled', 'completed', 'cancelled'];
                                                        if (!in_array($status, $allowed_consultation_status, true)) {
                                                            $status = 'pending';
                                                        }
                                                        $status_display = [
                                                            'pending' => 'Pending',
                                                            'approved' => 'Approved',
                                                            'declined' => 'Declined',
                                                            'scheduled' => 'Scheduled',
                                                            'completed' => 'Completed',
                                                            'cancelled' => 'Cancelled'
                                                        ];
                                                        $display_text = $status_display[$status] ?? 'Pending';
                                                    ?>
                                                    <?php
                                                        $con_colors = [
                                                            'pending' => ['bg' => '#fef3c7', 'color' => '#92400e', 'border' => '#fcd34d'],
                                                            'approved' => ['bg' => '#d1fae5', 'color' => '#065f46', 'border' => '#a7f3d0'],
                                                            'declined' => ['bg' => '#fee2e2', 'color' => '#991b1b', 'border' => '#fecaca'],
                                                            'scheduled' => ['bg' => '#dbeafe', 'color' => '#1e40af', 'border' => '#93c5fd'],
                                                            'completed' => ['bg' => '#dcfce7', 'color' => '#166534', 'border' => '#bbf7d0'],
                                                            'cancelled' => ['bg' => '#fee2e2', 'color' => '#991b1b', 'border' => '#fecaca']
                                                        ];
                                                        $cc = $con_colors[$status] ?? $con_colors['pending'];
                                                    ?>
                                                    <span class="status-tag tag-<?php echo htmlspecialchars($status); ?>" style="background: <?php echo $cc['bg']; ?>; color: <?php echo $cc['color']; ?>; border: 1px solid <?php echo $cc['border']; ?>; padding: 8px 14px; border-radius: 6px; font-weight: 600; display: inline-block; font-size: 12px;">
                                                        <?php echo htmlspecialchars($display_text); ?>
                                                    </span>
                                                </td>
                                                <td data-label="Actions">
                                                    <div class="action-buttons">
                                                        <?php $is_pending = ($status === 'pending'); ?>
                                                        <?php if ($is_pending): ?>
                                                            <button class="btn-action btn-update" style="background-color: #10b981 !important;" onclick="approveConsultation(<?php echo $consultation['id']; ?>, '<?php echo htmlspecialchars($consultation['email']); ?>', '<?php echo htmlspecialchars(($consultation['first_name'] ?? '') . ' ' . ($consultation['last_name'] ?? '')); ?>')">&#10003; Approve</button>
                                                            <button class="btn-action btn-delete" onclick="declineConsultation(<?php echo $consultation['id']; ?>, '<?php echo htmlspecialchars($consultation['email']); ?>', '<?php echo htmlspecialchars(($consultation['first_name'] ?? '') . ' ' . ($consultation['last_name'] ?? '')); ?>')">&#10007; Decline</button>
                                                        <?php endif; ?>
                                                        <a href="mailto:<?php echo htmlspecialchars($consultation['email']); ?>" class="btn-action btn-view">Email</a>
                                                        <button class="btn-action btn-delete" onclick="deleteConsultation(<?php echo $consultation['id']; ?>)">Delete</button>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endwhile; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
                    <div class="panel-view" data-panel="service-bookings">
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-calendar-check"></i> Service Booking Management
                            </h2>

                            <div class="table-wrapper">
                                <div class="table-header">
                                    <div>
                                        <h2>Booked Services</h2>
                                        <p style="margin: 6px 0 0 0; font-size: 13px; opacity: 0.9;">Track customer requests, preferred schedules, and project details in one place.</p>
                                    </div>
                                </div>

                                <div class="booking-summary-grid">
                                    <div class="booking-summary-card">
                                        <div class="booking-summary-value"><?php echo (int)($service_bookings_count['total_bookings'] ?? 0); ?></div>
                                        <div class="booking-summary-label">Total Bookings</div>
                                    </div>
                                    <div class="booking-summary-card">
                                        <div class="booking-summary-value"><?php echo (int)($service_bookings_count['pending_bookings'] ?? 0); ?></div>
                                        <div class="booking-summary-label">Pending Review</div>
                                    </div>
                                    <div class="booking-summary-card">
                                        <div class="booking-summary-value"><?php echo (int)($service_bookings_count['scheduled_bookings'] ?? 0); ?></div>
                                        <div class="booking-summary-label">Scheduled / Confirmed</div>
                                    </div>
                                    <div class="booking-summary-card">
                                        <div class="booking-summary-value"><?php echo (int)($service_bookings_count['completed_bookings'] ?? 0); ?></div>
                                        <div class="booking-summary-label">Completed</div>
                                    </div>
                                </div>

                                <?php if (!$service_bookings_result || $service_bookings_result->num_rows === 0): ?>
                                    <div class="empty-state">
                                        <h3>No Service Bookings Yet</h3>
                                        <p>Once customers submit a service booking, the request details will appear here.</p>
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="admin-table booking-table">
                                            <thead>
                                                <tr>
                                                    <th>ID</th>
                                                    <th>Service</th>
                                                    <th>Customer</th>
                                                    <th>Schedule</th>
                                                    <th>Budget</th>
                                                    <th>Status</th>
                                                    <th>Notes</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($booking = $service_bookings_result->fetch_assoc()): ?>
                                                    <?php
                                                        $booking_status_raw = strtolower(trim((string)($booking['status'] ?? 'pending')));
                                                        if ($booking_status_raw === '' || $booking_status_raw === 'null' || $booking_status_raw === '0') {
                                                            $booking_status_raw = 'pending';
                                                        }
                                                        $booking_status_display = [
                                                            'pending' => 'Pending',
                                                            'confirmed' => 'Confirmed',
                                                            'approved' => 'Approved',
                                                            'scheduled' => 'Scheduled',
                                                            'in_progress' => 'In Progress',
                                                            'completed' => 'Completed',
                                                            'cancelled' => 'Cancelled'
                                                        ];
                                                        $booking_status_text = $booking_status_display[$booking_status_raw] ?? ucfirst(str_replace('_', ' ', $booking_status_raw));
                                                        $booking_status_colors = [
                                                            'pending' => ['bg' => '#fef3c7', 'color' => '#92400e', 'border' => '#fcd34d'],
                                                            'confirmed' => ['bg' => '#dbeafe', 'color' => '#1e40af', 'border' => '#93c5fd'],
                                                            'approved' => ['bg' => '#dbeafe', 'color' => '#1e40af', 'border' => '#93c5fd'],
                                                            'scheduled' => ['bg' => '#e0f2fe', 'color' => '#075985', 'border' => '#bae6fd'],
                                                            'in_progress' => ['bg' => '#ede9fe', 'color' => '#5b21b6', 'border' => '#ddd6fe'],
                                                            'completed' => ['bg' => '#dcfce7', 'color' => '#166534', 'border' => '#bbf7d0'],
                                                            'cancelled' => ['bg' => '#fee2e2', 'color' => '#991b1b', 'border' => '#fecaca']
                                                        ];
                                                        $bsc = $booking_status_colors[$booking_status_raw] ?? $booking_status_colors['pending'];
                                                        $booking_payload = htmlspecialchars(json_encode([
                                                            'id' => (int)($booking['id'] ?? 0),
                                                            'service_name' => (string)($booking['service_name'] ?? ''),
                                                            'service_id' => (int)($booking['service_id'] ?? 0),
                                                            'customer_name' => (string)($booking['customer_name'] ?? ''),
                                                            'customer_email' => (string)($booking['customer_email'] ?? ''),
                                                            'customer_phone' => (string)($booking['customer_phone'] ?? ''),
                                                            'address' => (string)($booking['address'] ?? ''),
                                                            'city' => (string)($booking['city'] ?? ''),
                                                            'pincode' => (string)($booking['pincode'] ?? ''),
                                                            'area_sqft' => (int)($booking['area_sqft'] ?? 0),
                                                            'preferred_date' => (string)($booking['preferred_date'] ?? ''),
                                                            'preferred_time' => (string)($booking['preferred_time'] ?? ''),
                                                            'budget_range' => (string)($booking['budget_range'] ?? ''),
                                                            'notes' => (string)($booking['notes'] ?? ''),
                                                            'status' => (string)($booking_status_text ?? 'Pending'),
                                                            'created_at' => (string)($booking['created_at'] ?? ''),
                                                            'updated_at' => (string)($booking['updated_at'] ?? '')
                                                        ]), ENT_QUOTES, 'UTF-8');
                                                        $preferred_date_text = !empty($booking['preferred_date']) ? date('M d, Y', strtotime($booking['preferred_date'])) : 'Not selected';
                                                        $created_at_text = !empty($booking['created_at']) ? date('M d, Y', strtotime($booking['created_at'])) : 'N/A';
                                                        $notes_preview = trim((string)($booking['notes'] ?? ''));
                                                    ?>
                                                    <tr>
                                                        <td data-label="ID"><strong>#<?php echo (int)($booking['id'] ?? 0); ?></strong></td>
                                                        <td data-label="Service">
                                                            <div class="booking-cell-stack">
                                                                <strong><?php echo htmlspecialchars($booking['service_name'] ?? 'Custom Service'); ?></strong>
                                                                <span class="booking-meta-text">Service ID: #<?php echo (int)($booking['service_id'] ?? 0); ?></span>
                                                            </div>
                                                        </td>
                                                        <td data-label="Customer">
                                                            <div class="booking-cell-stack">
                                                                <strong><?php echo htmlspecialchars($booking['customer_name'] ?? 'N/A'); ?></strong>
                                                                <span><?php echo htmlspecialchars($booking['customer_email'] ?? 'N/A'); ?></span>
                                                                <small class="booking-meta-text"><?php echo htmlspecialchars($booking['customer_phone'] ?? 'N/A'); ?></small>
                                                            </div>
                                                        </td>
                                                        <td data-label="Schedule">
                                                            <div class="booking-cell-stack">
                                                                <strong><?php echo htmlspecialchars($preferred_date_text); ?></strong>
                                                                <span><?php echo htmlspecialchars($booking['preferred_time'] ?? 'Flexible'); ?></span>
                                                                <small class="booking-meta-text">Booked: <?php echo htmlspecialchars($created_at_text); ?></small>
                                                            </div>
                                                        </td>
                                                        <td data-label="Budget">
                                                            <div class="booking-cell-stack">
                                                                <strong><?php echo htmlspecialchars($booking['budget_range'] ?? 'Not specified'); ?></strong>
                                                                <small class="booking-meta-text"><?php echo (int)($booking['area_sqft'] ?? 0) > 0 ? (int)$booking['area_sqft'] . ' sq ft' : 'Area not shared'; ?></small>
                                                            </div>
                                                        </td>
                                                        <td data-label="Status">
                                                            <span class="status-tag" style="background: <?php echo $bsc['bg']; ?>; color: <?php echo $bsc['color']; ?>; border: 1px solid <?php echo $bsc['border']; ?>; padding: 8px 14px; border-radius: 999px; font-weight: 700; display: inline-block; font-size: 12px;">
                                                                <?php echo htmlspecialchars($booking_status_text); ?>
                                                            </span>
                                                        </td>
                                                        <td data-label="Notes">
                                                            <span class="booking-notes-preview"><?php echo htmlspecialchars($notes_preview !== '' ? (strlen($notes_preview) > 72 ? substr($notes_preview, 0, 69) . '...' : $notes_preview) : 'No notes added'); ?></span>
                                                        </td>
                                                        <td data-label="Actions">
                                                            <div class="action-buttons">
                                                                <button class="btn-action btn-view" type="button" onclick="viewServiceBookingDetails(<?php echo $booking_payload; ?>)">View</button>
                                                                <a class="btn-action btn-update" href="mailto:<?php echo htmlspecialchars($booking['customer_email'] ?? ''); ?>">Email</a>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="panel-view" data-panel="users">
                        <!-- Users Section -->
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-users"></i> Users Management
                            </h2>

                            <div class="table-wrapper">
                                <div class="table-header">
                                    <h2>Registered Users</h2>
                                </div>

                                <?php 
                                // Fetch users fresh for display
                                $display_users_query = "
                                    SELECT id, name, email, phone, role, created_at
                                    FROM users
                                    ORDER BY created_at DESC
                                    LIMIT 20
                                ";
                                $display_users_result = $conn->query($display_users_query);
                                $user_count = 0;
                                
                                if ($display_users_result) {
                                    $user_count = $display_users_result->num_rows;
                                } else {
                                    error_log("Display users query failed: " . $conn->error);
                                }
                                ?>

                                <?php if ($user_count === 0): ?>
                                    <div class="empty-state">
                                        <h3>No Users</h3>
                                        <p>No registered users found in the system.</p>
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="admin-table">
                                            <thead>
                                                <tr>
                                                    <th>ID</th>
                                                    <th>Name</th>
                                                    <th>Email</th>
                                                    <th>Phone</th>
                                                    <th>Role</th>
                                                    <th>Joined Date</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php 
                                                if ($display_users_result && $user_count > 0) {
                                                    while ($user = $display_users_result->fetch_assoc()): 
                                                ?>
                                                    <tr>
                                                        <td data-label="ID"><strong>#<?php echo htmlspecialchars($user['id']); ?></strong></td>
                                                        <td data-label="Name"><?php echo htmlspecialchars($user['name'] ?? 'N/A'); ?></td>
                                                        <td data-label="Email"><?php echo htmlspecialchars($user['email'] ?? 'N/A'); ?></td>
                                                        <td data-label="Phone"><?php echo htmlspecialchars($user['phone'] ?? 'N/A'); ?></td>
                                                        <td data-label="Role">
                                                            <?php
                                                                $role_val = strtolower(trim($user['role'] ?? 'customer'));
                                                                $role_colors = [
                                                                    'admin' => ['bg' => '#e9d5ff', 'color' => '#6b21a8', 'border' => '#d8b4fe'],
                                                                    'customer' => ['bg' => '#dcfce7', 'color' => '#166534', 'border' => '#bbf7d0']
                                                                ];
                                                                $rc = $role_colors[$role_val] ?? $role_colors['customer'];
                                                            ?>
                                                            <span class="status-tag tag-<?php echo htmlspecialchars($role_val); ?>" style="background: <?php echo $rc['bg']; ?>; color: <?php echo $rc['color']; ?>; border: 1px solid <?php echo $rc['border']; ?>; padding: 6px 14px; border-radius: 6px; font-weight: 600; display: inline-block; font-size: 12px;">
                                                                <?php echo ucfirst(htmlspecialchars($role_val)); ?>
                                                            </span>
                                                        </td>
                                                        <td data-label="Joined"><?php echo date('M d, Y', strtotime($user['created_at'])); ?></td>
                                                        <td data-label="Actions">
                                                            <div class="action-buttons">
                                                                <button class="btn-action btn-view" onclick="viewUserDetailsModal(<?php echo $user['id']; ?>)">View</button>
                                                                <button class="btn-action btn-delete" onclick="deleteUser(<?php echo $user['id']; ?>)">Delete</button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php 
                                                    endwhile;
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Team Members Panel -->
                    <div class="panel-view" data-panel="team">
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-people-group"></i> Team Members Management
                            </h2>

                            <div class="table-wrapper">
                                <div class="table-header">
                                    <h2>Team Members</h2>
                                    <button class="btn-action btn-update" onclick="openAddTeamModal()" style="padding:8px 12px;">
                                        <i class="fas fa-plus"></i> Add Member
                                    </button>
                                </div>

                                <div style="padding: 20px; display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 20px;" id="teamGrid">
                                    <!-- Team members will be loaded here by JavaScript -->
                                    <div style="text-align: center; color: #999;">Loading team members...</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="panel-view" data-panel="products">
                        <!-- Products Panel (moved) -->
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-boxes"></i> Products
                            </h2>

                            <div class="table-wrapper">
                                <div class="table-header">
                                    <h2>Shop Products</h2>
                                    <div>
                                        <a href="admin-add-product.php" class="btn-action btn-update" style="padding:8px 12px;">Add Product</a>
                                    </div>
                                </div>

                                <?php if (empty($products)): ?>
                                    <div class="empty-state">
                                        <h3>No Products Found</h3>
                                        <p>No products were detected in <strong>shop.php</strong>.</p>
                                    </div>
                                <?php else: ?>
                                    <div class="table-responsive">
                                        <table class="admin-table">
                                            <thead>
                                                <tr>
                                                    <th>ID</th>
                                                    <th>Image</th>
                                                    <th>Name</th>
                                                    <th>Price</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($products as $p): ?>
                                                    <tr>
                                                        <td>#<?php echo htmlspecialchars($p['id']); ?></td>
                                                        <td><img src="<?php echo htmlspecialchars($p['image']); ?>" alt="<?php echo htmlspecialchars($p['name']); ?>" style="width:80px;height:50px;object-fit:cover;border-radius:6px;"></td>
                                                        <td><?php echo htmlspecialchars($p['name']); ?></td>
                                                        <td>Rs <?php echo number_format((float)$p['price'], 0); ?></td>
                                                        <td>
                                                            <div class="action-buttons">
                                                                <a href="shop.php" class="btn-action btn-view">View on Shop</a>
                                                                <a href="admin-edit-product.php?id=<?php echo urlencode($p['id']); ?>" class="btn-action btn-update">Edit</a>
                                                                <button class="btn-action btn-delete" onclick="deleteProduct(<?php echo htmlspecialchars($p['id']); ?>)">Delete</button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endforeach; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <div class="panel-view" data-panel="gallery">
                        <!-- Gallery Section -->
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-images"></i> Gallery
                            </h2>

                            <div class="table-wrapper">
                                <div class="table-header">
                                    <h2>Gallery Images</h2>
                                    <button class="btn-action btn-update" onclick="openAddGalleryModal()" style="padding:8px 12px;">Add Gallery</button>
                                </div>

                                <div style="padding: 20px; display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px;">
                                    <?php
                                    $galleries = [];
                                    try {
                                        $conn->query("CREATE TABLE IF NOT EXISTS gallery_items (
                                            id INT AUTO_INCREMENT PRIMARY KEY,
                                            title VARCHAR(255) NOT NULL,
                                            category VARCHAR(100) NOT NULL,
                                            image VARCHAR(500) NOT NULL,
                                            sort_order INT NOT NULL DEFAULT 0,
                                            is_active TINYINT(1) NOT NULL DEFAULT 1,
                                            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                                            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

                                        $galleryRequiredCols = [
                                            'title' => "ALTER TABLE gallery_items ADD COLUMN title VARCHAR(255) NOT NULL DEFAULT ''",
                                            'category' => "ALTER TABLE gallery_items ADD COLUMN category VARCHAR(100) NOT NULL DEFAULT 'Interior'",
                                            'image' => "ALTER TABLE gallery_items ADD COLUMN image VARCHAR(500) NOT NULL DEFAULT ''",
                                            'sort_order' => "ALTER TABLE gallery_items ADD COLUMN sort_order INT NOT NULL DEFAULT 0",
                                            'is_active' => "ALTER TABLE gallery_items ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1",
                                            'created_at' => "ALTER TABLE gallery_items ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP",
                                            'updated_at' => "ALTER TABLE gallery_items ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP",
                                        ];

                                        $galleryColsResult = $conn->query("SHOW COLUMNS FROM gallery_items");
                                        $galleryExistingCols = [];
                                        if ($galleryColsResult) {
                                            while ($galleryCol = $galleryColsResult->fetch_assoc()) {
                                                $galleryExistingCols[] = $galleryCol['Field'];
                                            }
                                        }
                                        foreach ($galleryRequiredCols as $field => $sql) {
                                            if (!in_array($field, $galleryExistingCols, true)) {
                                                $conn->query($sql);
                                            }
                                        }

                                        $galleryResult = $conn->query("SELECT id, image, title, category FROM gallery_items WHERE is_active = 1 ORDER BY sort_order ASC, id ASC");
                                        if ($galleryResult) {
                                            while ($gallery = $galleryResult->fetch_assoc()) {
                                                $galleries[] = [
                                                    'id' => (int)($gallery['id'] ?? 0),
                                                    'image' => (string)($gallery['image'] ?? ''),
                                                    'alt' => (string)($gallery['title'] ?? ''),
                                                    'title' => (string)($gallery['title'] ?? ''),
                                                    'category' => (string)($gallery['category'] ?? 'Gallery')
                                                ];
                                            }
                                        }
                                    } catch (Throwable $e) {
                                        $galleries = [];
                                    }
                                    
                                    // If no galleries found, show empty state
                                    if (empty($galleries)) {
                                        echo '<p style="grid-column: 1/-1; text-align: center; color: #999;">No gallery items found</p>';
                                    } else {
                                        foreach ($galleries as $gallery): ?>
                                            <div style="background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.1); transition: transform 0.3s ease;">
                                                <div style="width: 100%; height: 200px; overflow: hidden; position: relative;">
                                                    <img src="<?php echo htmlspecialchars($gallery['image']); ?>" alt="<?php echo htmlspecialchars($gallery['title']); ?>" style="width: 100%; height: 100%; object-fit: cover;">
                                                </div>
                                                <div style="padding: 15px;">
                                                    <p style="margin: 0; font-size: 14px; font-weight: 600; color: #333;"><?php echo htmlspecialchars($gallery['title']); ?></p>
                                                    <p style="margin: 5px 0 10px 0; font-size: 12px; color: #999;"><?php echo htmlspecialchars($gallery['category']); ?></p>
                                                    <div class="action-buttons" style="gap: 8px;">
                                                        <button class="btn-action btn-update" onclick="openEditGalleryModal(<?php echo $gallery['id']; ?>, '<?php echo addslashes(htmlspecialchars($gallery['title'])); ?>', '<?php echo htmlspecialchars($gallery['category']); ?>', '<?php echo htmlspecialchars($gallery['image']); ?>')" style="flex: 1; padding: 6px;">Edit</button>
                                                        <button class="btn-action btn-delete" onclick="deleteGallery(<?php echo $gallery['id']; ?>)" style="flex: 1; padding: 6px;">Delete</button>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach;
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Projects Panel -->
                    <div class="panel-view" data-panel="projects">
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-building"></i> Projects Management
                            </h2>

                            <?php
                            $conn->query("CREATE TABLE IF NOT EXISTS projects (
                                id INT AUTO_INCREMENT PRIMARY KEY,
                                title VARCHAR(255) NOT NULL,
                                category VARCHAR(100) NOT NULL DEFAULT 'Interior',
                                location VARCHAR(120) NOT NULL DEFAULT '',
                                project_year VARCHAR(10) NOT NULL DEFAULT '',
                                image VARCHAR(500) NOT NULL DEFAULT '',
                                description TEXT,
                                sort_order INT NOT NULL DEFAULT 0,
                                is_active TINYINT(1) NOT NULL DEFAULT 1,
                                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                                INDEX idx_sort_order (sort_order),
                                INDEX idx_is_active (is_active)
                            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

                            $projectsResult = $conn->query("SELECT id, title, category, location, project_year, image, description, sort_order, is_active FROM projects ORDER BY sort_order ASC, id DESC");
                            $adminProjects = [];
                            if ($projectsResult) {
                                while ($projectRow = $projectsResult->fetch_assoc()) {
                                    $adminProjects[] = $projectRow;
                                }
                            }
                            ?>

                            <style>
                                .admin-project-grid {
                                    padding: 20px;
                                    display: grid;
                                    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
                                    gap: 20px;
                                }
                                .admin-project-card {
                                    background: #fff;
                                    border-radius: 12px;
                                    border: 1px solid #ece6de;
                                    box-shadow: 0 2px 10px rgba(0,0,0,0.08);
                                    overflow: hidden;
                                    display: flex;
                                    flex-direction: column;
                                }
                                .admin-project-image {
                                    width: 100%;
                                    aspect-ratio: 16/10;
                                    background: #f2ede6;
                                    overflow: hidden;
                                }
                                .admin-project-image img {
                                    width: 100%;
                                    height: 100%;
                                    object-fit: cover;
                                }
                                .admin-project-content {
                                    padding: 14px;
                                    display: flex;
                                    flex-direction: column;
                                    gap: 8px;
                                }
                                .admin-project-meta {
                                    display: flex;
                                    flex-wrap: wrap;
                                    gap: 6px;
                                }
                                .admin-project-badge {
                                    background: #f3ece2;
                                    color: #6b5738;
                                    border-radius: 999px;
                                    padding: 4px 8px;
                                    font-size: 11px;
                                    font-weight: 700;
                                }
                                .admin-project-title {
                                    margin: 0;
                                    font-size: 16px;
                                    font-weight: 700;
                                    color: #333;
                                }
                                .admin-project-desc {
                                    margin: 0;
                                    font-size: 13px;
                                    color: #666;
                                    line-height: 1.55;
                                    min-height: 40px;
                                }
                                .admin-project-actions {
                                    display: flex;
                                    gap: 8px;
                                    flex-wrap: wrap;
                                }
                                @media (max-width: 768px) {
                                    .admin-project-grid {
                                        grid-template-columns: 1fr;
                                        padding: 14px;
                                        gap: 14px;
                                    }
                                }
                            </style>

                            <div class="table-wrapper">
                                <div class="table-header">
                                    <h2>Website Projects (Dynamic)</h2>
                                    <button class="btn-action btn-update" onclick="openAddProjectModal()" style="padding:8px 12px;">Add Project</button>
                                </div>
                                <div class="admin-project-grid">
                                    <?php if (empty($adminProjects)): ?>
                                        <p style="grid-column: 1/-1; text-align: center; color: #999; margin: 20px 0;">No projects found. Add your first project.</p>
                                    <?php else: ?>
                                        <?php foreach ($adminProjects as $project): ?>
                                            <?php
                                            $pid = (int)($project['id'] ?? 0);
                                            $ptitle = (string)($project['title'] ?? '');
                                            $pcategory = (string)($project['category'] ?? 'Interior');
                                            $plocation = (string)($project['location'] ?? '');
                                            $pyear = (string)($project['project_year'] ?? '');
                                            $pimage = (string)($project['image'] ?? '');
                                            $pdesc = (string)($project['description'] ?? '');
                                            $psort = (int)($project['sort_order'] ?? 0);
                                            $pactive = (int)($project['is_active'] ?? 1);
                                            ?>
                                            <div class="admin-project-card">
                                                <div class="admin-project-image">
                                                    <img src="<?php echo htmlspecialchars($pimage ?: 'assets/img/project/project_1_1.jpg'); ?>" alt="<?php echo htmlspecialchars($ptitle ?: 'Project'); ?>">
                                                </div>
                                                <div class="admin-project-content">
                                                    <div class="admin-project-meta">
                                                        <span class="admin-project-badge"><?php echo htmlspecialchars($pcategory); ?></span>
                                                        <?php if ($plocation !== ''): ?><span class="admin-project-badge"><?php echo htmlspecialchars($plocation); ?></span><?php endif; ?>
                                                        <?php if ($pyear !== ''): ?><span class="admin-project-badge"><?php echo htmlspecialchars($pyear); ?></span><?php endif; ?>
                                                        <span class="admin-project-badge"><?php echo $pactive ? 'Active' : 'Hidden'; ?></span>
                                                    </div>
                                                    <p class="admin-project-title"><?php echo htmlspecialchars($ptitle); ?></p>
                                                    <p class="admin-project-desc"><?php echo htmlspecialchars($pdesc !== '' ? $pdesc : 'No description provided.'); ?></p>
                                                    <div class="admin-project-actions">
                                                        <button class="btn-action btn-update" onclick="openEditProjectModal(<?php echo $pid; ?>, <?php echo htmlspecialchars(json_encode($ptitle), ENT_QUOTES); ?>, <?php echo htmlspecialchars(json_encode($pcategory), ENT_QUOTES); ?>, <?php echo htmlspecialchars(json_encode($plocation), ENT_QUOTES); ?>, <?php echo htmlspecialchars(json_encode($pyear), ENT_QUOTES); ?>, <?php echo htmlspecialchars(json_encode($pdesc), ENT_QUOTES); ?>, <?php echo htmlspecialchars(json_encode($pimage), ENT_QUOTES); ?>, <?php echo $psort; ?>, <?php echo $pactive; ?>)" style="flex:1; padding:6px;">Edit</button>
                                                        <button class="btn-action btn-delete" onclick="deleteProject(<?php echo $pid; ?>)" style="flex:1; padding:6px;">Delete</button>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Blog Panel -->
                    <div class="panel-view" data-panel="blog">
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-newspaper"></i> Blog Management
                            </h2>
                            <style>
                                /* Admin Blog Grid - Isolated from page styles */
                                .admin-blog-container {
                                    padding: 20px;
                                    display: grid;
                                    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
                                    gap: 20px;
                                }
                                .admin-blog-item {
                                    background: white;
                                    border-radius: 10px;
                                    overflow: hidden;
                                    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                                    transition: transform 0.3s ease;
                                }
                                .admin-blog-item:hover {
                                    transform: translateY(-4px);
                                }
                                .admin-blog-item .blog-img {
                                    width: 100%;
                                    height: 180px;
                                    overflow: hidden;
                                    position: relative;
                                }
                                .admin-blog-item .blog-img img {
                                    width: 100%;
                                    height: 100%;
                                    object-fit: cover;
                                }
                                .admin-blog-item .blog-content {
                                    padding: 15px;
                                }
                                .admin-blog-item .blog-category {
                                    display: inline-block;
                                    background: #f0f0f0;
                                    color: #666;
                                    padding: 4px 8px;
                                    border-radius: 4px;
                                    font-size: 12px;
                                    margin-bottom: 8px;
                                }
                                .admin-blog-item .blog-date {
                                    margin: 0 0 5px 0;
                                    font-size: 14px;
                                    color: #999;
                                }
                                .admin-blog-item .blog-title {
                                    margin: 0 0 10px 0;
                                    font-size: 15px;
                                    font-weight: 600;
                                    color: #333;
                                    line-height: 1.3;
                                }
                                .admin-blog-item .blog-author {
                                    margin: 0 0 10px 0;
                                    font-size: 12px;
                                    color: #999;
                                }
                            </style>
                            <div class="table-wrapper">
                                <div class="table-header">
                                    <h2>Blog Posts</h2>
                                    <button class="btn-action btn-update" onclick="openAddBlogModal()" style="padding:8px 12px;">Add Blog Post</button>
                                </div>

                                <div class="admin-blog-container">
                                    <?php
                                    $conn->query("CREATE TABLE IF NOT EXISTS blogs (
                                        id INT AUTO_INCREMENT PRIMARY KEY,
                                        title VARCHAR(255) NOT NULL,
                                        category VARCHAR(120) NOT NULL,
                                        author VARCHAR(120) NOT NULL,
                                        day VARCHAR(10) NOT NULL,
                                        month VARCHAR(30) NOT NULL,
                                        image_path VARCHAR(500) NOT NULL,
                                        content TEXT,
                                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

                                    $blog_posts = [];
                                    $blog_result = $conn->query("SELECT id, title, category, author, day, month, image_path FROM blogs ORDER BY created_at DESC");
                                    if ($blog_result) {
                                        while ($row = $blog_result->fetch_assoc()) {
                                            $blog_posts[] = [
                                                'id' => (int)($row['id'] ?? 0),
                                                'image' => (string)($row['image_path'] ?? ''),
                                                'category' => (string)($row['category'] ?? ''),
                                                'author' => (string)($row['author'] ?? ''),
                                                'title' => (string)($row['title'] ?? ''),
                                                'day' => (string)($row['day'] ?? ''),
                                                'month' => (string)($row['month'] ?? '')
                                            ];
                                        }
                                    }
                                    
                                    if (empty($blog_posts)) {
                                        echo '<p style="grid-column: 1/-1; text-align: center; color: #999;">No blog posts found.</p>';
                                    } else {
                                        foreach ($blog_posts as $post): ?>
                                            <div class="admin-blog-item">
                                                <div class="blog-img">
                                                    <img src="<?php echo htmlspecialchars($post['image']); ?>" alt="<?php echo htmlspecialchars($post['title']); ?>">
                                                </div>
                                                <div class="blog-content">
                                                    <span class="blog-category"><?php echo htmlspecialchars($post['category']); ?></span>
                                                    <p class="blog-date"><?php echo htmlspecialchars($post['month'] . ' ' . $post['day']); ?></p>
                                                    <p class="blog-title"><?php echo htmlspecialchars($post['title']); ?></p>
                                                    <p class="blog-author">by <?php echo htmlspecialchars($post['author']); ?></p>
                                                    <div class="action-buttons" style="gap: 8px;">
                                                        <button class="btn-action btn-update" onclick="openEditBlogModal(<?php echo (int)$post['id']; ?>, <?php echo htmlspecialchars(json_encode((string)$post['title']), ENT_QUOTES); ?>, <?php echo htmlspecialchars(json_encode((string)$post['category']), ENT_QUOTES); ?>, <?php echo htmlspecialchars(json_encode((string)$post['author']), ENT_QUOTES); ?>, <?php echo htmlspecialchars(json_encode((string)$post['image']), ENT_QUOTES); ?>, <?php echo htmlspecialchars(json_encode((string)$post['day']), ENT_QUOTES); ?>, <?php echo htmlspecialchars(json_encode((string)$post['month']), ENT_QUOTES); ?>)" style="flex: 1; padding: 6px;">Edit</button>
                                                        <button class="btn-action btn-delete" onclick="deleteBlog(<?php echo $post['id']; ?>)" style="flex: 1; padding: 6px;">Delete</button>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endforeach;
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Services Panel -->
                    <div class="panel-view" data-panel="services">
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-concierge-bell"></i> Services Management
                            </h2>
                            <div class="table-wrapper">
                                <div class="table-header">
                                    <h2>Our Services</h2>
                                    <button class="btn-action btn-update" onclick="addService()" style="padding: 8px 12px;">Add Service</button>
                                </div>
                                <style>
                                    .service-admin-grid {
                                        display: grid;
                                        grid-template-columns: repeat(3, minmax(0, 1fr));
                                        gap: 20px;
                                        padding: 20px;
                                    }
                                    .service-admin-card {
                                        background: white;
                                        border-radius: 10px;
                                        border: 1px solid #ddd;
                                        overflow: hidden;
                                        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
                                        transition: transform 0.3s ease;
                                    }
                                    .service-admin-card:hover {
                                        transform: translateY(-3px);
                                    }
                                    .service-admin-image {
                                        width: 100%;
                                        height: 200px;
                                        object-fit: cover;
                                    }
                                    .service-admin-content {
                                        padding: 20px;
                                    }
                                    .service-admin-title {
                                        color: #1b8a67;
                                        margin: 0 0 10px 0;
                                        font-size: 18px;
                                    }
                                    .service-admin-desc {
                                        color: #555;
                                        font-size: 14px;
                                        line-height: 1.6;
                                        margin: 0 0 15px 0;
                                    }
                                    .service-admin-actions {
                                        display: flex;
                                        gap: 8px;
                                    }
                                    .service-admin-badges {
                                        display: flex;
                                        gap: 8px;
                                        margin-bottom: 12px;
                                        flex-wrap: wrap;
                                    }
                                    .service-admin-badge {
                                        display: inline-flex;
                                        align-items: center;
                                        gap: 4px;
                                        padding: 4px 10px;
                                        background: #f0f8f5;
                                        border: 1px solid #1b8a67;
                                        color: #1b8a67;
                                        border-radius: 12px;
                                        font-size: 12px;
                                        font-weight: 600;
                                    }
                                    @media (max-width: 1024px) {
                                        .service-admin-grid {
                                            grid-template-columns: repeat(2, minmax(0, 1fr));
                                        }
                                    }
                                    @media (max-width: 768px) {
                                        .service-admin-grid {
                                            grid-template-columns: repeat(2, minmax(0, 1fr));
                                            gap: 16px;
                                            padding: 16px;
                                        }
                                        .service-admin-card {
                                            border-radius: 8px;
                                        }
                                        .service-admin-image {
                                            height: 180px;
                                        }
                                        .service-admin-content {
                                            padding: 16px;
                                        }
                                        .service-admin-title {
                                            font-size: 16px;
                                        }
                                        .service-admin-desc {
                                            font-size: 13px;
                                        }
                                    }
                                    @media (max-width: 640px) {
                                        .service-admin-grid {
                                            grid-template-columns: 1fr;
                                            padding: 12px;
                                            gap: 14px;
                                        }
                                        .service-admin-content {
                                            padding: 14px;
                                        }
                                        .service-admin-image {
                                            height: 160px;
                                        }
                                        .service-admin-badges {
                                            margin-bottom: 10px;
                                        }
                                        .service-admin-badge {
                                            font-size: 11px;
                                            padding: 3px 8px;
                                        }
                                    }
                                </style>
                                <div class="service-admin-grid">
                                    <?php
                                    $services = [];
                                    try {
                                        $conn->query("CREATE TABLE IF NOT EXISTS services (
                                            id INT AUTO_INCREMENT PRIMARY KEY,
                                            title VARCHAR(255) NOT NULL,
                                            image VARCHAR(500) NOT NULL,
                                            link VARCHAR(500) DEFAULT '#',
                                            description TEXT NOT NULL,
                                            area_sqft INT,
                                            price DECIMAL(10, 2),
                                            duration VARCHAR(100),
                                            status VARCHAR(50) DEFAULT 'ACTIVE',
                                            sort_order INT NOT NULL DEFAULT 0,
                                            is_active TINYINT(1) NOT NULL DEFAULT 1,
                                            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                                            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
                                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

                                        $conn->query("CREATE TABLE IF NOT EXISTS service_products (
                                            id INT AUTO_INCREMENT PRIMARY KEY,
                                            service_id INT NOT NULL,
                                            product_name VARCHAR(255) NOT NULL,
                                            cost DECIMAL(10, 2),
                                            quantity VARCHAR(100),
                                            sort_order INT DEFAULT 0,
                                            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                                            FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE,
                                            INDEX idx_service_id (service_id)
                                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

                                        $conn->query("CREATE TABLE IF NOT EXISTS service_tools (
                                            id INT AUTO_INCREMENT PRIMARY KEY,
                                            service_id INT NOT NULL,
                                            tool_name VARCHAR(255) NOT NULL,
                                            tool_description TEXT,
                                            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                                            FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE,
                                            INDEX idx_service_id (service_id)
                                        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

                                        $requiredCols = [
                                            'title' => "ALTER TABLE services ADD COLUMN title VARCHAR(255) NOT NULL DEFAULT ''",
                                            'image' => "ALTER TABLE services ADD COLUMN image VARCHAR(500) NOT NULL DEFAULT ''",
                                            'link' => "ALTER TABLE services ADD COLUMN link VARCHAR(500) DEFAULT '#'",
                                            'description' => "ALTER TABLE services ADD COLUMN description TEXT NOT NULL",
                                            'area_sqft' => "ALTER TABLE services ADD COLUMN area_sqft INT",
                                            'price' => "ALTER TABLE services ADD COLUMN price DECIMAL(10, 2)",
                                            'duration' => "ALTER TABLE services ADD COLUMN duration VARCHAR(100)",
                                            'status' => "ALTER TABLE services ADD COLUMN status VARCHAR(50) DEFAULT 'ACTIVE'",
                                            'sort_order' => "ALTER TABLE services ADD COLUMN sort_order INT NOT NULL DEFAULT 0",
                                            'is_active' => "ALTER TABLE services ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1",
                                            'created_at' => "ALTER TABLE services ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP",
                                            'updated_at' => "ALTER TABLE services ADD COLUMN updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP",
                                        ];

                                        $existingCols = [];
                                        $colsResult = $conn->query("SHOW COLUMNS FROM services");
                                        if ($colsResult) {
                                            while ($col = $colsResult->fetch_assoc()) {
                                                $existingCols[] = $col['Field'];
                                            }
                                        }
                                        foreach ($requiredCols as $field => $sql) {
                                            if (!in_array($field, $existingCols, true)) {
                                                @$conn->query($sql);
                                            }
                                        }

                                        $serviceResult = $conn->query("SELECT id, title, image, link, description, area_sqft, price, duration, status FROM services WHERE is_active = 1 ORDER BY sort_order ASC, id ASC");
                                        if ($serviceResult) {
                                            while ($row = $serviceResult->fetch_assoc()) {
                                                $services[] = $row;
                                            }
                                        }
                                    } catch (Throwable $e) {
                                        $services = [];
                                    }

                                    if (empty($services)) {
                                        echo '<p style="grid-column: 1/-1; text-align: center; color: #999;">No services found. Click \"Add Service\" to create one.</p>';
                                    } else {
                                        foreach ($services as $index => $service) {
                                            $serviceId = (int)($service['id'] ?? 0);
                                            $productCount = 0;
                                            $toolCount = 0;
                                            
                                            // Count products and tools
                                            if ($serviceId > 0) {
                                                $prodCountResult = $conn->query("SELECT COUNT(*) as count FROM service_products WHERE service_id = $serviceId");
                                                if ($prodCountResult) {
                                                    $prodRow = $prodCountResult->fetch_assoc();
                                                    $productCount = (int)($prodRow['count'] ?? 0);
                                                }
                                                
                                                $toolCountResult = $conn->query("SELECT COUNT(*) as count FROM service_tools WHERE service_id = $serviceId");
                                                if ($toolCountResult) {
                                                    $toolRow = $toolCountResult->fetch_assoc();
                                                    $toolCount = (int)($toolRow['count'] ?? 0);
                                                }
                                            }
                                            
                                            $serviceData = [
                                                'id' => $serviceId,
                                                'title' => (string)($service['title'] ?? ''),
                                                'image' => (string)($service['image'] ?? ''),
                                                'link' => (string)($service['link'] ?? '#'),
                                                'description' => (string)($service['description'] ?? ''),
                                                'area_sqft' => (int)($service['area_sqft'] ?? 0),
                                                'price' => (float)($service['price'] ?? 0),
                                                'duration' => (string)($service['duration'] ?? ''),
                                                'status' => (string)($service['status'] ?? 'ACTIVE'),
                                                'index' => (int)$index
                                            ];
                                            echo '<div class="service-admin-card">';
                                            echo '<img src="' . htmlspecialchars($serviceData['image']) . '" alt="' . htmlspecialchars($serviceData['title']) . '" class="service-admin-image">';
                                            echo '<div class="service-admin-content">';
                                            echo '<h3 class="service-admin-title">' . htmlspecialchars($serviceData['title']) . '</h3>';
                                            
                                            // Show badges
                                            echo '<div class="service-admin-badges">';
                                            echo '<span class="service-admin-badge"><i class="fas fa-box" style="font-size: 11px;"></i> ' . $productCount . ' Products</span>';
                                            echo '<span class="service-admin-badge"><i class="fas fa-tools" style="font-size: 11px;"></i> ' . $toolCount . ' Tools</span>';
                                            echo '</div>';
                                            
                                            $previewDesc = strlen($serviceData['description']) > 90 ? substr($serviceData['description'], 0, 90) . '...' : $serviceData['description'];
                                            echo '<p class="service-admin-desc">' . htmlspecialchars($previewDesc) . '</p>';
                                            echo '<div class="service-admin-actions">';
                                            echo '<button class="btn-action btn-view" onclick="editService(' . $serviceId . ', ' . htmlspecialchars(json_encode($serviceData), ENT_QUOTES, 'UTF-8') . ')" style="flex: 1;">Edit</button>';
                                            echo '<button class="btn-action btn-delete" onclick="deleteService(' . $serviceId . ', \'' . addslashes($serviceData['title']) . '\')" style="flex: 1; background: #e74c3c;">Delete</button>';
                                            echo '</div>';
                                            echo '</div>';
                                            echo '</div>';
                                        }
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Hero Slider Panel -->
                    <div class="panel-view" data-panel="hero-slide">
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-image"></i> Hero Slider Management
                            </h2>
                            <div class="table-wrapper" style="padding: 20px;">
                                <div class="table-header">
                                    <h2>Hero Slider Slides</h2>
                                    <button class="btn-action btn-update" onclick="addHeroSlide()" style="padding: 8px 12px;">Add Slide</button>
                                </div>
                                <!-- Hero Slider Preview Carousel -->
                                <div style="position: relative; margin-top: 20px; background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                    <style>
                                        .hero-slides-grid {
                                            display: grid;
                                            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
                                            gap: 20px;
                                            padding: 20px;
                                        }
                                        .hero-slide-card {
                                            background: white;
                                            border: 1px solid #e0e0e0;
                                            border-radius: 10px;
                                            overflow: hidden;
                                            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
                                            transition: all 0.3s ease;
                                            cursor: pointer;
                                        }
                                        .hero-slide-card:hover {
                                            box-shadow: 0 4px 16px rgba(0,0,0,0.15);
                                            transform: translateY(-2px);
                                        }
                                        .hero-slide-card .slide-image {
                                            width: 100%;
                                            height: 200px;
                                            background-size: cover;
                                            background-position: center;
                                            position: relative;
                                        }
                                        .hero-slide-card .slide-badge {
                                            position: absolute;
                                            top: 10px;
                                            right: 10px;
                                            background: #d4a574;
                                            color: white;
                                            padding: 6px 12px;
                                            border-radius: 20px;
                                            font-size: 12px;
                                            font-weight: 600;
                                        }
                                        .hero-slide-card .slide-content {
                                            padding: 16px;
                                        }
                                        .hero-slide-card .slide-subtitle {
                                            font-size: 12px;
                                            color: #d4a574;
                                            text-transform: uppercase;
                                            letter-spacing: 1px;
                                            margin-bottom: 8px;
                                            font-weight: 600;
                                        }
                                        .hero-slide-card .slide-title {
                                            font-size: 16px;
                                            font-weight: 700;
                                            color: #333;
                                            margin-bottom: 12px;
                                            line-height: 1.4;
                                        }
                                        .hero-slide-card .slide-title .highlight {
                                            color: #d4a574;
                                        }
                                        .hero-slide-card .slide-actions {
                                            display: flex;
                                            gap: 8px;
                                            margin-top: 12px;
                                        }
                                        .hero-slide-card .slide-actions button {
                                            flex: 1;
                                            padding: 8px 12px;
                                            border: none;
                                            border-radius: 6px;
                                            font-size: 12px;
                                            font-weight: 600;
                                            cursor: pointer;
                                            transition: all 0.3s;
                                        }
                                        .hero-slide-card .btn-edit {
                                            background: #d4a574;
                                            color: white;
                                        }
                                        .hero-slide-card .btn-edit:hover {
                                            background: #c4956a;
                                        }
                                        .hero-slide-card .btn-delete {
                                            background: #f1f1f1;
                                            color: #e74c3c;
                                        }
                                        .hero-slide-card .btn-delete:hover {
                                            background: #e74c3c;
                                            color: white;
                                        }
                                        .add-slide-btn {
                                            padding: 20px;
                                            text-align: center;
                                        }
                                        .add-slide-btn button {
                                            padding: 12px 30px;
                                            background: #d4a574;
                                            color: white;
                                            border: none;
                                            border-radius: 6px;
                                            font-size: 14px;
                                            font-weight: 600;
                                            cursor: pointer;
                                            transition: all 0.3s;
                                        }
                                        .add-slide-btn button:hover {
                                            background: #c4956a;
                                        }
                                    </style>

                                    <div style="padding: 20px;">
                                        <h3 style="margin: 0 0 20px 0; color: #333; font-size: 18px;">Hero Slides</h3>
                                        <div class="hero-slides-grid" id="heroSlidesContainer">
                                            <p style="grid-column: 1/-1; text-align: center; color: #999; padding: 40px;">Loading hero slides...</p>
                                        </div>
                                    </div>

                                    <div class="add-slide-btn">
                                        <button onclick="addHeroSlide()">+ Add New Slide</button>
                                    </div>
                                </div>

                                <script>
                                    // Hero Slider State
                                    let currentSlideIndex = 0;
                                    
                                    // Load hero slides via AJAX
                                    function loadHeroSlides() {
                                        const formData = new FormData();
                                        formData.append('action', 'get_slides');
                                        
                                        fetch('admin-hero-slider-handler.php', {
                                            method: 'POST',
                                            body: formData
                                        })
                                        .then(response => response.json())
                                        .then(data => {
                                            if (data.success) {
                                                window.heroSlides = data.data;
                                                renderHeroSlidesGrid();
                                            } else {
                                                const container = document.getElementById('heroSlidesContainer');
                                                container.innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #e74c3c;">Error: ' + data.message + '</p>';
                                            }
                                        })
                                        .catch(error => {
                                            console.error('Error loading slides:', error);
                                            const container = document.getElementById('heroSlidesContainer');
                                            container.innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #e74c3c;">Error loading slides. Please try again.</p>';
                                        });
                                    }

                                    function renderHeroSlidesGrid() {
                                        const container = document.getElementById('heroSlidesContainer');
                                        container.innerHTML = '';

                                        if (!window.heroSlides || window.heroSlides.length === 0) {
                                            container.innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #999; padding: 40px;">No hero slides found. Click "Add New Slide" to create one.</p>';
                                            return;
                                        }

                                        // Create slide cards
                                        window.heroSlides.forEach((slide, index) => {
                                            const card = document.createElement('div');
                                            card.className = 'hero-slide-card';
                                            card.innerHTML = `
                                                <div class="slide-image" style="background-image: url('${slide.image}');">
                                                    <div class="slide-badge">Slide ${index + 1}</div>
                                                </div>
                                                <div class="slide-content">
                                                    <div class="slide-subtitle">${slide.subtitle}</div>
                                                    <div class="slide-title">
                                                        ${slide.title_part1} 
                                                        <span class="highlight">${slide.highlight}</span> 
                                                        ${slide.title_part2}
                                                    </div>
                                                    <div class="slide-actions">
                                                        <button class="btn-edit" onclick="editHeroSlide(${index})">Edit</button>
                                                        <button class="btn-delete" onclick="deleteHeroSlide(${index})">Delete</button>
                                                    </div>
                                                </div>
                                            `;
                                            container.appendChild(card);
                                        });
                                    }

                                    function goToSlide(index) {
                                        currentSlideIndex = index;
                                        updateSliderDisplay();
                                    }

                                    function nextHeroSlide() {
                                        if (!window.heroSlides) return;
                                        currentSlideIndex = (currentSlideIndex + 1) % window.heroSlides.length;
                                        updateSliderDisplay();
                                    }

                                    function prevHeroSlide() {
                                        if (!window.heroSlides) return;
                                        currentSlideIndex = (currentSlideIndex - 1 + window.heroSlides.length) % window.heroSlides.length;
                                        updateSliderDisplay();
                                    }

                                    function updateSliderDisplay() {
                                        const slides = document.querySelectorAll('.hero-slides-grid .hero-slide-card');
                                        slides.forEach((slide, index) => {
                                            slide.classList.toggle('active', index === currentSlideIndex);
                                        });
                                    }
                                    
                                    // Load slides when page loads and when this section is visible
                                    document.addEventListener('DOMContentLoaded', loadHeroSlides);
                                    
                                    // Also load when the hero-slide panel is clicked (if tabbed interface)
                                    document.addEventListener('click', function(e) {
                                        if (e.target.getAttribute('data-target') === 'hero-slide') {
                                            loadHeroSlides();
                                        }
                                    });
                                </script>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Newsletter Panel -->
                    <div class="panel-view" data-panel="newsletter">
                        <div class="dashboard-section" style="width: 100%; margin: 0; padding: 0 20px;">
                            <h2 class="section-title">
                                <i class="fas fa-envelope"></i> Newsletter Management
                            </h2>
                            
                            <style>
                                .newsletter-stats-grid {
                                    display: grid;
                                    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
                                    gap: 15px;
                                    margin-bottom: 30px;
                                    width: 100%;
                                }
                                
                                .newsletter-stat-card {
                                    background: white;
                                    padding: 20px;
                                    border-radius: 10px;
                                    border-left: 4px solid #d4a574;
                                    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
                                    text-align: center;
                                }
                                
                                .newsletter-stat-value {
                                    font-size: 28px;
                                    font-weight: 700;
                                    color: #d4a574;
                                    margin: 0 0 8px 0;
                                }
                                
                                .newsletter-stat-label {
                                    font-size: 12px;
                                    color: #666;
                                    font-weight: 600;
                                    text-transform: uppercase;
                                    letter-spacing: 0.5px;
                                }
                                
                                .newsletter-tools-grid {
                                    display: grid;
                                    grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
                                    gap: 15px;
                                    padding: 20px;
                                    width: 100%;
                                }
                                
                                .newsletter-tool-card {
                                    color: white;
                                    padding: 20px;
                                    border-radius: 10px;
                                    text-align: center;
                                    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.15);
                                    transition: transform 0.3s ease, box-shadow 0.3s ease;
                                    display: flex;
                                    flex-direction: column;
                                    justify-content: space-between;
                                    min-height: 200px;
                                }
                                
                                .newsletter-tool-card:hover {
                                    transform: translateY(-5px);
                                    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
                                }
                                
                                .newsletter-tool-icon {
                                    font-size: 32px;
                                    margin-bottom: 12px;
                                    opacity: 0.9;
                                }
                                
                                .newsletter-tool-title {
                                    margin: 10px 0;
                                    font-size: 16px;
                                    font-weight: 600;
                                }
                                
                                .newsletter-tool-desc {
                                    margin: 0 0 15px 0;
                                    font-size: 13px;
                                    opacity: 0.9;
                                    line-height: 1.4;
                                }
                                
                                .newsletter-tool-btn {
                                    background: white;
                                    text-decoration: none;
                                    display: inline-block;
                                    padding: 10px 18px;
                                    border-radius: 5px;
                                    font-weight: 600;
                                    font-size: 12px;
                                    cursor: pointer;
                                    border: none;
                                    transition: all 0.3s ease;
                                }
                                
                                .newsletter-table-responsive {
                                    overflow-x: auto;
                                    -webkit-overflow-scrolling: touch;
                                }
                                
                                .newsletter-table {
                                    width: 100%;
                                    border-collapse: collapse;
                                }
                                
                                .newsletter-container {
                                    width: 100%;
                                }
                                
                                .newsletter-table thead {
                                    background: #f5f5f5;
                                    border-bottom: 2px solid #e0e0e0;
                                }
                                
                                .newsletter-table th {
                                    padding: 15px;
                                    text-align: left;
                                    color: #333;
                                    font-weight: 600;
                                    font-size: 13px;
                                    text-transform: uppercase;
                                    letter-spacing: 0.5px;
                                }
                                
                                .newsletter-table td {
                                    padding: 12px 15px;
                                    border-bottom: 1px solid #e0e0e0;
                                    font-size: 13px;
                                }
                                
                                .newsletter-table tr:hover {
                                    background: #f9f9f9;
                                }
                                
                                @media (max-width: 768px) {
                                    .newsletter-stats-grid {
                                        grid-template-columns: repeat(2, 1fr);
                                        gap: 12px;
                                    }
                                    
                                    .newsletter-stat-card {
                                        padding: 15px;
                                    }
                                    
                                    .newsletter-stat-value {
                                        font-size: 24px;
                                    }
                                    
                                    .newsletter-stat-label {
                                        font-size: 11px;
                                    }
                                    
                                    .newsletter-tools-grid {
                                        grid-template-columns: repeat(2, 1fr);
                                        gap: 12px;
                                        padding: 15px;
                                    }
                                    
                                    .newsletter-tool-card {
                                        padding: 15px;
                                        min-height: 180px;
                                    }
                                    
                                    .newsletter-tool-icon {
                                        font-size: 28px;
                                        margin-bottom: 8px;
                                    }
                                    
                                    .newsletter-tool-title {
                                        font-size: 14px;
                                        margin: 8px 0;
                                    }
                                    
                                    .newsletter-tool-desc {
                                        font-size: 12px;
                                        margin-bottom: 12px;
                                    }
                                    
                                    .newsletter-tool-btn {
                                        padding: 8px 14px;
                                        font-size: 11px;
                                    }
                                    
                                    .newsletter-table th,
                                    .newsletter-table td {
                                        padding: 10px;
                                        font-size: 12px;
                                    }
                                }
                                
                                @media (max-width: 480px) {
                                    .newsletter-stats-grid {
                                        grid-template-columns: repeat(2, 1fr);
                                        gap: 10px;
                                    }
                                    
                                    .newsletter-stat-card {
                                        padding: 12px;
                                    }
                                    
                                    .newsletter-stat-value {
                                        font-size: 20px;
                                    }
                                    
                                    .newsletter-stat-label {
                                        font-size: 10px;
                                    }
                                    
                                    .newsletter-tools-grid {
                                        grid-template-columns: 1fr;
                                        gap: 10px;
                                        padding: 12px;
                                    }
                                    
                                    .newsletter-tool-card {
                                        padding: 15px;
                                        min-height: 160px;
                                    }
                                    
                                    .newsletter-tool-icon {
                                        font-size: 26px;
                                    }
                                    
                                    .newsletter-tool-title {
                                        font-size: 13px;
                                    }
                                    
                                    .newsletter-tool-desc {
                                        font-size: 11px;
                                    }
                                    
                                    .newsletter-table {
                                        font-size: 11px;
                                    }
                                    
                                    .newsletter-table th,
                                    .newsletter-table td {
                                        padding: 8px 10px;
                                    }
                                }
                            </style>

                            <!-- Newsletter Statistics -->
                            <div class="newsletter-stats-grid">
                                <div class="newsletter-stat-card">
                                    <div class="newsletter-stat-value"><?php echo $newsletter_stats['total_subscribers'] ?? 0; ?></div>
                                    <div class="newsletter-stat-label">Total Subscribers</div>
                                </div>
                                <div class="newsletter-stat-card">
                                    <div class="newsletter-stat-value"><?php echo $newsletter_stats['confirmed_subscribers'] ?? 0; ?></div>
                                    <div class="newsletter-stat-label">Confirmed</div>
                                </div>
                                <div class="newsletter-stat-card">
                                    <div class="newsletter-stat-value"><?php echo $newsletter_stats['pending_subscribers'] ?? 0; ?></div>
                                    <div class="newsletter-stat-label">Pending Approval</div>
                                </div>
                                <div class="newsletter-stat-card">
                                    <div class="newsletter-stat-value"><?php echo $newsletter_stats['sent_campaigns'] ?? 0; ?></div>
                                    <div class="newsletter-stat-label">Campaigns Sent</div>
                                </div>
                                <div class="newsletter-stat-card">
                                    <div class="newsletter-stat-value"><?php echo $newsletter_stats['draft_campaigns'] ?? 0; ?></div>
                                    <div class="newsletter-stat-label">Draft Campaigns</div>
                                </div>
                            </div>

                            <!-- Newsletter Quick Links -->
                            <div class="table-wrapper">
                                <div class="table-header">
                                    <h3>Newsletter Management Tools</h3>
                                </div>
                                <div class="newsletter-tools-grid">
                                    <div class="newsletter-tool-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                        <div>
                                            <i class="fas fa-users newsletter-tool-icon"></i>
                                            <h4 class="newsletter-tool-title">Manage Subscribers</h4>
                                            <p class="newsletter-tool-desc">View and manage all newsletter subscribers</p>
                                        </div>
                                        <a href="admin-newsletter.php?action=subscribers" class="newsletter-tool-btn" style="color: #667eea;">View Subscribers</a>
                                    </div>

                                    <div class="newsletter-tool-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                                        <div>
                                            <i class="fas fa-tasks newsletter-tool-icon"></i>
                                            <h4 class="newsletter-tool-title">Pending Approvals</h4>
                                            <p class="newsletter-tool-desc">Approve or reject pending subscribers</p>
                                        </div>
                                        <a href="admin-newsletter.php?action=approvals" class="newsletter-tool-btn" style="color: #f5576c;">Review Approvals</a>
                                    </div>

                                    <div class="newsletter-tool-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                                        <div>
                                            <i class="fas fa-rocket newsletter-tool-icon"></i>
                                            <h4 class="newsletter-tool-title">Create Campaign</h4>
                                            <p class="newsletter-tool-desc">Design and send campaigns to subscribers</p>
                                        </div>
                                        <a href="admin-newsletter.php?action=create_campaign" class="newsletter-tool-btn" style="color: #00f2fe;">New Campaign</a>
                                    </div>

                                    <div class="newsletter-tool-card" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                                        <div>
                                            <i class="fas fa-chart-bar newsletter-tool-icon"></i>
                                            <h4 class="newsletter-tool-title">View Campaigns</h4>
                                            <p class="newsletter-tool-desc">Check campaign performance and details</p>
                                        </div>
                                        <a href="admin-newsletter.php?action=campaigns" class="newsletter-tool-btn" style="color: #fee140;">View Campaigns</a>
                                    </div>
                                </div>
                            </div>

                            <!-- Recent Subscribers Table -->
                            <div class="table-wrapper" style="margin-top: 30px;">
                                <div class="table-header">
                                    <h3>Recent Subscribers</h3>
                                </div>
                                <div class="newsletter-table-responsive">
                                    <table class="newsletter-table">
                                        <thead>
                                            <tr>
                                                <th>Email</th>
                                                <th>Name</th>
                                                <th>Status</th>
                                                <th>Joined</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            if (isset($newsletter_stats['total_subscribers']) && $newsletter_stats['total_subscribers'] > 0) {
                                                $recent_subscribers_query = $conn->query("
                                                    SELECT id, email, full_name, status, created_at 
                                                    FROM newsletter_subscribers 
                                                    ORDER BY created_at DESC 
                                                    LIMIT 5
                                                ");
                                                
                                                if ($recent_subscribers_query && $recent_subscribers_query->num_rows > 0) {
                                                    while ($row = $recent_subscribers_query->fetch_assoc()) {
                                                        $status_class = 'badge-' . $row['status'];
                                                        echo '<tr>';
                                                        echo '<td>' . htmlspecialchars($row['email']) . '</td>';
                                                        echo '<td>' . htmlspecialchars($row['full_name'] ?: 'N/A') . '</td>';
                                                        echo '<td><span class="status-badge ' . $status_class . '">' . ucfirst($row['status']) . '</span></td>';
                                                        echo '<td>' . date('M d, Y', strtotime($row['created_at'])) . '</td>';
                                                        echo '</tr>';
                                                    }
                                                }
                                            } else {
                                                echo '<tr><td colspan="4" style="text-align: center; padding: 30px; color: #999;">No subscribers yet. Start collecting subscribers!</td></tr>';
                                            }
                                        ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    </div>

                    <!-- Profile Panel -->
                    <div class="panel-view" data-panel="profile">
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-user-circle"></i> Admin Profile
                            </h2>
                            <div class="config-wrap">
                                <div class="config-card">
                                    <div class="config-head">Account Information</div>
                                    <div class="config-body">
                                        <div class="config-field">
                                            <label>Admin Name</label>
                                            <input type="text" value="<?php echo htmlspecialchars($admin_profile['name']); ?>" readonly style="background:#f9f9f9;">
                                        </div>
                                        <div class="config-field">
                                            <label>Email Address</label>
                                            <input type="email" id="profileEmail" value="<?php echo htmlspecialchars($admin_profile['email']); ?>" placeholder="admin@email.com">
                                        </div>
                                        <div class="config-field">
                                            <label>Phone Number</label>
                                            <input type="tel" id="profilePhone" value="<?php echo htmlspecialchars($admin_profile['phone']); ?>" placeholder="Enter phone number">
                                        </div>
                                        <div id="profileStatus" style="display:none;padding:12px;border-radius:6px;font-size:14px;"></div>
                                        <div class="config-actions">
                                            <button id="saveProfileBtn" onclick="saveProfileChanges()" style="padding:10px 20px;background:#d4a574;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600;">Save Profile</button>
                                        </div>
                                    </div>
                                </div>
                                <div class="config-card">
                                    <div class="config-head">Security</div>
                                    <div class="config-body">
                                        <div class="config-field">
                                            <label>Current Password</label>
                                            <input type="password" id="currentPassword" placeholder="Enter current password">
                                        </div>
                                        <div class="config-field">
                                            <label>New Password</label>
                                            <input type="password" id="newPassword" placeholder="Leave empty to keep current">
                                        </div>
                                        <div class="config-field">
                                            <label>Confirm New Password</label>
                                            <input type="password" id="confirmPassword" placeholder="Confirm new password">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Settings Panel -->
                    <div class="panel-view" data-panel="settings">
                        <div class="dashboard-section">
                            <h2 class="section-title">
                                <i class="fas fa-cog"></i> System Settings
                            </h2>
                            <div class="config-wrap">
                                <div class="config-card">
                                    <div class="config-head">General</div>
                                    <div class="config-body">
                                        <div class="config-field">
                                            <label>Site Name</label>
                                            <input type="text" id="siteName" value="<?php echo htmlspecialchars($system_settings['site_name']); ?>">
                                        </div>
                                        <div class="config-field">
                                            <label>Contact Email</label>
                                            <input type="email" id="contactEmail" value="<?php echo htmlspecialchars($system_settings['contact_email']); ?>">
                                        </div>
                                        <div class="config-field">
                                            <label>Support Phone</label>
                                            <input type="tel" id="supportPhone" value="<?php echo htmlspecialchars($system_settings['support_phone']); ?>">
                                        </div>
                                        <div class="config-field">
                                            <label>Enable Maintenance Mode</label>
                                            <div style="display:flex;align-items:center;gap:10px;">
                                                <input type="checkbox" id="maintenanceMode" style="width:18px;height:18px;cursor:pointer;" <?php echo $system_settings['maintenance_mode'] === '1' ? 'checked' : ''; ?>>
                                                <span style="color:#666;font-size:13px;">Users will see maintenance notice when enabled.</span>
                                            </div>
                                        </div>
                                        <div class="config-actions">
                                            <button id="maintenanceToggleBtn" onclick="toggleMaintenanceMode()" style="padding:10px 20px;background:#6b5738;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600;">Enable Maintenance</button>
                                            <button id="saveSettingsBtn" onclick="saveSystemSettings()" style="padding:10px 20px;background:#d4a574;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600;">Save Settings</button>
                                        </div>
                                    </div>
                                </div>
                                <div class="config-card">
                                    <div class="config-head">Database Backup</div>
                                    <div class="config-body">
                                        <p style="font-size:13px;color:#666;margin:0;">Create a secure backup of your database for recovery purposes.</p>
                                        <div class="config-actions" style="justify-content:flex-start;">
                                            <button id="backupBtn" onclick="createDatabaseBackup()" style="padding:10px 20px;background:#666;color:#fff;border:none;border-radius:8px;cursor:pointer;font-weight:600;">Create Backup</button>
                                        </div>
                                        <div id="backupStatus" style="display:none;padding:10px;border-radius:6px;font-size:14px;"></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div> <!-- .panel-views -->
            </div> <!-- .panels-container -->

        </div>

    </div>

    <script src="assets/js/vendor/jquery-3.7.1.min.js"></script>
    <script src="assets/js/bootstrap.min.js"></script>
    <script>
        // Panels nav: click to show panels. On touch devices, also respond to touchstart.
        (function(){
            const nav = document.querySelector('.panel-nav');
            if (!nav) return;
            const navItems = nav.querySelectorAll('li');
            const views = document.querySelectorAll('.panel-view');
            const navToggleBtn = document.getElementById('navToggleBtn');
            const panelNavOverlay = document.getElementById('panelNavOverlay');

            function closeNav() {
                document.body.classList.remove('nav-open');
            }

            function openNav() {
                document.body.classList.add('nav-open');
            }

            function showPanel(name) {
                views.forEach(v => v.classList.toggle('active', v.getAttribute('data-panel') === name));
                navItems.forEach(i => i.classList.toggle('active', i.getAttribute('data-target') === name));
                if (window.innerWidth <= 992) {
                    closeNav();
                }
            }

            const isTouch = ('ontouchstart' in window) || navigator.maxTouchPoints > 0;

            navItems.forEach(item => {
                const target = item.getAttribute('data-target');
                item.addEventListener('click', () => showPanel(target));
                item.addEventListener('keydown', (e) => {
                    if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); showPanel(target); }
                });
                if (isTouch) {
                    item.addEventListener('touchstart', (e) => { e.preventDefault(); showPanel(target); });
                }
            });

            if (navToggleBtn) {
                navToggleBtn.addEventListener('click', () => {
                    if (document.body.classList.contains('nav-open')) {
                        closeNav();
                    } else {
                        openNav();
                    }
                });
            }

            if (panelNavOverlay) {
                panelNavOverlay.addEventListener('click', closeNav);
            }

            window.addEventListener('resize', () => {
                if (window.innerWidth > 992) {
                    closeNav();
                }
            });
        })();

        // Filter orders by status
        document.getElementById('statusFilter').addEventListener('change', function() {
            const selectedStatus = this.value;
            const rows = document.querySelectorAll('.order-row');

            rows.forEach(row => {
                if (selectedStatus === '' || row.getAttribute('data-status') === selectedStatus) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        });

        // Update order status
        function updateStatus(orderId) {
            const statusModal = document.createElement('div');
            statusModal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; padding: 30px; border-radius: 10px; width: 90%; max-width: 400px; box-shadow: 0 10px 40px rgba(0,0,0,0.3);">
                        <h3 style="margin-top: 0; color: #333;">Update Order Status</h3>
                        <select id="newStatus" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; margin-bottom: 20px; font-size: 14px;">
                            <option value="">Select new status</option>
                            <option value="pending">Pending</option>
                            <option value="processing">Processing</option>
                            <option value="shipped">Shipped</option>
                            <option value="delivered">Delivered</option>
                            <option value="cancelled">Cancelled</option>
                        </select>
                        <div style="display: flex; gap: 10px;">
                            <button onclick="confirmUpdateStatus(${orderId}, this.parentElement.parentElement.parentElement)" style="flex: 1; padding: 10px; background: #d4a574; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Update</button>
                            <button onclick="this.parentElement.parentElement.parentElement.remove()" style="flex: 1; padding: 10px; background: #ddd; color: #333; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(statusModal);
            document.getElementById('newStatus').focus();
        }

        function confirmUpdateStatus(orderId, modalElement) {
            const status = document.getElementById('newStatus').value;
            
            if (!status) {
                alert('Please select a status');
                return;
            }

            const formData = new FormData();
            formData.append('order_id', orderId);
            formData.append('status', status);

            fetch('api/update-order-status.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Order status updated successfully!');
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
                modalElement.remove();
            })
            .catch(error => {
                alert('Error updating order status');
                console.error('Error:', error);
                modalElement.remove();
            });
        }

        // Delete consultation
        function deleteConsultation(consultationId) {
            if (confirm('Are you sure you want to delete this consultation request? This action cannot be undone.')) {
                const formData = new FormData();
                formData.append('consultation_id', consultationId);

                fetch('api/delete-consultation.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Consultation deleted successfully!');
                        location.reload();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    alert('Error deleting consultation');
                    console.error('Error:', error);
                });
            }
        }

        // Real-time Notification System
        let notificationCheckInterval;
        let lastNotificationCheck = new Date().toISOString();

        function initializeNotifications() {
            const bell = document.getElementById('notificationBell');
            const panel = document.getElementById('notificationPanel');

            if (bell) {
                bell.addEventListener('click', (e) => {
                    e.stopPropagation();
                    panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
                    if (panel.style.display === 'block') {
                        fetchNotifications();
                    }
                });

                // Close panel when clicking outside
                document.addEventListener('click', (e) => {
                    if (!e.target.closest('.notification-bell-container')) {
                        panel.style.display = 'none';
                    }
                });
            }

            // Start polling for new consultations
            startConsultationPolling();

            // Start notification polling
            startNotificationPolling();
        }

        function startNotificationPolling() {
            // Initial fetch
            fetchNotifications();

            // Poll every 10 seconds
            notificationCheckInterval = setInterval(fetchNotifications, 10000);
        }

        function fetchNotifications() {
            fetch('api/get-admin-notifications.php?action=get')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateNotificationUI(data.notifications, data.unread_count);
                    }
                })
                .catch(error => console.error('Error fetching notifications:', error));
        }

        function updateNotificationUI(notifications, unreadCount) {
            const badge = document.getElementById('notificationBadge');
            const list = document.getElementById('notificationList');

            if (unreadCount > 0) {
                badge.textContent = unreadCount;
                badge.style.display = 'flex';
            } else {
                badge.style.display = 'none';
            }

            if (notifications.length === 0) {
                list.innerHTML = '<p style="padding: 20px; text-align: center; color: #999;">No notifications</p>';
                return;
            }

            let html = '';
            notifications.forEach(notif => {
                const iconClass = notif.type === 'approval' ? 'approval' : 'decline';
                const icon = notif.type === 'approval' ? 'fa-check-circle' : 'fa-times-circle';

                html += `
                    <div class="notification-item ${notif.status === 'unread' ? 'unread' : ''}">
                        <div class="notification-icon ${iconClass}">
                            <i class="fas ${icon}"></i>
                        </div>
                        <div class="notification-content">
                            <div class="notification-message">${notif.message}</div>
                            <div class="notification-time">${notif.time_ago}</div>
                        </div>
                    </div>
                `;
            });

            list.innerHTML = html;

            // Add click handlers to mark as read
            list.querySelectorAll('.notification-item').forEach((item, index) => {
                if (notifications[index].status === 'unread') {
                    item.addEventListener('click', () => {
                        markNotificationAsRead(notifications[index].id);
                    });
                }
            });
        }

        function markNotificationAsRead(notificationId) {
            const formData = new FormData();
            formData.append('notification_id', notificationId);

            fetch('api/get-admin-notifications.php?action=mark_read', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        fetchNotifications();
                    }
                })
                .catch(error => console.error('Error marking notification as read:', error));
        }

        function markAllNotificationsAsRead() {
            fetch('api/get-admin-notifications.php?action=mark_all_read', {
                method: 'POST'
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        fetchNotifications();
                    }
                })
                .catch(error => console.error('Error marking all notifications as read:', error));
        }

        function startConsultationPolling() {
            // Poll every 5 seconds for new consultations
            setInterval(() => {
                fetch('api/get-new-consultations.php?last_check=' + encodeURIComponent(lastNotificationCheck))
                    .then(response => response.json())
                    .then(data => {
                        if (data.success && data.total_count > 0) {
                            lastNotificationCheck = data.timestamp;

                            if (data.new_count > 0) {
                                showBrowserNotification('New Consultation Request', `${data.new_count} new consultation request(s) received!`);
                            }

                            if (data.updated_count > 0) {
                                showBrowserNotification('Consultation Updated', `${data.updated_count} consultation(s) status changed!`);
                            }

                            // Highlight consultation tab if there are new items
                            if (data.new_count > 0) {
                                const consultTab = document.querySelector('[data-target="consultations"]');
                                if (consultTab) {
                                    consultTab.style.animation = 'pulse 1s infinite';
                                }
                            }
                        }
                    })
                    .catch(error => console.error('Error polling consultations:', error));
            }, 5000);
        }

        function showBrowserNotification(title, message) {
            // Only show browser notification if permitted
            if ('Notification' in window && Notification.permission === 'granted') {
                new Notification(title, {
                    icon: 'favicon.ico',
                    badge: 'favicon.ico',
                    body: message,
                    tag: 'admin-consultation',
                    requireInteraction: false
                });
            }
        }

        // Request notification permission on page load
        function requestNotificationPermission() {
            if ('Notification' in window && Notification.permission === 'default') {
                Notification.requestPermission();
            }
        }

        // Approve consultation
        function approveConsultation(consultationId, email, name) {
            const sendEmail = document.getElementById('sendEmailToggle').checked;
            const emailMsg = sendEmail ? 'An approval email will be sent to ' + email + '.' : 'No email will be sent.';
            
            if (confirm(`Are you sure you want to approve this consultation request for ${name}?\n\n${emailMsg}`)) {
                const formData = new FormData();
                formData.append('consultation_id', consultationId);
                formData.append('send_email', sendEmail ? '1' : '0');

                fetch('api/approve-consultation.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    console.log('Response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Response data:', data);
                    if (data.success) {
                        alert(data.message || 'Consultation approved successfully');
                        showBrowserNotification('Consultation Approved', `Consultation updated for ${name}`);
                        location.reload();
                    } else {
                        alert('Error: ' + (data.message || 'Unknown error'));
                    }
                })
                .catch(error => {
                    console.error('Fetch error:', error);
                    alert('Error approving consultation: ' + error.message);
                });
            }
        }

        // Decline consultation
        function declineConsultation(consultationId, email, name) {
            const sendEmail = document.getElementById('sendEmailToggle').checked;
            const emailMsg = sendEmail ? 'A decline email will be sent to ' + email + '.' : 'No email will be sent.';
            
            if (confirm(`Are you sure you want to decline this consultation request for ${name}?\n\n${emailMsg}`)) {
                const formData = new FormData();
                formData.append('consultation_id', consultationId);
                formData.append('send_email', sendEmail ? '1' : '0');

                fetch('api/decline-consultation.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    console.log('Response status:', response.status);
                    return response.json();
                })
                .then(data => {
                    console.log('Response data:', data);
                    if (data.success) {
                        alert(data.message || 'Consultation declined successfully');
                        location.reload();
                    } else {
                        alert('Error: ' + (data.message || 'Unknown error'));
                    }
                })
                .catch(error => {
                    console.error('Fetch error:', error);
                    alert('Error declining consultation: ' + error.message);
                });
            }
        }

        function closeServiceBookingModal() {
            const modal = document.querySelector('.service-booking-modal-overlay');
            if (modal) {
                if (modal._escapeHandler) {
                    document.removeEventListener('keydown', modal._escapeHandler);
                }
                modal.remove();
            }
            document.body.classList.remove('service-booking-modal-open');
        }

        function setupServiceBookingModal(modal) {
            modal.addEventListener('click', function(event) {
                if (event.target === modal) {
                    closeServiceBookingModal();
                }
            });

            const handleEscape = function(event) {
                if (event.key === 'Escape') {
                    closeServiceBookingModal();
                }
            };

            modal._escapeHandler = handleEscape;
            document.addEventListener('keydown', handleEscape);
        }

        function viewServiceBookingDetails(booking) {
            closeServiceBookingModal();

            const escapeHtml = (value) => String(value ?? '')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#39;');

            const createdAt = booking.created_at ? new Date(booking.created_at) : null;
            const preferredDate = booking.preferred_date ? new Date(booking.preferred_date) : null;
            const createdAtText = createdAt && !isNaN(createdAt) ? createdAt.toLocaleString('en-US', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            }) : 'N/A';
            const preferredDateText = preferredDate && !isNaN(preferredDate) ? preferredDate.toLocaleDateString('en-US', {
                year: 'numeric',
                month: 'long',
                day: 'numeric'
            }) : 'Not selected';
            const fullAddress = [booking.address, booking.city, booking.pincode].filter(Boolean).join(', ') || 'Not provided';
            const areaText = Number(booking.area_sqft) > 0 ? `${booking.area_sqft} sq ft` : 'Not specified';
            const preferredTimeText = booking.preferred_time || 'Flexible';
            const budgetText = booking.budget_range || 'Not specified';
            const notesText = booking.notes || 'No additional notes shared for this booking.';
            const serviceText = booking.service_name || 'Custom Service';
            const statusText = booking.status || 'Pending';
            const customerName = booking.customer_name || 'N/A';
            const customerEmail = booking.customer_email || 'N/A';
            const customerPhone = booking.customer_phone || 'N/A';
            const safeMailto = booking.customer_email ? `mailto:${encodeURIComponent(booking.customer_email)}` : 'javascript:void(0)';

            const modal = document.createElement('div');
            modal.className = 'service-booking-modal-overlay';
            modal.setAttribute('style', [
                'position:fixed',
                'inset:0',
                'width:100vw',
                'height:100vh',
                'padding:clamp(12px,3vw,28px)',
                'background:rgba(15,23,42,0.72)',
                'display:flex',
                'align-items:center',
                'justify-content:center',
                'overflow-y:auto',
                'z-index:100000',
                'box-sizing:border-box'
            ].join(';'));

            modal.innerHTML = `
                <div role="dialog" aria-modal="true" aria-labelledby="serviceBookingTitle" style="position:relative;background:#ffffff;border-radius:20px;box-shadow:0 24px 80px rgba(15,23,42,0.28);width:min(100%,860px);max-height:min(90vh,960px);margin:auto;display:flex;flex-direction:column;overflow:hidden;">
                    <div style="display:flex;align-items:center;justify-content:space-between;gap:16px;padding:clamp(18px,3vw,26px);border-bottom:1px solid #e5e7eb;background:linear-gradient(135deg,#fffaf4 0%,#ffffff 100%);">
                        <div style="display:flex;flex-direction:column;gap:6px;min-width:0;">
                            <h3 id="serviceBookingTitle" style="margin:0;font-size:clamp(20px,2vw,28px);color:#1f2937;display:flex;align-items:center;gap:10px;flex-wrap:wrap;"><i class="fas fa-calendar-check" style="color:#d4a574;font-size:24px;"></i> Service Booking Details</h3>
                            <p style="margin:0;color:#6b7280;font-size:13px;">Booking #${escapeHtml(booking.id)} for ${escapeHtml(serviceText)}</p>
                        </div>
                        <button type="button" onclick="closeServiceBookingModal()" aria-label="Close booking details" style="background:none;border:none;font-size:24px;color:#666;cursor:pointer;padding:0;width:36px;height:36px;display:flex;align-items:center;justify-content:center;border-radius:50%;">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>

                    <div style="flex:1;overflow-y:auto;padding:clamp(18px,3vw,28px);background:#ffffff;">
                        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;margin-bottom:22px;">
                            <div style="padding:16px 18px;border:1px solid #eceff3;border-radius:14px;background:#f9fafb;">
                                <div style="font-size:12px;font-weight:700;color:#7b6a55;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px;">Status</div>
                                <div style="font-size:18px;font-weight:800;color:#1f2937;">${escapeHtml(statusText)}</div>
                            </div>
                            <div style="padding:16px 18px;border:1px solid #eceff3;border-radius:14px;background:#f9fafb;">
                                <div style="font-size:12px;font-weight:700;color:#7b6a55;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px;">Preferred Date</div>
                                <div style="font-size:18px;font-weight:800;color:#1f2937;">${escapeHtml(preferredDateText)}</div>
                            </div>
                            <div style="padding:16px 18px;border:1px solid #eceff3;border-radius:14px;background:#f9fafb;">
                                <div style="font-size:12px;font-weight:700;color:#7b6a55;text-transform:uppercase;letter-spacing:.5px;margin-bottom:8px;">Area / Budget</div>
                                <div style="font-size:18px;font-weight:800;color:#1f2937;">${escapeHtml(areaText)}</div>
                                <div style="color:#6b7280;font-size:13px;margin-top:6px;">${escapeHtml(budgetText)}</div>
                            </div>
                        </div>

                        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:16px;">
                            <div style="padding:18px;border:1px solid #eceff3;border-radius:16px;background:#ffffff;">
                                <h4 style="font-size:14px;font-weight:700;color:#333;text-transform:uppercase;letter-spacing:.5px;margin:0 0 16px 0;padding-bottom:12px;border-bottom:2px solid #d4a574;">Customer</h4>
                                <div style="display:grid;gap:14px;">
                                    <div><div style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px;">Name</div><div style="font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">${escapeHtml(customerName)}</div></div>
                                    <div><div style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px;">Email</div><div style="font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">${escapeHtml(customerEmail)}</div></div>
                                    <div><div style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px;">Phone</div><div style="font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">${escapeHtml(customerPhone)}</div></div>
                                </div>
                            </div>

                            <div style="padding:18px;border:1px solid #eceff3;border-radius:16px;background:#ffffff;">
                                <h4 style="font-size:14px;font-weight:700;color:#333;text-transform:uppercase;letter-spacing:.5px;margin:0 0 16px 0;padding-bottom:12px;border-bottom:2px solid #d4a574;">Booking Info</h4>
                                <div style="display:grid;gap:14px;">
                                    <div><div style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px;">Service</div><div style="font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">${escapeHtml(serviceText)}</div></div>
                                    <div><div style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px;">Preferred Time</div><div style="font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">${escapeHtml(preferredTimeText)}</div></div>
                                    <div><div style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;margin-bottom:6px;">Booked On</div><div style="font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">${escapeHtml(createdAtText)}</div></div>
                                </div>
                            </div>

                            <div style="padding:18px;border:1px solid #eceff3;border-radius:16px;background:#ffffff;grid-column:1 / -1;">
                                <h4 style="font-size:14px;font-weight:700;color:#333;text-transform:uppercase;letter-spacing:.5px;margin:0 0 16px 0;padding-bottom:12px;border-bottom:2px solid #d4a574;">Project Address</h4>
                                <div style="font-size:15px;color:#333;line-height:1.7;overflow-wrap:anywhere;">${escapeHtml(fullAddress)}</div>
                            </div>

                            <div style="padding:18px;border:1px solid #eceff3;border-radius:16px;background:#ffffff;grid-column:1 / -1;">
                                <h4 style="font-size:14px;font-weight:700;color:#333;text-transform:uppercase;letter-spacing:.5px;margin:0 0 16px 0;padding-bottom:12px;border-bottom:2px solid #d4a574;">Customer Notes</h4>
                                <div style="font-size:15px;color:#333;line-height:1.7;white-space:pre-wrap;overflow-wrap:anywhere;">${escapeHtml(notesText)}</div>
                            </div>
                        </div>
                    </div>

                    <div style="display:flex;gap:12px;justify-content:flex-end;flex-wrap:wrap;padding:clamp(16px,2.5vw,24px);border-top:1px solid #e5e7eb;background:#f8fafc;">
                        <a class="btn-action btn-update" href="${safeMailto}" style="min-width:132px;text-align:center;">Email</a>
                        <button class="btn-action btn-view" type="button" onclick="closeServiceBookingModal()" style="min-width:132px;">Close</button>
                    </div>
                </div>
            `;

            document.body.classList.add('service-booking-modal-open');
            document.body.appendChild(modal);
            setupServiceBookingModal(modal);

            if (window.innerWidth <= 600) {
                const modalCard = modal.firstElementChild;
                if (modalCard) {
                    modal.style.alignItems = 'flex-end';
                    modalCard.style.width = '100%';
                    modalCard.style.maxHeight = '92vh';
                    modalCard.style.borderRadius = '18px 18px 0 0';
                }
            }
        }

        function closeUserDetailsModal() {
            const modal = document.querySelector('.user-details-modal-overlay');
            if (modal) {
                if (modal._escapeHandler) {
                    document.removeEventListener('keydown', modal._escapeHandler);
                }
                modal.remove();
            }
            document.body.classList.remove('user-modal-open');
        }

        function setupUserDetailsModal(modal) {
            modal.addEventListener('click', function(event) {
                if (event.target === modal) {
                    closeUserDetailsModal();
                }
            });

            const handleEscape = function(event) {
                if (event.key === 'Escape') {
                    closeUserDetailsModal();
                }
            };

            modal._escapeHandler = handleEscape;
            document.addEventListener('keydown', handleEscape);
        }

        // View user details modal
        function viewUserDetailsModal(userId) {
            closeUserDetailsModal();

            // Fetch user details from server
            fetch('api/get-user-details.php?user_id=' + userId)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.user) {
                        const user = data.user;
                        const joinDate = new Date(user.created_at);
                        const joinDateFormatted = joinDate.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
                        const joinTimeFormatted = joinDate.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
                        const userRole = (user.role || 'customer').toString().trim();
                        const roleLabel = userRole.charAt(0).toUpperCase() + userRole.slice(1).toLowerCase();
                        
                        const modal = document.createElement('div');
                        modal.className = 'user-details-modal-overlay';
                        modal.setAttribute('style', [
                            'position:fixed',
                            'inset:0',
                            'width:100vw',
                            'height:100vh',
                            'padding:clamp(12px,3vw,28px)',
                            'background:rgba(15,23,42,0.72)',
                            'display:flex',
                            'align-items:center',
                            'justify-content:center',
                            'overflow-y:auto',
                            'z-index:100000',
                            'box-sizing:border-box'
                        ].join(';'));
                        modal.innerHTML = `
                            <div class="user-details-modal" role="dialog" aria-modal="true" aria-labelledby="userDetailsTitle" style="position:relative;background:#ffffff;border-radius:20px;box-shadow:0 24px 80px rgba(15,23,42,0.28);width:min(100%,760px);max-height:min(88vh,920px);margin:auto;display:flex;flex-direction:column;overflow:hidden;">
                                <div class="user-modal-header" style="display:flex;align-items:center;justify-content:space-between;gap:16px;padding:clamp(18px,3vw,26px);border-bottom:1px solid #e5e7eb;background:linear-gradient(135deg,#fffaf4 0%,#ffffff 100%);">
                                    <h3 id="userDetailsTitle" style="margin:0;font-size:clamp(20px,2vw,28px);color:#1f2937;display:flex;align-items:center;gap:10px;flex-wrap:wrap;"><i class="fas fa-user-circle" style="color:#d4a574;font-size:24px;"></i> User Details</h3>
                                    <button class="modal-close-btn" type="button" onclick="closeUserDetailsModal()" aria-label="Close user details" style="background:none;border:none;font-size:24px;color:#666;cursor:pointer;padding:0;width:36px;height:36px;display:flex;align-items:center;justify-content:center;border-radius:50%;">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                                
                                <div class="user-modal-body" style="flex:1;overflow-y:auto;padding:clamp(18px,3vw,28px);background:#ffffff;">
                                    <div class="detail-section" style="margin-bottom:28px;">
                                        <h4 style="font-size:14px;font-weight:700;color:#333;text-transform:uppercase;letter-spacing:.5px;margin:0 0 16px 0;padding-bottom:12px;border-bottom:2px solid #d4a574;">Account Information</h4>
                                        <div class="detail-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;">
                                            <div class="detail-item" style="display:flex;flex-direction:column;gap:6px;padding:16px 18px;border:1px solid #eceff3;border-radius:14px;background:#f9fafb;min-width:0;">
                                                <label style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;">User ID</label>
                                                <p style="margin:0;font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">#${user.id}</p>
                                            </div>
                                            <div class="detail-item" style="display:flex;flex-direction:column;gap:6px;padding:16px 18px;border:1px solid #eceff3;border-radius:14px;background:#f9fafb;min-width:0;">
                                                <label style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;">Email Address</label>
                                                <p style="margin:0;font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">${user.email || 'N/A'}</p>
                                            </div>
                                            <div class="detail-item" style="display:flex;flex-direction:column;gap:6px;padding:16px 18px;border:1px solid #eceff3;border-radius:14px;background:#f9fafb;min-width:0;">
                                                <label style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;">Phone Number</label>
                                                <p style="margin:0;font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">${user.phone || 'N/A'}</p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="detail-section" style="margin-bottom:28px;">
                                        <h4 style="font-size:14px;font-weight:700;color:#333;text-transform:uppercase;letter-spacing:.5px;margin:0 0 16px 0;padding-bottom:12px;border-bottom:2px solid #d4a574;">Account Type</h4>
                                        <div class="detail-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;">
                                            <div class="detail-item" style="display:flex;flex-direction:column;gap:6px;padding:16px 18px;border:1px solid #eceff3;border-radius:14px;background:#f9fafb;min-width:0;">
                                                <label style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;">User Role</label>
                                                <p style="margin:0;font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">
                                                    <span style="background:#dcfce7;color:#166534;border:1px solid #bbf7d0;padding:6px 14px;border-radius:999px;font-weight:600;display:inline-block;font-size:12px;">${roleLabel}</span>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="detail-section" style="margin-bottom:0;">
                                        <h4 style="font-size:14px;font-weight:700;color:#333;text-transform:uppercase;letter-spacing:.5px;margin:0 0 16px 0;padding-bottom:12px;border-bottom:2px solid #d4a574;">Registration Details</h4>
                                        <div class="detail-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:16px;">
                                            <div class="detail-item" style="display:flex;flex-direction:column;gap:6px;padding:16px 18px;border:1px solid #eceff3;border-radius:14px;background:#f9fafb;min-width:0;">
                                                <label style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;">Registration Date</label>
                                                <p style="margin:0;font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">${joinDateFormatted}</p>
                                            </div>
                                            <div class="detail-item" style="display:flex;flex-direction:column;gap:6px;padding:16px 18px;border:1px solid #eceff3;border-radius:14px;background:#f9fafb;min-width:0;">
                                                <label style="font-size:12px;font-weight:600;color:#999;text-transform:uppercase;letter-spacing:.5px;">Registration Time</label>
                                                <p style="margin:0;font-size:15px;color:#333;line-height:1.6;overflow-wrap:anywhere;">${joinTimeFormatted}</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="user-modal-footer" style="display:flex;gap:12px;justify-content:flex-end;flex-wrap:wrap;padding:clamp(16px,2.5vw,24px);border-top:1px solid #e5e7eb;background:#f8fafc;">
                                    <button class="btn-action btn-delete" type="button" onclick="confirmDeleteUser(${user.id})" style="min-width:132px;">Delete User</button>
                                    <button class="btn-action btn-view" type="button" onclick="closeUserDetailsModal()" style="min-width:132px;">Close</button>
                                </div>
                            </div>
                        `;
                        document.body.classList.add('user-modal-open');
                        document.body.appendChild(modal);
                        setupUserDetailsModal(modal);

                        if (window.innerWidth <= 600) {
                            const modalCard = modal.querySelector('.user-details-modal');
                            if (modalCard) {
                                modal.style.alignItems = 'flex-end';
                                modalCard.style.width = '100%';
                                modalCard.style.maxHeight = '92vh';
                                modalCard.style.borderRadius = '18px 18px 0 0';
                            }
                        }
                    } else {
                        alert('Error: Unable to load user details');
                    }
                })
                .catch(error => {
                    alert('Error fetching user details');
                    console.error('Error:', error);
                });
        }

        // Confirm delete user
        function confirmDeleteUser(userId) {
            if (confirm('Are you sure you want to delete this user? This action cannot be undone.')) {
                const formData = new FormData();
                formData.append('user_id', userId);

                fetch('api/delete-user.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('User deleted successfully!');
                        location.reload();
                    } else {
                        alert('Error: ' + (data.message || 'Unable to delete user'));
                    }
                })
                .catch(error => {
                    alert('Error deleting user');
                    console.error('Error:', error);
                });
            }
        }

        // View user details
        function viewUserDetails(userId, name, email, phone, role) {
            viewUserDetailsModal(userId);
        }

        // Delete user
        function deleteUser(userId) {
            confirmDeleteUser(userId);
        }

        // Delete product
        function deleteProduct(productId) {
            if (!confirm('Are you sure you want to delete product #' + productId + '? This cannot be undone.')) return;

            const formData = new FormData();
            formData.append('product_id', productId);

            fetch('admin-delete-product.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Product deleted successfully');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unable to delete product'));
                }
            })
            .catch(error => {
                console.error('Delete error:', error);
                alert('Error deleting product');
            });
        }

        // Gallery management functions
        function openAddGalleryModal() {
            const modal = document.createElement('div');
            modal.id = 'galleryModal';
            modal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; padding: 30px; border-radius: 10px; width: 90%; max-width: 500px; box-shadow: 0 10px 40px rgba(0,0,0,0.3);">
                        <h3 style="margin-top: 0; color: #333;">Add Gallery Item</h3>
                        <form id="galleryForm" enctype="multipart/form-data">
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Title</label>
                                <input type="text" id="galleryTitle" placeholder="Gallery title" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Category</label>
                                <select id="galleryCategory" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                    <option value="">Select Category</option>
                                    <option value="Interior">Interior</option>
                                    <option value="Architecture">Architecture</option>
                                    <option value="Building">Building</option>
                                    <option value="Exterior">Exterior</option>
                                    <option value="Shape">Shape</option>
                                </select>
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Upload Image</label>
                                <input type="file" id="galleryImage" accept="image/*" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                <p style="margin: 5px 0 0 0; font-size: 12px; color: #999;">Supported: JPG, PNG, GIF, WebP (Max 5MB)</p>
                            </div>
                            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                                <button type="button" onclick="document.getElementById('galleryModal').remove()" style="padding: 10px 20px; background: #ddd; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                                <button type="button" onclick="submitAddGallery()" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Add</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            document.getElementById('galleryTitle').focus();
        }

        function openEditGalleryModal(id, title, category, image) {
            const modal = document.createElement('div');
            modal.id = 'galleryEditModal';
            modal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; padding: 30px; border-radius: 10px; width: 90%; max-width: 500px; box-shadow: 0 10px 40px rgba(0,0,0,0.3);">
                        <h3 style="margin-top: 0; color: #333;">Edit Gallery Item</h3>
                        <form id="galleryEditForm" enctype="multipart/form-data">
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Title</label>
                                <input type="text" id="editGalleryTitle" value="${title}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Category</label>
                                <select id="editGalleryCategory" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                    <option value="Interior" ${category === 'Interior' ? 'selected' : ''}>Interior</option>
                                    <option value="Architecture" ${category === 'Architecture' ? 'selected' : ''}>Architecture</option>
                                    <option value="Building" ${category === 'Building' ? 'selected' : ''}>Building</option>
                                    <option value="Exterior" ${category === 'Exterior' ? 'selected' : ''}>Exterior</option>
                                    <option value="Shape" ${category === 'Shape' ? 'selected' : ''}>Shape</option>
                                </select>
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Current Image</label>
                                <img src="${image}" alt="Current" style="width: 100%; max-height: 150px; object-fit: cover; border-radius: 6px; margin-bottom: 10px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Upload New Image (Optional)</label>
                                <input type="file" id="editGalleryImage" accept="image/*" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                <p style="margin: 5px 0 0 0; font-size: 12px; color: #999;">Leave empty to keep current image</p>
                            </div>
                            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                                <button type="button" onclick="document.getElementById('galleryEditModal').remove()" style="padding: 10px 20px; background: #ddd; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                                <button type="button" onclick="submitEditGallery(${id})" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Update</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            document.getElementById('editGalleryTitle').focus();
        }

        function submitAddGallery() {
            const title = document.getElementById('galleryTitle').value.trim();
            const category = document.getElementById('galleryCategory').value.trim();
            const imageFile = document.getElementById('galleryImage').files[0];

            if (!title || !category || !imageFile) {
                alert('Please fill in all fields and select an image');
                return;
            }

            // Check file size (5MB max)
            if (imageFile.size > 5 * 1024 * 1024) {
                alert('Image size must be less than 5MB');
                return;
            }

            const formData = new FormData();
            formData.append('title', title);
            formData.append('category', category);
            formData.append('image', imageFile);

            fetch('admin-add-gallery.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Gallery item added successfully');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unable to add gallery item'));
                }
            })
            .catch(error => {
                console.error('Add error:', error);
                alert('Error adding gallery item');
            });
        }

        function submitEditGallery(id) {
            const title = document.getElementById('editGalleryTitle').value.trim();
            const category = document.getElementById('editGalleryCategory').value.trim();
            const imageFile = document.getElementById('editGalleryImage').files[0];

            if (!title || !category) {
                alert('Please fill in all required fields');
                return;
            }

            // Check file size if image is selected (5MB max)
            if (imageFile && imageFile.size > 5 * 1024 * 1024) {
                alert('Image size must be less than 5MB');
                return;
            }

            const formData = new FormData();
            formData.append('gallery_id', id);
            formData.append('title', title);
            formData.append('category', category);
            if (imageFile) {
                formData.append('image', imageFile);
            }

            fetch('admin-edit-gallery.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Gallery item updated successfully');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unable to update gallery item'));
                }
            })
            .catch(error => {
                console.error('Edit error:', error);
                alert('Error updating gallery item');
            });
        }

        function deleteGallery(id) {
            if (!confirm('Are you sure you want to delete this gallery item? This cannot be undone.')) return;

            const formData = new FormData();
            formData.append('gallery_id', id);

            fetch('admin-delete-gallery.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Gallery item deleted successfully');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unable to delete gallery item'));
                }
            })
            .catch(error => {
                console.error('Delete error:', error);
                alert('Error deleting gallery item');
            });
        }

        // Hero Slider Management Functions
        // Service Management Functions
        function addService() {
            const modal = document.createElement('div');
            modal.innerHTML = `
                <style>
                    .service-create-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.6);display:flex;align-items:center;justify-content:center;z-index:10000;padding:20px;overflow-y:auto}
                    .service-create-modal{background:#fff;padding:40px;border-radius:12px;width:100%;max-width:900px;box-shadow:0 20px 60px rgba(0,0,0,0.3);margin:auto}
                    @media (max-width: 992px){.service-create-modal{padding:24px;max-width:96%}}
                    @media (max-width: 768px){
                        .service-create-overlay{align-items:flex-start;padding:10px}
                        .service-create-modal{padding:16px;border-radius:10px}
                        .service-create-overlay div[style*="grid-template-columns: 1fr 1fr;"]{grid-template-columns:1fr !important;gap:10px !important}
                        .service-create-overlay div[style*="grid-template-columns: 1fr 1fr 1fr;"]{grid-template-columns:1fr !important;gap:10px !important}
                        .service-create-overlay .product-row{grid-template-columns:1fr !important;gap:10px !important}
                        .service-create-overlay .tool-row{grid-template-columns:1fr !important;gap:10px !important}
                        .service-create-overlay #uploadArea{padding:16px 12px !important}
                        .service-create-actions button{width:100%}
                    }
                </style>
                <div class="service-create-overlay" onclick="if(event.target === this) this.remove()">
                    <div class="service-create-modal">
                        <h3 style="margin-top: 0; color: #333; font-size: 28px;">Add New Service with Product Breakdown</h3>
                        
                        <!-- Basic Service Info -->
                        <div style="margin-bottom: 30px; padding-bottom: 30px; border-bottom: 2px solid #eee;">
                            <h4 style="color: #1b8a67; margin-bottom: 20px;">ÃƒÂ°Ã…Â¸Ã¢â‚¬Å“Ã¢â‚¬Â¹ Basic Service Information</h4>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 15px;">
                                <div>
                                    <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Service Title *</label>
                                    <input type="text" class="service-input" placeholder="e.g., Commercial Interiors" style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                                <div>
                                    <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Area (sqft) *</label>
                                    <input type="number" class="service-input" placeholder="e.g., 5000" style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                            </div>
                            <div>
                                <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Service Description *</label>
                                <textarea class="service-input" placeholder="Enter detailed service description..." style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px; min-height: 100px; resize: vertical;"></textarea>
                            </div>
                        </div>

                        <!-- Pricing Info -->
                        <div style="margin-bottom: 30px; padding-bottom: 30px; border-bottom: 2px solid #eee;">
                            <h4 style="color: #1b8a67; margin-bottom: 20px;">ÃƒÂ°Ã…Â¸Ã¢â‚¬â„¢Ã‚Â° Pricing Information</h4>
                            <div style="display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 20px;">
                                <div>
                                    <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Base Price ($) *</label>
                                    <input type="number" class="service-input" placeholder="5000" style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                                <div>
                                    <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Duration *</label>
                                    <input type="text" class="service-input" placeholder="e.g., 8-12 weeks" style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                                <div>
                                    <label style="display: block; margin-bottom: 8px; font-weight: 600; color: #333;">Status</label>
                                    <select class="service-input" style="width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                        <option>ACTIVE</option>
                                        <option>INACTIVE</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- Product Breakdown -->
                        <div style="margin-bottom: 30px; padding-bottom: 30px; border-bottom: 2px solid #eee;">
                            <h4 style="color: #1b8a67; margin-bottom: 20px;">ÃƒÂ°Ã…Â¸Ã¢â‚¬Å“Ã‚Â¦ Product Breakdown</h4>
                            <div class="products-container" style="margin-bottom: 15px;">
                                <div class="product-row" style="display: grid; grid-template-columns: 2fr 1fr 1fr auto auto; gap: 12px; margin-bottom: 12px;" data-spot-x="" data-spot-y="">
                                    <input type="text" placeholder="Product Name" class="product-name" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 13px;">
                                    <input type="number" placeholder="Cost ($)" class="product-cost" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 13px;">
                                    <input type="text" placeholder="Quantity" class="product-qty" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 13px;">
                                    <button type="button" class="btn-pick-spot" onclick="setAddSpotTarget(this)" style="padding: 10px 12px; background: #2f7de1; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">Pick Spot</button>
                                    <button type="button" onclick="removeProductRow(this)" style="padding: 10px 15px; background: #e74c3c; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">X</button>
                                </div>
                            </div>
                            <button type="button" onclick="addProductRow()" style="padding: 10px 20px; background: #1b8a67; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">+ Add Product</button>
                        </div>

                        <!-- Tools Used -->
                        <div style="margin-bottom: 30px; padding-bottom: 30px; border-bottom: 2px solid #eee;">
                            <h4 style="color: #1b8a67; margin-bottom: 20px;">ÃƒÂ°Ã…Â¸Ã¢â‚¬ÂºÃ‚Â ÃƒÂ¯Ã‚Â¸Ã‚Â Tools & Software Used</h4>
                            <div class="tools-container" style="margin-bottom: 15px;">
                                <div class="tool-row" style="display: grid; grid-template-columns: 1fr 2fr auto; gap: 12px; margin-bottom: 12px;">
                                    <input type="text" placeholder="Tool Name" class="tool-name" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 13px;">
                                    <input type="text" placeholder="Description" class="tool-desc" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 13px;">
                                    <button type="button" onclick="removeToolRow(this)" style="padding: 10px 15px; background: #e74c3c; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">ÃƒÂ¢Ã…â€œÃ¢â‚¬Â¢</button>
                                </div>
                            </div>
                            <button type="button" onclick="addToolRow()" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">+ Add Tool</button>
                        </div>

                        <!-- Image Upload -->
                        <div style="margin-bottom: 30px;">
                            <h4 style="color: #1b8a67; margin-bottom: 20px;">ÃƒÂ°Ã…Â¸Ã¢â‚¬â€œÃ‚Â¼ÃƒÂ¯Ã‚Â¸Ã‚Â Service Image</h4>
                            <div style="position: relative; border: 2px dashed #d4a574; border-radius: 6px; padding: 30px; text-align: center; background: #fafafa; cursor: pointer;" id="uploadArea">
                                <input type="file" id="newServiceImage" accept="image/*" style="display: none;">
                                <i class="fas fa-cloud-upload-alt" style="font-size: 32px; color: #d4a574; margin-bottom: 10px; display: block;"></i>
                                <p style="margin: 0; color: #333; font-weight: 600;">Click to upload or drag image here</p>
                                <small style="color: #999; display: block; margin-top: 5px;">Supported: JPG, PNG, GIF, WebP (Max 5MB)</small>
                                <div id="imagePreview" style="margin-top: 15px; display: none;">
                                    <div style="position: relative; display: inline-block; max-width: 100%;">
                                        <img id="previewImg" style="max-width: 100%; max-height: 240px; border-radius: 4px; cursor: crosshair;">
                                        <div id="addSpotLayer" style="position:absolute;inset:0;pointer-events:none;"></div>
                                    </div>
                                    <div id="addSpotHint" style="margin-top:8px;font-size:12px;color:#556;">Select a product row, then tap image to set spot</div>
                                </div>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="service-create-actions" style="display: flex; gap: 10px; justify-content: flex-end; flex-wrap: wrap;">
                            <button onclick="this.parentElement.parentElement.parentElement.remove()" style="padding: 12px 25px; background: #ddd; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 14px;">Cancel</button>
                            <button onclick="saveCompleteService()" style="padding: 12px 25px; background: #1b8a67; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; font-size: 14px;">Save Service</button>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            
            // Setup file upload handlers
            const fileInput = document.getElementById('newServiceImage');
            const uploadArea = document.getElementById('uploadArea');
            const previewImg = document.getElementById('previewImg');
            window.activeAddSpotRow = null;
            
            uploadArea.addEventListener('click', () => fileInput.click());
            if (previewImg) {
                previewImg.addEventListener('click', onAddImageClick);
            }
            
            fileInput.addEventListener('change', (e) => {
                handleImageSelect(e.target.files[0]);
            });
            
            uploadArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadArea.style.background = '#f0f0f0';
                uploadArea.style.borderColor = '#1b8a67';
            });
            
            uploadArea.addEventListener('dragleave', () => {
                uploadArea.style.background = '#fafafa';
                uploadArea.style.borderColor = '#d4a574';
            });
            
            uploadArea.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadArea.style.background = '#fafafa';
                uploadArea.style.borderColor = '#d4a574';
                if (e.dataTransfer.files.length) {
                    handleImageSelect(e.dataTransfer.files[0]);
                }
            });
        }

        function addProductRow() {
            const container = document.querySelector('.products-container');
            const newRow = document.createElement('div');
            newRow.className = 'product-row';
            newRow.dataset.spotX = '';
            newRow.dataset.spotY = '';
            newRow.style.cssText = 'display: grid; grid-template-columns: 2fr 1fr 1fr auto auto; gap: 12px; margin-bottom: 12px;';
            newRow.innerHTML = `
                <input type="text" placeholder="Product Name" class="product-name" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 13px;">
                <input type="number" placeholder="Cost ($)" class="product-cost" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 13px;">
                <input type="text" placeholder="Quantity" class="product-qty" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 13px;">
                <button type="button" class="btn-pick-spot" onclick="setAddSpotTarget(this)" style="padding: 10px 12px; background: #2f7de1; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">Pick Spot</button>
                <button type="button" onclick="removeProductRow(this)" style="padding: 10px 15px; background: #e74c3c; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">X</button>
            `;
            container.appendChild(newRow);
        }

        function removeProductRow(btn) {
            const row = btn.closest('.product-row');
            if (!row) return;
            if (window.activeAddSpotRow === row) {
                window.activeAddSpotRow = null;
            }
            row.remove();
            renderAddSpotMarkers();
        }

        function addToolRow() {
            const container = document.querySelector('.tools-container');
            const newRow = document.createElement('div');
            newRow.className = 'tool-row';
            newRow.style.cssText = 'display: grid; grid-template-columns: 1fr 2fr auto; gap: 12px; margin-bottom: 12px;';
            newRow.innerHTML = `
                <input type="text" placeholder="Tool Name" class="tool-name" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 13px;">
                <input type="text" placeholder="Description" class="tool-desc" style="padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 13px;">
                <button type="button" onclick="removeToolRow(this)" style="padding: 10px 15px; background: #e74c3c; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600;">ÃƒÂ¢Ã…â€œÃ¢â‚¬Â¢</button>
            `;
            container.appendChild(newRow);
        }

        function removeToolRow(btn) {
            btn.parentElement.remove();
        }

        function saveCompleteService() {
            // Collect basic info
            const inputs = document.querySelectorAll('.service-input');
            const title = inputs[0].value;
            const area = inputs[1].value;
            const description = inputs[2].value;
            const basePrice = inputs[3].value;
            const duration = inputs[4].value;
            const status = inputs[5].value;
            
            if (!title || !area || !description || !basePrice || !duration) {
                alert('Please fill in all required fields');
                return;
            }

            // Collect products
            const products = [];
            document.querySelectorAll('.product-row').forEach(row => {
                const name = row.querySelector('.product-name').value.trim();
                const cost = row.querySelector('.product-cost').value.trim();
                const qty = row.querySelector('.product-qty').value.trim();
                const x = row.dataset.spotX !== '' ? parseFloat(row.dataset.spotX) : null;
                const y = row.dataset.spotY !== '' ? parseFloat(row.dataset.spotY) : null;
                if (name && cost && qty) {
                    products.push({ name, cost: parseFloat(cost), qty, x, y });
                }
            });

            // Collect tools
            const tools = [];
            document.querySelectorAll('.tool-row').forEach(row => {
                const name = row.querySelector('.tool-name').value.trim();
                const desc = row.querySelector('.tool-desc').value.trim();
                if (name && desc) {
                    tools.push({ name, desc });
                }
            });

            // Prepare data
            const formData = new FormData();
            formData.append('action', 'add_service');
            formData.append('title', title);
            formData.append('area', area);
            formData.append('description', description);
            formData.append('basePrice', basePrice);
            formData.append('duration', duration);
            formData.append('status', status);
            formData.append('products', JSON.stringify(products));
            formData.append('tools', JSON.stringify(tools));

            const imageFile = document.getElementById('newServiceImage').file;
            if (imageFile) {
                formData.append('image', imageFile);
            }
            
            // Debug: log the data being sent
            console.log('Sending form data:', {
                title, area, description, basePrice, duration, status,
                productsCount: products.length,
                toolsCount: tools.length,
                hasImage: !!imageFile
            });

            // Show loading state
            const saveBtn = event.target;
            const originalText = saveBtn.textContent;
            saveBtn.textContent = 'ÃƒÂ°Ã…Â¸Ã¢â‚¬â„¢Ã‚Â¾ Saving...';
            saveBtn.disabled = true;

            // Send to API
            fetch('api/save-service.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json().then(data => ({ok: response.ok, data})))
            .then(result => {
                if (!result.ok) {
                    throw new Error(result.data.message || 'HTTP error, status = ' + result.data.status);
                }
                if (result.data.success) {
                    alert('ÃƒÂ¢Ã…â€œÃ¢â‚¬Å“ Service added successfully!');
                    // Close modal
                    const modal = saveBtn.closest('.service-create-overlay') || saveBtn.closest('div[style*="position: fixed"]');
                    if (modal) {
                        modal.remove();
                    }
                    // Reload the page to show new service
                    setTimeout(() => location.reload(), 500);
                } else {
                    throw new Error(result.data.message || 'Unknown error occurred');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('ÃƒÂ¢Ã‚ÂÃ…â€™ Error: ' + error.message);
                saveBtn.textContent = originalText;
                saveBtn.disabled = false;
            });
        }

        function handleImageSelect(file) {
            if (!file) return;
            
            // Validate file type
            if (!file.type.startsWith('image/')) {
                alert('Please select a valid image file');
                return;
            }
            
            // Validate file size (5MB)
            if (file.size > 5 * 1024 * 1024) {
                alert('Image size must be less than 5MB');
                return;
            }
            
            // Show preview
            const reader = new FileReader();
            reader.onload = (e) => {
                document.getElementById('previewImg').src = e.target.result;
                document.getElementById('imagePreview').style.display = 'block';
                renderAddSpotMarkers();
            };
            reader.readAsDataURL(file);
            
            // Store file for later upload
            document.getElementById('newServiceImage').file = file;
        }

        function setAddSpotTarget(btn) {
            const row = btn.closest('.product-row');
            if (!row) return;
            window.activeAddSpotRow = row;
            document.querySelectorAll('.product-row .btn-pick-spot').forEach((b) => {
                b.style.outline = 'none';
            });
            btn.style.outline = '2px solid #163f75';
            const hint = document.getElementById('addSpotHint');
            if (hint) {
                const name = row.querySelector('.product-name')?.value.trim() || 'selected product';
                hint.textContent = 'Tap image to set spot for: ' + name;
            }
        }

        function onAddImageClick(e) {
            if (!window.activeAddSpotRow) {
                const hint = document.getElementById('addSpotHint');
                if (hint) hint.textContent = 'Select a product row first, then tap image';
                return;
            }
            const rect = e.target.getBoundingClientRect();
            if (!rect.width || !rect.height) return;
            const x = ((e.clientX - rect.left) / rect.width) * 100;
            const y = ((e.clientY - rect.top) / rect.height) * 100;
            const row = window.activeAddSpotRow;
            row.dataset.spotX = Math.max(0, Math.min(100, x)).toFixed(2);
            row.dataset.spotY = Math.max(0, Math.min(100, y)).toFixed(2);

            const btn = row.querySelector('.btn-pick-spot');
            if (btn) {
                btn.textContent = `${row.dataset.spotX}%, ${row.dataset.spotY}%`;
                btn.style.background = '#1b8a67';
                btn.style.outline = 'none';
            }
            window.activeAddSpotRow = null;
            renderAddSpotMarkers();
        }

        function renderAddSpotMarkers() {
            const layer = document.getElementById('addSpotLayer');
            if (!layer) return;
            layer.innerHTML = '';
            document.querySelectorAll('.product-row').forEach((row, index) => {
                const x = parseFloat(row.dataset.spotX || '');
                const y = parseFloat(row.dataset.spotY || '');
                if (!Number.isFinite(x) || !Number.isFinite(y)) return;
                const dot = document.createElement('div');
                dot.style.cssText = 'position:absolute;left:' + x + '%;top:' + y + '%;transform:translate(-50%,-50%);width:14px;height:14px;border-radius:50%;background:#ff8f4c;border:2px solid #fff;box-shadow:0 0 0 1px rgba(0,0,0,.2)';
                dot.title = row.querySelector('.product-name')?.value.trim() || ('Product ' + (index + 1));
                layer.appendChild(dot);
            });
        }

        function saveNewService() {
            const title = document.getElementById('newServiceTitle').value;
            const imageFile = document.getElementById('newServiceImage').file;
            const link = document.getElementById('newServiceLink').value || '#';
            const description = document.getElementById('newServiceDesc').value;

            if (!title || !imageFile || !description) {
                alert('Please fill in all required fields (Title, Image, Description)');
                return;
            }

            const formData = new FormData();
            formData.append('action', 'add_service');
            formData.append('title', title);
            formData.append('image', imageFile);
            formData.append('link', link);
            formData.append('description', description);

            // Show loading indicator
            const addBtn = event.target;
            const originalText = addBtn.textContent;
            addBtn.textContent = 'Adding...';
            addBtn.disabled = true;

            fetch('api/upload-service-image.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Now save the service with the uploaded image path
                    const serviceData = new FormData();
                    serviceData.append('action', 'add_service');
                    serviceData.append('title', title);
                    serviceData.append('image', data.image_path);
                    serviceData.append('link', link);
                    serviceData.append('description', description);

                    return fetch('api/update-service.php', {
                        method: 'POST',
                        body: serviceData
                    });
                } else {
                    throw new Error(data.message || 'Failed to upload image');
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Service added successfully!');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unable to add service'));
                }
            })
            .catch(error => {
                alert('Error: ' + error.message);
                console.error('Error:', error);
                addBtn.textContent = originalText;
                addBtn.disabled = false;
            });
        }

        function editService(serviceId, serviceData) {
            const modal = document.createElement('div');
            modal.innerHTML = `
                <style>
                    .edit-service-modal-overlay {
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background: rgba(0,0,0,0.6);
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        z-index: 10000;
                        padding: 10px;
                        overflow-y: auto;
                    }

                    .edit-service-modal {
                        background: white;
                        border-radius: 12px;
                        width: 100%;
                        max-width: 900px;
                        max-height: 90vh;
                        overflow-y: auto;
                        box-shadow: 0 20px 60px rgba(0,0,0,0.3);
                        margin: auto;
                    }

                    .edit-service-header {
                        padding: 24px;
                        border-bottom: 2px solid #eee;
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        flex-wrap: wrap;
                        gap: 10px;
                    }

                    .edit-service-header h3 {
                        margin: 0;
                        color: #333;
                        font-size: 22px;
                    }

                    .close-btn {
                        background: #fff;
                        border: 1px solid #ddd;
                        border-radius: 50%;
                        width: 32px;
                        height: 32px;
                        cursor: pointer;
                        font-size: 18px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        transition: all 0.3s ease;
                    }

                    .close-btn:hover {
                        background: #f0f0f0;
                    }

                    .edit-service-content {
                        padding: 24px;
                    }

                    .edit-section {
                        margin-bottom: 30px;
                    }

                    .edit-section-title {
                        font-size: 18px;
                        font-weight: 700;
                        color: #1b8a67;
                        margin: 0 0 15px 0;
                        padding-bottom: 10px;
                        border-bottom: 2px solid #d4a574;
                    }

                    .form-group {
                        margin-bottom: 15px;
                    }

                    .form-group label {
                        display: block;
                        margin-bottom: 6px;
                        font-weight: 600;
                        color: #333;
                        font-size: 13px;
                    }

                    .form-group input,
                    .form-group textarea,
                    .form-group select {
                        width: 100%;
                        padding: 10px;
                        border: 1px solid #ddd;
                        border-radius: 6px;
                        box-sizing: border-box;
                        font-size: 14px;
                        font-family: inherit;
                    }

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

                    .form-row {
                        display: grid;
                        grid-template-columns: 1fr 1fr;
                        gap: 15px;
                    }

                    .products-list, .tools-list {
                        margin-top: 15px;
                        max-height: 300px;
                        overflow-y: auto;
                        border: 1px solid #eee;
                        border-radius: 6px;
                        padding: 12px;
                        background: #f9f8f6;
                    }

                    .list-item {
                        display: grid;
                        grid-template-columns: 1fr 1fr 1fr auto;
                        gap: 8px;
                        margin-bottom: 10px;
                        padding: 10px;
                        background: white;
                        border-radius: 4px;
                        border: 1px solid #eee;
                        align-items: center;
                        font-size: 13px;
                    }

                    .list-item >div:not(:last-child) {
                        word-break: break-word;
                    }

                    .remove-btn {
                        background: #e74c3c;
                        color: white;
                        border: none;
                        padding: 4px 8px;
                        border-radius: 4px;
                        cursor: pointer;
                        font-size: 12px;
                        transition: all 0.3s ease;
                    }

                    .remove-btn:hover {
                        background: #c0392b;
                    }

                    .add-btn {
                        background: #1b8a67;
                        color: white;
                        border: none;
                        padding: 8px 16px;
                        border-radius: 6px;
                        cursor: pointer;
                        font-weight: 600;
                        font-size: 13px;
                        transition: all 0.3s ease;
                    }

                    .add-btn:hover {
                        background: #2a5f4a;
                    }

                    .add-row-container {
                        display: grid;
                        grid-template-columns: 1fr 1fr 1fr auto;
                        gap: 8px;
                        margin-top: 10px;
                        margin-bottom: 10px;
                    }

                    .add-row-container input {
                        padding: 8px;
                        font-size: 13px;
                    }

                    .add-row-container button {
                        padding: 8px 12px;
                        font-size: 12px;
                    }

                    .edit-service-footer {
                        padding: 20px 24px;
                        border-top: 2px solid #eee;
                        display: flex;
                        gap: 10px;
                        justify-content: flex-end;
                        flex-wrap: wrap;
                    }

                    .btn-cancel {
                        background: #ddd;
                        color: #333;
                        border: none;
                        padding: 10px 20px;
                        border-radius: 6px;
                        cursor: pointer;
                        font-weight: 600;
                        font-size: 14px;
                        transition: all 0.3s ease;
                    }

                    .btn-cancel:hover {
                        background: #ccc;
                    }

                    .btn-save {
                        background: #1b8a67;
                        color: white;
                        border: none;
                        padding: 10px 25px;
                        border-radius: 6px;
                        cursor: pointer;
                        font-weight: 600;
                        font-size: 14px;
                        transition: all 0.3s ease;
                    }

                    .btn-save:hover {
                        background: #2a5f4a;
                    }

                    .tool-row input {
                        grid-column: span 2;
                    }

                    /* Tablet Responsive */
                    @media (max-width: 1024px) {
                        .edit-service-modal {
                            max-width: 95%;
                        }

                        .form-row {
                            grid-template-columns: 1fr;
                        }

                        .list-item {
                            grid-template-columns: 1fr auto;
                            gap: 8px;
                        }

                        .add-row-container {
                            grid-template-columns: 1fr auto;
                            gap: 8px;
                        }
                    }

                    /* Mobile Responsive */
                    @media (max-width: 768px) {
                        .edit-service-modal {
                            max-height: 95vh;
                            border-radius: 8px;
                        }

                        .edit-service-header {
                            padding: 16px;
                            justify-content: space-between;
                        }

                        .edit-service-header h3 {
                            font-size: 18px;
                            flex: 1;
                        }

                        .edit-service-content {
                            padding: 16px;
                        }

                        .edit-section {
                            margin-bottom: 20px;
                        }

                        .edit-section-title {
                            font-size: 16px;
                            margin: 0 0 12px 0;
                        }

                        .form-group {
                            margin-bottom: 12px;
                        }

                        .form-group label {
                            font-size: 12px;
                            margin-bottom: 5px;
                        }

                        .form-row {
                            gap: 10px;
                        }

                        .products-list, .tools-list {
                            max-height: 250px;
                            padding: 10px;
                        }

                        .list-item {
                            grid-template-columns: 1fr;
                            gap: 6px;
                            padding: 8px;
                            font-size: 12px;
                        }

                        .add-row-container {
                            grid-template-columns: 1fr;
                            gap: 6px;
                        }

                        .add-row-container input {
                            padding: 6px;
                            font-size: 12px;
                        }
                        
                        .add-row-container button {
                            width: 100%;
                        }

                        .edit-service-footer {
                            padding: 16px;
                            gap: 8px;
                        }

                        .btn-cancel, .btn-save {
                            padding: 8px 16px;
                            font-size: 13px;
                            flex: 1;
                        }
                    }

                    /* Extra Small Devices */
                    @media (max-width: 480px) {
                        .edit-service-modal {
                            margin: 10px;
                            max-height: calc(100vh - 20px);
                        }

                        .edit-service-header {
                            padding: 12px;
                        }

                        .edit-service-header h3 {
                            font-size: 16px;
                        }

                        .close-btn {
                            width: 28px;
                            height: 28px;
                            font-size: 16px;
                        }

                        .edit-service-content {
                            padding: 12px;
                        }

                        .form-group input,
                        .form-group textarea,
                        .form-group select {
                            padding: 8px;
                            font-size: 13px;
                        }

                        .form-group textarea {
                            min-height: 80px;
                        }

                        .list-item {
                            grid-template-columns: 1fr;
                        }

                        .add-row-container {
                            grid-template-columns: 1fr;
                        }

                        .products-list, .tools-list {
                            max-height: 200px;
                            padding: 8px;
                        }

                        .btn-cancel, .btn-save {
                            padding: 8px 12px;
                            font-size: 12px;
                            flex: 1;
                        }
                    }
                </style>
                <div class="edit-service-modal-overlay" onclick="if(event.target === this) this.remove()">
                    <div class="edit-service-modal">
                        <div class="edit-service-header">
                            <h3>Edit Service</h3>
                            <button class="close-btn" onclick="this.closest('.edit-service-modal-overlay').remove()">ÃƒÂ¢Ã…â€œÃ¢â‚¬Â¢</button>
                        </div>

                        <div class="edit-service-content">
                            <!-- Basic Info Section -->
                            <div class="edit-section">
                                <h4 class="edit-section-title">ÃƒÂ°Ã…Â¸Ã¢â‚¬Å“Ã¢â‚¬Â¹ Basic Information</h4>
                                <div class="form-group">
                                    <label>Service Title *</label>
                                    <input type="text" id="editServiceTitle" value="${serviceData.title}">
                                </div>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label>Service Image URL</label>
                                        <input type="text" id="editServiceImage" value="${serviceData.image}">
                                    </div>
                                    <div class="form-group">
                                        <label>Service Link</label>
                                        <input type="text" id="editServiceLink" value="${serviceData.link || '#'}">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label>Service Description *</label>
                                    <textarea id="editServiceDesc" placeholder="Enter service description">${serviceData.description}</textarea>
                                </div>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label>Area (sqft) *</label>
                                        <input type="number" id="editServiceArea" value="${serviceData.area_sqft || 0}" min="0">
                                    </div>
                                    <div class="form-group">
                                        <label>Base Price ($) *</label>
                                        <input type="number" id="editServicePrice" value="${serviceData.price || 0}" min="0" step="0.01">
                                    </div>
                                </div>
                                <div class="form-row">
                                    <div class="form-group">
                                        <label>Duration *</label>
                                        <input type="text" id="editServiceDuration" value="${serviceData.duration || ''}" placeholder="e.g., 8-12 weeks">
                                    </div>
                                    <div class="form-group">
                                        <label>Status</label>
                                        <select id="editServiceStatus">
                                            <option value="ACTIVE" ${(String(serviceData.status || 'ACTIVE').toUpperCase() === 'ACTIVE') ? 'selected' : ''}>ACTIVE</option>
                                            <option value="INACTIVE" ${(String(serviceData.status || 'ACTIVE').toUpperCase() === 'INACTIVE') ? 'selected' : ''}>INACTIVE</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="edit-section">
                                <h4 class="edit-section-title">Image Spot Picker</h4>
                                <div class="form-group">
                                    <div style="position: relative; display: inline-block; max-width: 100%; border: 1px solid #ddd; border-radius: 8px; overflow: hidden;">
                                        <img id="editSpotImage" src="${serviceData.image}" style="max-width: 100%; max-height: 260px; display: block; cursor: crosshair;">
                                        <div id="editSpotLayer" style="position:absolute;inset:0;pointer-events:none;"></div>
                                    </div>
                                    <div id="editSpotHint" style="margin-top: 8px; font-size: 12px; color: #556;">Click "Pick Spot" on a product, then tap image</div>
                                </div>
                            </div>

                            <!-- Products Section -->
                            <div class="edit-section">
                                <h4 class="edit-section-title">ÃƒÂ°Ã…Â¸Ã¢â‚¬Å“Ã‚Â¦ Products Breakdown</h4>
                                <div id="productsList" class="products-list"></div>
                                <div class="add-row-container" id="newProductRow">
                                    <input type="text" placeholder="Product Name" class="new-product-name" id="newProductName">
                                    <input type="number" placeholder="Cost ($)" class="new-product-cost" id="newProductCost">
                                    <input type="text" placeholder="Quantity" class="new-product-qty" id="newProductQty">
                                    <button class="add-btn" onclick="addProductToList()">Add</button>
                                </div>
                            </div>

                            <!-- Tools Section -->
                            <div class="edit-section">
                                <h4 class="edit-section-title">ÃƒÂ°Ã…Â¸Ã¢â‚¬ÂºÃ‚Â ÃƒÂ¯Ã‚Â¸Ã‚Â Tools & Software</h4>
                                <div id="toolsList" class="tools-list"></div>
                                <div class="add-row-container tool-row" id="newToolRow">
                                    <input type="text" placeholder="Tool Name" class="new-tool-name" id="newToolName">
                                    <input type="text" placeholder="Description" class="new-tool-desc" id="newToolDesc">
                                    <button class="add-btn" onclick="addToolToList()">Add</button>
                                </div>
                            </div>
                        </div>

                        <div class="edit-service-footer">
                            <button class="btn-cancel" onclick="this.closest('.edit-service-modal-overlay').remove()">Cancel</button>
                            <button class="btn-save" onclick="saveServiceChanges(${serviceId})">Save Changes</button>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);

            // Store service ID and data globally for helper functions
            window.editingServiceId = serviceId;
            window.editingProducts = [];
            window.editingTools = [];
            window.activeEditProductIndex = null;

            const editSpotImage = document.getElementById('editSpotImage');
            const editServiceImageInput = document.getElementById('editServiceImage');
            if (editSpotImage) {
                editSpotImage.addEventListener('click', onEditImageClick);
            }
            if (editServiceImageInput && editSpotImage) {
                editServiceImageInput.addEventListener('input', function () {
                    editSpotImage.src = this.value.trim();
                });
            }

            // Fetch existing products and tools
            fetchServiceDetails(serviceId);
        }

        function fetchServiceDetails(serviceId) {
            fetch('api/get-service-details.php?service_id=' + serviceId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        window.editingProducts = data.products || [];
                        window.editingTools = data.tools || [];
                        displayProductsList();
                        displayToolsList();
                    }
                })
                .catch(error => {
                    console.log('Service details will be loaded with minimal data');
                    displayProductsList();
                    displayToolsList();
                });
        }

        function displayProductsList() {
            const container = document.getElementById('productsList');
            if (!container) return;

            container.innerHTML = '';
            if (window.editingProducts.length === 0) {
                container.innerHTML = '<div style="text-align: center; padding: 20px; color: #999;">No products added yet</div>';
                return;
            }

            window.editingProducts.forEach((product, index) => {
                const item = document.createElement('div');
                item.className = 'list-item';
                item.style.gridTemplateColumns = '1.2fr .7fr .7fr .9fr auto auto';
                const sx = Number.isFinite(parseFloat(product.spot_x)) ? parseFloat(product.spot_x).toFixed(2) : '';
                const sy = Number.isFinite(parseFloat(product.spot_y)) ? parseFloat(product.spot_y).toFixed(2) : '';
                const spotText = (sx !== '' && sy !== '') ? `${sx}%, ${sy}%` : 'No spot';
                item.innerHTML = `
                    <div><strong>${product.product_name || product.name}</strong></div>
                    <div>$${parseFloat(product.cost).toFixed(2)}</div>
                    <div>${product.quantity}</div>
                    <div>${spotText}</div>
                    <button class="add-btn" style="padding: 4px 8px;" onclick="setEditSpotTarget(${index})">Pick Spot</button>
                    <button class="remove-btn" onclick="removeProduct(${index})">Remove</button>
                `;
                container.appendChild(item);
            });
            renderEditSpotMarkers();
        }

        function displayToolsList() {
            const container = document.getElementById('toolsList');
            if (!container) return;

            container.innerHTML = '';
            if (window.editingTools.length === 0) {
                container.innerHTML = '<div style="text-align: center; padding: 20px; color: #999;">No tools added yet</div>';
                return;
            }

            window.editingTools.forEach((tool, index) => {
                const item = document.createElement('div');
                item.className = 'list-item';
                item.style.gridTemplateColumns = '1fr 1fr auto';
                item.innerHTML = `
                    <div><strong>${tool.tool_name || tool.name}</strong></div>
                    <div>${tool.tool_description || tool.description}</div>
                    <button class="remove-btn" onclick="removeTool(${index})">Remove</button>
                `;
                container.appendChild(item);
            });
        }

        function addProductToList() {
            const name = document.getElementById('newProductName').value.trim();
            const cost = document.getElementById('newProductCost').value.trim();
            const qty = document.getElementById('newProductQty').value.trim();

            if (!name || !cost || !qty) {
                alert('Please fill in all product fields');
                return;
            }

            window.editingProducts.push({
                product_name: name,
                cost: parseFloat(cost),
                quantity: qty,
                spot_x: null,
                spot_y: null
            });

            document.getElementById('newProductName').value = '';
            document.getElementById('newProductCost').value = '';
            document.getElementById('newProductQty').value = '';
            displayProductsList();
        }

        function removeProduct(index) {
            window.editingProducts.splice(index, 1);
            displayProductsList();
        }

        function setEditSpotTarget(index) {
            window.activeEditProductIndex = index;
            const product = window.editingProducts[index] || {};
            const hint = document.getElementById('editSpotHint');
            if (hint) {
                hint.textContent = 'Tap image to set spot for: ' + (product.product_name || product.name || 'product');
            }
        }

        function onEditImageClick(e) {
            if (window.activeEditProductIndex === null || window.activeEditProductIndex === undefined) {
                const hint = document.getElementById('editSpotHint');
                if (hint) hint.textContent = 'Click "Pick Spot" on a product first';
                return;
            }
            const rect = e.target.getBoundingClientRect();
            if (!rect.width || !rect.height) return;
            const x = ((e.clientX - rect.left) / rect.width) * 100;
            const y = ((e.clientY - rect.top) / rect.height) * 100;
            const product = window.editingProducts[window.activeEditProductIndex];
            if (!product) return;
            product.spot_x = Math.max(0, Math.min(100, x)).toFixed(2);
            product.spot_y = Math.max(0, Math.min(100, y)).toFixed(2);
            window.activeEditProductIndex = null;
            displayProductsList();
        }

        function renderEditSpotMarkers() {
            const layer = document.getElementById('editSpotLayer');
            if (!layer) return;
            layer.innerHTML = '';
            (window.editingProducts || []).forEach((product, idx) => {
                const x = parseFloat(product.spot_x);
                const y = parseFloat(product.spot_y);
                if (!Number.isFinite(x) || !Number.isFinite(y)) return;
                const dot = document.createElement('div');
                dot.style.cssText = 'position:absolute;left:' + x + '%;top:' + y + '%;transform:translate(-50%,-50%);width:14px;height:14px;border-radius:50%;background:#ff8f4c;border:2px solid #fff;box-shadow:0 0 0 1px rgba(0,0,0,.2)';
                dot.title = product.product_name || product.name || ('Product ' + (idx + 1));
                layer.appendChild(dot);
            });
        }

        function addToolToList() {
            const name = document.getElementById('newToolName').value.trim();
            const desc = document.getElementById('newToolDesc').value.trim();

            if (!name || !desc) {
                alert('Please fill in all tool fields');
                return;
            }

            window.editingTools.push({
                tool_name: name,
                tool_description: desc
            });

            document.getElementById('newToolName').value = '';
            document.getElementById('newToolDesc').value = '';
            displayToolsList();
        }

        function removeTool(index) {
            window.editingTools.splice(index, 1);
            displayToolsList();
        }

        function saveServiceChanges(serviceId) {
            const title = document.getElementById('editServiceTitle').value.trim();
            const image = document.getElementById('editServiceImage').value.trim();
            const link = document.getElementById('editServiceLink').value || '#';
            const description = document.getElementById('editServiceDesc').value.trim();
            const area = document.getElementById('editServiceArea').value.trim();
            const basePrice = document.getElementById('editServicePrice').value.trim();
            const duration = document.getElementById('editServiceDuration').value.trim();
            const status = document.getElementById('editServiceStatus').value || 'ACTIVE';

            if (!title || !description || area === '' || basePrice === '' || !duration) {
                alert('Please fill in all required fields (Title, Description, Area, Price, Duration)');
                return;
            }

            // Convert products and tools to the format expected by API
            const products = window.editingProducts.map(p => ({
                name: p.product_name || p.name,
                cost: parseFloat(p.cost),
                qty: p.quantity,
                x: (p.spot_x !== null && p.spot_x !== undefined && p.spot_x !== '') ? parseFloat(p.spot_x) : null,
                y: (p.spot_y !== null && p.spot_y !== undefined && p.spot_y !== '') ? parseFloat(p.spot_y) : null
            }));

            const tools = window.editingTools.map(t => ({
                name: t.tool_name || t.name,
                desc: t.tool_description || t.description
            }));

            const formData = new FormData();
            formData.append('action', 'update_service');
            formData.append('service_id', serviceId);
            formData.append('title', title);
            formData.append('image', image);
            formData.append('link', link);
            formData.append('description', description);
            formData.append('area', area);
            formData.append('basePrice', basePrice);
            formData.append('duration', duration);
            formData.append('status', status);
            formData.append('products', JSON.stringify(products));
            formData.append('tools', JSON.stringify(tools));

            fetch('api/save-service.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('ÃƒÂ¢Ã…â€œÃ¢â‚¬Å“ Service updated successfully with all products and tools!');
                    location.reload();
                } else {
                    alert('ÃƒÂ¢Ã‚ÂÃ…â€™ Error: ' + (data.message || 'Unable to update service'));
                }
            })
            .catch(error => {
                alert('ÃƒÂ¢Ã‚ÂÃ…â€™ Error updating service');
                console.error('Error:', error);
            });
        }

        function deleteService(serviceId, serviceTitle) {
            if (!confirm(`Are you sure you want to delete the service "${serviceTitle}"? This will also delete all associated products and tools.`)) {
                return;
            }

            const formData = new FormData();
            formData.append('action', 'delete_service');
            formData.append('service_id', serviceId);
            formData.append('service_title', serviceTitle);

            fetch('api/save-service.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('ÃƒÂ¢Ã…â€œÃ¢â‚¬Å“ Service deleted successfully along with all products and tools!');
                    location.reload();
                } else {
                    alert('ÃƒÂ¢Ã‚ÂÃ…â€™ Error: ' + (data.message || 'Unable to delete service'));
                }
            })
            .catch(error => {
                alert('ÃƒÂ¢Ã‚ÂÃ…â€™ Error deleting service');
                console.error('Error:', error);
            });
        }

        // Hero Slider Management Functions
        function addHeroSlide() {
            const modal = document.createElement('div');
            modal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; padding: 30px; border-radius: 10px; width: 90%; max-width: 500px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); max-height: 80vh; overflow-y: auto;">
                        <h3 style="margin-top: 0; color: #333;">Add New Hero Slide</h3>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Background Image URL</label>
                            <input type="text" id="slideImage" placeholder="assets/img/your-image.jpg" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Slide Title</label>
                            <input type="text" id="slideTitle" placeholder="e.g., Interior Design for Luxury Living Spaces." style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Highlight Word (Colored Text)</label>
                            <input type="text" id="slideHighlight" placeholder="e.g., Luxury" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                        </div>
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Subtitle</label>
                            <input type="text" id="slideSubtitle" placeholder="e.g., Innovative solutions" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                        </div>
                        <div style="display: flex; gap: 10px; justify-content: flex-end;">
                            <button onclick="this.closest('[style*=\"z-index: 10000\"]').parentElement.remove()" style="padding: 10px 20px; background: #ddd; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                            <button onclick="saveHeroSlide()" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Add Slide</button>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }

        function editHeroSlide(slideIndex) {
            const slides = window.heroSlides || [];
            if (slideIndex >= slides.length) {
                alert('Slide not found');
                return;
            }
            
            const slide = slides[slideIndex];
            const modal = document.createElement('div');
            modal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; padding: 30px; border-radius: 10px; width: 90%; max-width: 500px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); max-height: 80vh; overflow-y: auto;">
                        <h3 style="margin-top: 0; color: #333;">Edit Hero Slide #${slideIndex + 1}</h3>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Background Image URL</label>
                            <input type="text" id="editSlideImage" value="${slide.image}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Slide Title</label>
                            <input type="text" id="editSlideTitle" value="${slide.title_part1} ${slide.title_part2}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Highlight Word (Colored Text)</label>
                            <input type="text" id="editSlideHighlight" value="${slide.highlight}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                        </div>
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Subtitle</label>
                            <input type="text" id="editSlideSubtitle" value="${slide.subtitle}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                        </div>
                        <div style="display: flex; gap: 10px; justify-content: flex-end;">
                            <button onclick="this.closest('[style*=\"z-index: 10000\"]').parentElement.remove()" style="padding: 10px 20px; background: #ddd; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                            <button onclick="updateHeroSlide(${slideIndex})" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Save Changes</button>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }

        function deleteHeroSlide(slideIndex) {
            if (confirm('Are you sure you want to delete slide #' + (slideIndex + 1) + '? This action cannot be undone.')) {
                const formData = new FormData();
                formData.append('action', 'delete_slide');
                formData.append('slide_index', slideIndex);
                
                fetch('admin-hero-slider-handler.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('Slide deleted successfully!');
                        location.reload();
                    } else {
                        alert('Error: ' + (data.message || 'Failed to delete slide'));
                    }
                })
                .catch(error => {
                    alert('Error: ' + error.message);
                    console.error('Error:', error);
                });
            }
        }

        function saveHeroSlide() {
            const image = document.getElementById('slideImage').value;
            const title = document.getElementById('slideTitle').value;
            const highlight = document.getElementById('slideHighlight').value;
            const subtitle = document.getElementById('slideSubtitle').value || 'Innovative solutions';

            if (!image || !title || !highlight) {
                alert('Please fill in all required fields');
                return;
            }

            const formData = new FormData();
            formData.append('action', 'add_slide');
            formData.append('image', image);
            formData.append('title', title);
            formData.append('highlight', highlight);
            formData.append('subtitle', subtitle);
            
            const modalWrapper = document.querySelector('[style*="z-index: 10000"]').parentElement;
            const addBtn = modalWrapper.querySelector('button:last-of-type');
            const originalText = addBtn.textContent;
            addBtn.textContent = 'Adding...';
            addBtn.disabled = true;

            fetch('admin-hero-slider-handler.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Hero slide added successfully and index.html has been updated!');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Failed to add slide'));
                    addBtn.textContent = originalText;
                    addBtn.disabled = false;
                }
            })
            .catch(error => {
                alert('Error: ' + error.message);
                console.error('Error:', error);
                addBtn.textContent = originalText;
                addBtn.disabled = false;
            });
        }

        function updateHeroSlide(slideIndex) {
            const image = document.getElementById('editSlideImage').value;
            const title = document.getElementById('editSlideTitle').value;
            const highlight = document.getElementById('editSlideHighlight').value;
            const subtitle = document.getElementById('editSlideSubtitle').value;

            if (!image || !title || !highlight) {
                alert('Please fill in all required fields');
                return;
            }

            const formData = new FormData();
            formData.append('action', 'edit_slide');
            formData.append('slide_index', slideIndex);
            formData.append('image', image);
            formData.append('title', title);
            formData.append('highlight', highlight);
            formData.append('subtitle', subtitle);
            
            const modalWrapper = document.querySelector('[style*="z-index: 10000"]').parentElement;
            const saveBtn = modalWrapper.querySelector('button:last-of-type');
            const originalText = saveBtn.textContent;
            saveBtn.textContent = 'Saving...';
            saveBtn.disabled = true;

            fetch('admin-hero-slider-handler.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Slide updated successfully and index.html has been updated!');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Failed to update slide'));
                    saveBtn.textContent = originalText;
                    saveBtn.disabled = false;
                }
            })
            .catch(error => {
                alert('Error: ' + error.message);
                console.error('Error:', error);
                saveBtn.textContent = originalText;
                saveBtn.disabled = false;
            });
        }

        // Projects Management Functions (Database-driven)
        let isAddingProject = false;
        let isUpdatingProject = false;

        function switchProjectTab() {
            // Legacy no-op kept for compatibility with older buttons.
        }

        function openAddProjectModal() {
            const modal = document.createElement('div');
            modal.id = 'projectModal';
            modal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; padding: 30px; border-radius: 10px; width: 90%; max-width: 560px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); max-height: 92vh; overflow-y: auto;">
                        <h3 style="margin-top: 0; color: #333;">Add Project</h3>
                        <form id="projectForm" enctype="multipart/form-data">
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Project Title</label>
                                <input type="text" id="projectTitle" placeholder="Project title" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Category</label>
                                <select id="projectCategory" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                    <option value="">Select Category</option>
                                    <option value="Masonry">Masonry</option>
                                    <option value="Interior">Interior</option>
                                    <option value="Architecture">Architecture</option>
                                    <option value="Building">Building</option>
                                    <option value="Commercial">Commercial</option>
                                    <option value="Residential">Residential</option>
                                    <option value="Retail">Retail</option>
                                </select>
                            </div>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 15px;">
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Location</label>
                                    <input type="text" id="projectLocation" placeholder="e.g., Bangalore" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Year</label>
                                    <input type="text" id="projectYear" placeholder="e.g., 2026" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Description</label>
                                <textarea id="projectDescription" placeholder="Short project description" style="width: 100%; min-height: 90px; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px; resize: vertical;"></textarea>
                            </div>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 15px;">
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Sort Order</label>
                                    <input type="number" id="projectSortOrder" min="0" value="0" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Status</label>
                                    <select id="projectIsActive" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                        <option value="1">Active</option>
                                        <option value="0">Hidden</option>
                                    </select>
                                </div>
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Upload Image</label>
                                <input type="file" id="projectImage" accept="image/*" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                <p style="margin: 5px 0 0 0; font-size: 12px; color: #999;">Supported: JPG, PNG, GIF, WebP (Max 5MB)</p>
                            </div>
                            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                                <button type="button" onclick="document.getElementById('projectModal').remove()" style="padding: 10px 20px; background: #ddd; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                                <button type="button" id="submitAddProjectBtn" onclick="submitAddProject()" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Add</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            document.getElementById('projectTitle').focus();
        }

        function openEditProjectModal(id, title, category, location, year, description, image, sortOrder, isActive) {
            const modal = document.createElement('div');
            modal.id = 'projectEditModal';
            modal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; padding: 30px; border-radius: 10px; width: 90%; max-width: 560px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); max-height: 92vh; overflow-y: auto;">
                        <h3 style="margin-top: 0; color: #333;">Edit Project</h3>
                        <form id="projectEditForm" enctype="multipart/form-data">
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Project Title</label>
                                <input type="text" id="editProjectTitle" value="${title}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Category</label>
                                <select id="editProjectCategory" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                    <option value="Masonry" ${category === 'Masonry' ? 'selected' : ''}>Masonry</option>
                                    <option value="Interior" ${category === 'Interior' ? 'selected' : ''}>Interior</option>
                                    <option value="Architecture" ${category === 'Architecture' ? 'selected' : ''}>Architecture</option>
                                    <option value="Building" ${category === 'Building' ? 'selected' : ''}>Building</option>
                                    <option value="Commercial" ${category === 'Commercial' ? 'selected' : ''}>Commercial</option>
                                    <option value="Residential" ${category === 'Residential' ? 'selected' : ''}>Residential</option>
                                    <option value="Retail" ${category === 'Retail' ? 'selected' : ''}>Retail</option>
                                </select>
                            </div>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 15px;">
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Location</label>
                                    <input type="text" id="editProjectLocation" value="${location || ''}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Year</label>
                                    <input type="text" id="editProjectYear" value="${year || ''}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Description</label>
                                <textarea id="editProjectDescription" style="width: 100%; min-height: 90px; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px; resize: vertical;">${description || ''}</textarea>
                            </div>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-bottom: 15px;">
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Sort Order</label>
                                    <input type="number" id="editProjectSortOrder" min="0" value="${typeof sortOrder === 'number' ? sortOrder : 0}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Status</label>
                                    <select id="editProjectIsActive" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                        <option value="1" ${Number(isActive) === 1 ? 'selected' : ''}>Active</option>
                                        <option value="0" ${Number(isActive) === 0 ? 'selected' : ''}>Hidden</option>
                                    </select>
                                </div>
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Current Image</label>
                                <img src="${image}" alt="Current" style="width: 100%; max-height: 150px; object-fit: cover; border-radius: 6px; margin-bottom: 10px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Upload New Image (Optional)</label>
                                <input type="file" id="editProjectImage" accept="image/*" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                <p style="margin: 5px 0 0 0; font-size: 12px; color: #999;">Leave empty to keep current image</p>
                            </div>
                            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                                <button type="button" onclick="document.getElementById('projectEditModal').remove()" style="padding: 10px 20px; background: #ddd; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                                <button type="button" id="submitEditProjectBtn" onclick="submitEditProject(${id})" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Update</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            document.getElementById('editProjectTitle').focus();
        }

        function submitAddProject() {
            if (isAddingProject) return;

            const title = document.getElementById('projectTitle').value.trim();
            const category = document.getElementById('projectCategory').value.trim();
            const location = document.getElementById('projectLocation').value.trim();
            const projectYear = document.getElementById('projectYear').value.trim();
            const description = document.getElementById('projectDescription').value.trim();
            const sortOrder = document.getElementById('projectSortOrder').value || '0';
            const isActive = document.getElementById('projectIsActive').value || '1';
            const imageFile = document.getElementById('projectImage').files[0];

            if (!title || !category || !imageFile) {
                alert('Please fill in all fields and select an image');
                return;
            }

            if (imageFile.size > 5 * 1024 * 1024) {
                alert('Image size must be less than 5MB');
                return;
            }

            isAddingProject = true;
            let addSucceeded = false;
            const addBtn = document.getElementById('submitAddProjectBtn');
            if (addBtn) {
                addBtn.disabled = true;
                addBtn.textContent = 'Adding...';
            }

            const formData = new FormData();
            formData.append('action', 'add');
            formData.append('title', title);
            formData.append('category', category);
            formData.append('location', location);
            formData.append('project_year', projectYear);
            formData.append('description', description);
            formData.append('sort_order', sortOrder);
            formData.append('is_active', isActive);
            formData.append('image', imageFile);
            
            fetch('api/manage-project.php', {
                method: 'POST',
                body: formData
            })
            .then(async (response) => {
                const raw = await response.text();
                let data;

                try {
                    data = raw ? JSON.parse(raw) : {};
                } catch (parseError) {
                    throw new Error('Invalid server response while adding project');
                }

                if (!response.ok) {
                    throw new Error(data.message || ('Server returned ' + response.status));
                }

                return data;
            })
            .then(data => {
                if (!data.success) {
                    throw new Error(data.message || 'Unable to add project');
                }

                addSucceeded = true;
                alert('Project added successfully');

                const modal = document.getElementById('projectModal');
                if (modal) {
                    modal.remove();
                }

                window.setTimeout(() => {
                    window.location.href = 'admin-dashboard.php';
                }, 120);
            })
            .catch(error => {
                if (addSucceeded || (error && error.name === 'AbortError')) {
                    return;
                }

                console.error('Add error:', error);
                alert('Error adding project: ' + (error.message || 'Please try again'));
                isAddingProject = false;
                if (addBtn) {
                    addBtn.disabled = false;
                    addBtn.textContent = 'Add';
                }
            });
        }

        function submitEditProject(id) {
            if (isUpdatingProject) return;

            const title = document.getElementById('editProjectTitle').value.trim();
            const category = document.getElementById('editProjectCategory').value.trim();
            const location = document.getElementById('editProjectLocation').value.trim();
            const projectYear = document.getElementById('editProjectYear').value.trim();
            const description = document.getElementById('editProjectDescription').value.trim();
            const sortOrder = document.getElementById('editProjectSortOrder').value || '0';
            const isActive = document.getElementById('editProjectIsActive').value || '1';
            const imageFile = document.getElementById('editProjectImage').files[0];

            if (!title || !category) {
                alert('Please fill in all required fields');
                return;
            }

            if (imageFile && imageFile.size > 5 * 1024 * 1024) {
                alert('Image size must be less than 5MB');
                return;
            }

            isUpdatingProject = true;
            let updateSucceeded = false;
            const updateBtn = document.getElementById('submitEditProjectBtn');
            if (updateBtn) {
                updateBtn.disabled = true;
                updateBtn.textContent = 'Updating...';
            }

            const formData = new FormData();
            formData.append('action', 'update');
            formData.append('project_id', id);
            formData.append('title', title);
            formData.append('category', category);
            formData.append('location', location);
            formData.append('project_year', projectYear);
            formData.append('description', description);
            formData.append('sort_order', sortOrder);
            formData.append('is_active', isActive);
            if (imageFile) {
                formData.append('image', imageFile);
            }

            fetch('api/manage-project.php', {
                method: 'POST',
                body: formData
            })
            .then(async (response) => {
                const raw = await response.text();
                let data;

                try {
                    data = raw ? JSON.parse(raw) : {};
                } catch (parseError) {
                    throw new Error('Invalid server response while updating project');
                }

                if (!response.ok) {
                    throw new Error(data.message || ('Server returned ' + response.status));
                }

                return data;
            })
            .then(data => {
                if (!data.success) {
                    throw new Error(data.message || 'Unable to update project');
                }

                updateSucceeded = true;
                alert('Project updated successfully');

                const modal = document.getElementById('projectEditModal');
                if (modal) {
                    modal.remove();
                }

                window.setTimeout(() => {
                    window.location.href = 'admin-dashboard.php';
                }, 120);
            })
            .catch(error => {
                if (updateSucceeded || (error && error.name === 'AbortError')) {
                    return;
                }

                console.error('Edit error:', error);
                alert('Error updating project: ' + (error.message || 'Please try again'));
                isUpdatingProject = false;
                if (updateBtn) {
                    updateBtn.disabled = false;
                    updateBtn.textContent = 'Update';
                }
            });
        }

        function deleteProject(id) {
            if (!confirm('Are you sure you want to delete this project? This cannot be undone.')) return;

            const formData = new FormData();
            formData.append('action', 'delete');
            formData.append('project_id', id);

            fetch('api/manage-project.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Project deleted successfully');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unable to delete project'));
                }
            })
            .catch(error => {
                console.error('Delete error:', error);
                alert('Error deleting project');
            });
        }

        // Blog Management Functions
        function openAddBlogModal() {
            const modal = document.createElement('div');
            modal.id = 'blogModal';
            modal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; padding: 30px; border-radius: 10px; width: 90%; max-width: 500px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); max-height: 90vh; overflow-y: auto;">
                        <h3 style="margin-top: 0; color: #333;">Add Blog Post</h3>
                        <form id="blogForm" enctype="multipart/form-data">
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Blog Title</label>
                                <input type="text" id="blogTitle" placeholder="Blog title" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Category</label>
                                <input type="text" id="blogCategory" placeholder="e.g., Interior, Exterior, Decor" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Author Name</label>
                                <input type="text" id="blogAuthor" placeholder="e.g., John Smith" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            </div>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Date (Day)</label>
                                    <input type="number" id="blogDay" min="1" max="31" placeholder="1-31" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Month & Year</label>
                                    <input type="text" id="blogMonth" placeholder="e.g., JUNE 2025" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px; text-transform: uppercase;">
                                </div>
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Featured Image</label>
                                <input type="file" id="blogImage" accept="image/*" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                <p style="margin: 5px 0 0 0; font-size: 12px; color: #999;">Supported: JPG, PNG, GIF, WebP (Max 5MB)</p>
                            </div>
                            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                                <button type="button" onclick="document.getElementById('blogModal').remove()" style="padding: 10px 20px; background: #ddd; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                                <button type="button" onclick="submitAddBlog()" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Add</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            document.getElementById('blogTitle').focus();
        }

        function openEditBlogModal(id, title, category, author, image, day, month) {
            const modal = document.createElement('div');
            modal.id = 'blogEditModal';
            modal.dataset.oldImage = image;
            modal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 10000;">
                    <div style="background: white; padding: 30px; border-radius: 10px; width: 90%; max-width: 500px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); max-height: 90vh; overflow-y: auto;">
                        <h3 style="margin-top: 0; color: #333;">Edit Blog Post</h3>
                        <form id="blogEditForm" enctype="multipart/form-data">
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Blog Title</label>
                                <input type="text" id="editBlogTitle" value="${title}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Category</label>
                                <input type="text" id="editBlogCategory" value="${category}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Author Name</label>
                                <input type="text" id="editBlogAuthor" value="${author}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            </div>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Date (Day)</label>
                                    <input type="number" id="editBlogDay" min="1" max="31" value="${day}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                </div>
                                <div>
                                    <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Month & Year</label>
                                    <input type="text" id="editBlogMonth" value="${month}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px; text-transform: uppercase;">
                                </div>
                            </div>
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Current Image</label>
                                <img src="${image}" alt="Current" style="width: 100%; max-height: 150px; object-fit: cover; border-radius: 6px; margin-bottom: 10px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Upload New Image (Optional)</label>
                                <input type="file" id="editBlogImage" accept="image/*" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                                <p style="margin: 5px 0 0 0; font-size: 12px; color: #999;">Leave empty to keep current image</p>
                            </div>
                            <div style="display: flex; gap: 10px; justify-content: flex-end;">
                                <button type="button" onclick="document.getElementById('blogEditModal').remove()" style="padding: 10px 20px; background: #ddd; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                                <button type="button" onclick="submitEditBlog(${id})" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Update</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            document.getElementById('editBlogTitle').focus();
        }

        function submitAddBlog() {
            const title = document.getElementById('blogTitle').value.trim();
            const category = document.getElementById('blogCategory').value.trim();
            const author = document.getElementById('blogAuthor').value.trim();
            const day = document.getElementById('blogDay').value.trim();
            const month = document.getElementById('blogMonth').value.trim();
            const imageFile = document.getElementById('blogImage').files[0];

            if (!title || !category || !author || !day || !month || !imageFile) {
                alert('Please fill in all fields and select an image');
                return;
            }

            if (imageFile.size > 5 * 1024 * 1024) {
                alert('Image size must be less than 5MB');
                return;
            }

            const formData = new FormData();
            formData.append('title', title);
            formData.append('category', category);
            formData.append('author', author);
            formData.append('day', day);
            formData.append('month', month);
            formData.append('image', imageFile);

            fetch('admin-add-blog.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Blog post added successfully');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unable to add blog post'));
                }
            })
            .catch(error => {
                console.error('Add error:', error);
                alert('Error adding blog post');
            });
        }

        function submitEditBlog(id) {
            const title = document.getElementById('editBlogTitle').value.trim();
            const category = document.getElementById('editBlogCategory').value.trim();
            const author = document.getElementById('editBlogAuthor').value.trim();
            const day = document.getElementById('editBlogDay').value.trim();
            const month = document.getElementById('editBlogMonth').value.trim();
            const imageFile = document.getElementById('editBlogImage').files[0];
            const oldImage = document.getElementById('blogEditModal').dataset.oldImage;

            if (!title || !category || !author || !day || !month) {
                alert('Please fill in all required fields');
                return;
            }

            if (imageFile && imageFile.size > 5 * 1024 * 1024) {
                alert('Image size must be less than 5MB');
                return;
            }

            const formData = new FormData();
            formData.append('blog_id', id);
            formData.append('title', title);
            formData.append('category', category);
            formData.append('author', author);
            formData.append('day', day);
            formData.append('month', month);
            formData.append('old_image', oldImage);
            if (imageFile) {
                formData.append('image', imageFile);
            }

            fetch('admin-edit-blog.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Blog post updated successfully');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unable to update blog post'));
                }
            })
            .catch(error => {
                console.error('Edit error:', error);
                alert('Error updating blog post');
            });
        }

        function deleteBlog(id) {
            if (!confirm('Are you sure you want to delete this blog post? This cannot be undone.')) return;

            const formData = new FormData();
            formData.append('blog_id', id);

            fetch('admin-delete-blog.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Blog post deleted successfully');
                    location.reload();
                } else {
                    alert('Error: ' + (data.message || 'Unable to delete blog post'));
                }
            })
            .catch(error => {
                console.error('Delete error:', error);
                alert('Error deleting blog post');
            });
        }

        // Team Management Functions
        function loadTeamMembers() {
            const formData = new FormData();
            formData.append('action', 'get_all');

            fetch('api/manage-team.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('HTTP ' + response.status + ': ' + response.statusText);
                }
                return response.text();
            })
            .then(text => {
                try {
                    const data = JSON.parse(text);
                    if (data.success) {
                        displayTeamMembers(data.data);
                    } else {
                        document.getElementById('teamGrid').innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #c00;">Error: ' + (data.message || 'Unable to load team members') + '</p>';
                    }
                } catch (e) {
                    console.error('JSON Parse Error:', e);
                    console.error('Response text:', text.substring(0, 200));
                    document.getElementById('teamGrid').innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #c00;">Error: Invalid response from server. Please check browser console.</p>';
                }
            })
            .catch(error => {
                console.error('Load error:', error);
                document.getElementById('teamGrid').innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #c00;">Error loading team members: ' + error.message + '</p>';
            });
        }

        function displayTeamMembers(members) {
            const grid = document.getElementById('teamGrid');
            
            if (members.length === 0) {
                grid.innerHTML = '<p style="grid-column: 1/-1; text-align: center; color: #999;">No team members found. Add one to get started!</p>';
                return;
            }

            grid.innerHTML = members.map(member => `
                <div style="background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 10px rgba(0,0,0,0.1); transition: transform 0.3s ease;">
                    <div style="width: 100%; height: 200px; overflow: hidden; position: relative; background: #f5f5f5;">
                        <img src="${htmlEscape(member.image_path)}" alt="${htmlEscape(member.name)}" style="width: 100%; height: 100%; object-fit: inherit;">
                    </div>
                    <div style="padding: 15px;">
                        <h3 style="margin: 0 0 5px 0; font-size: 16px; font-weight: 700; color: #333;">${htmlEscape(member.name)}</h3>
                        <p style="margin: 0 0 10px 0; font-size: 13px; color: #d4a574; font-weight: 600;">${htmlEscape(member.designation)}</p>
                        <div style="display: flex; gap: 8px; margin-bottom: 10px;">
                            <a href="${htmlEscape(member.twitter_url)}" target="_blank" style="display: inline-flex; align-items: center; justify-content: center; width: 30px; height: 30px; background: #f5f5f5; border-radius: 50%; color: #333; text-decoration: none; font-size: 14px;">
                                <i class="fab fa-twitter"></i>
                            </a>
                            <a href="${htmlEscape(member.linkedin_url)}" target="_blank" style="display: inline-flex; align-items: center; justify-content: center; width: 30px; height: 30px; background: #f5f5f5; border-radius: 50%; color: #333; text-decoration: none; font-size: 14px;">
                                <i class="fab fa-linkedin-in"></i>
                            </a>
                        </div>
                        <div class="action-buttons" style="gap: 8px;">
                            <button class="btn-action btn-update" onclick="openEditTeamModal(${member.id}, '${addSlashes(htmlEscape(member.name))}', '${addSlashes(htmlEscape(member.designation))}', '${addSlashes(htmlEscape(member.image_path))}', '${addSlashes(htmlEscape(member.twitter_url))}', '${addSlashes(htmlEscape(member.linkedin_url))}')" style="flex: 1; padding: 6px;">Edit</button>
                            <button class="btn-action btn-delete" onclick="deleteTeamMember(${member.id})" style="flex: 1; padding: 6px;">Delete</button>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        function openAddTeamModal() {
            const modal = document.createElement('div');
            modal.id = 'addTeamModal';
            modal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000;">
                    <div style="background: white; padding: 30px; border-radius: 10px; max-width: 500px; width: 90%; max-height: 90vh; overflow-y: auto;">
                        <h2 style="margin-bottom: 20px; color: #333;">Add Team Member</h2>
                        
                        <form id="addTeamForm" onsubmit="submitAddTeam(event)">
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Name *</label>
                                <input type="text" id="teamName" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                            </div>

                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Designation *</label>
                                <input type="text" id="teamDesignation" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                            </div>

                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Twitter URL</label>
                                <input type="url" id="teamTwitter" placeholder="https://twitter.com/" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                            </div>

                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">LinkedIn URL</label>
                                <input type="url" id="teamLinkedin" placeholder="https://linkedin.com/" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                            </div>

                            <div style="margin-bottom: 20px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Profile Image *</label>
                                <input type="file" id="teamImage" accept="image/*" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                                <small style="color: #999;">Max size: 5MB. Accepted: JPEG, PNG, GIF, WebP</small>
                            </div>

                            <div style="display: flex; gap: 10px;">
                                <button type="submit" class="btn-action btn-update" style="flex: 1; padding: 10px;">Add Member</button>
                                <button type="button" class="btn-action btn-delete" onclick="document.getElementById('addTeamModal').remove()" style="flex: 1; padding: 10px;">Cancel</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            document.getElementById('teamName').focus();
        }

        function openEditTeamModal(id, name, designation, image, twitter, linkedin) {
            const modal = document.createElement('div');
            modal.id = 'editTeamModal';
            modal.innerHTML = `
                <div style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000;">
                    <div style="background: white; padding: 30px; border-radius: 10px; max-width: 500px; width: 90%; max-height: 90vh; overflow-y: auto;">
                        <h2 style="margin-bottom: 20px; color: #333;">Edit Team Member</h2>
                        
                        <div style="margin-bottom: 15px; text-align: center;">
                            <img src="${image}" alt="${name}" style="width: 100px; height: 100px; object-fit: cover; border-radius: 8px;">
                        </div>

                        <form id="editTeamForm" onsubmit="submitEditTeam(event, ${id})">
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Name *</label>
                                <input type="text" id="editTeamName" value="${name}" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                            </div>

                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Designation *</label>
                                <input type="text" id="editTeamDesignation" value="${designation}" required style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                            </div>

                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Twitter URL</label>
                                <input type="url" id="editTeamTwitter" value="${twitter}" placeholder="https://twitter.com/" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                            </div>

                            <div style="margin-bottom: 15px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">LinkedIn URL</label>
                                <input type="url" id="editTeamLinkedin" value="${linkedin}" placeholder="https://linkedin.com/" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                            </div>

                            <div style="margin-bottom: 20px;">
                                <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Profile Image (leave empty to keep current)</label>
                                <input type="file" id="editTeamImage" accept="image/*" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">
                                <small style="color: #999;">Max size: 5MB</small>
                            </div>

                            <div style="display: flex; gap: 10px;">
                                <button type="submit" class="btn-action btn-update" style="flex: 1; padding: 10px;">Update Member</button>
                                <button type="button" class="btn-action btn-delete" onclick="document.getElementById('editTeamModal').remove()" style="flex: 1; padding: 10px;">Cancel</button>
                            </div>
                        </form>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            document.getElementById('editTeamName').focus();
        }

        function submitAddTeam(event) {
            event.preventDefault();

            const name = document.getElementById('teamName').value.trim();
            const designation = document.getElementById('teamDesignation').value.trim();
            const twitter = document.getElementById('teamTwitter').value.trim();
            const linkedin = document.getElementById('teamLinkedin').value.trim();
            const imageFile = document.getElementById('teamImage').files[0];

            if (!name || !designation || !imageFile) {
                alert('Please fill in all required fields');
                return;
            }

            if (imageFile.size > 5 * 1024 * 1024) {
                alert('Image size must be less than 5MB');
                return;
            }

            const formData = new FormData();
            formData.append('action', 'add');
            formData.append('name', name);
            formData.append('designation', designation);
            formData.append('twitter_url', twitter || 'https://twitter.com/');
            formData.append('linkedin_url', linkedin || 'https://linkedin.com/');
            formData.append('image', imageFile);

            fetch('api/manage-team.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Team member added successfully');
                    document.getElementById('addTeamModal').remove();
                    loadTeamMembers();
                } else {
                    alert('Error: ' + (data.message || 'Unable to add team member'));
                }
            })
            .catch(error => {
                console.error('Add error:', error);
                alert('Error adding team member');
            });
        }

        function submitEditTeam(event, id) {
            event.preventDefault();

            const name = document.getElementById('editTeamName').value.trim();
            const designation = document.getElementById('editTeamDesignation').value.trim();
            const twitter = document.getElementById('editTeamTwitter').value.trim();
            const linkedin = document.getElementById('editTeamLinkedin').value.trim();
            const imageFile = document.getElementById('editTeamImage').files[0];

            if (!name || !designation) {
                alert('Please fill in all required fields');
                return;
            }

            if (imageFile && imageFile.size > 5 * 1024 * 1024) {
                alert('Image size must be less than 5MB');
                return;
            }

            const formData = new FormData();
            formData.append('action', 'edit');
            formData.append('id', id);
            formData.append('name', name);
            formData.append('designation', designation);
            formData.append('twitter_url', twitter || 'https://twitter.com/');
            formData.append('linkedin_url', linkedin || 'https://linkedin.com/');
            if (imageFile) {
                formData.append('image', imageFile);
            }

            fetch('api/manage-team.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Team member updated successfully');
                    document.getElementById('editTeamModal').remove();
                    loadTeamMembers();
                } else {
                    alert('Error: ' + (data.message || 'Unable to update team member'));
                }
            })
            .catch(error => {
                console.error('Edit error:', error);
                alert('Error updating team member');
            });
        }

        function deleteTeamMember(id) {
            if (!confirm('Are you sure you want to delete this team member? This cannot be undone.')) return;

            const formData = new FormData();
            formData.append('action', 'delete');
            formData.append('id', id);

            fetch('api/manage-team.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Team member deleted successfully');
                    loadTeamMembers();
                } else {
                    alert('Error: ' + (data.message || 'Unable to delete team member'));
                }
            })
            .catch(error => {
                console.error('Delete error:', error);
                alert('Error deleting team member');
            });
        }

        // Helper function to escape HTML
        function htmlEscape(str) {
            const div = document.createElement('div');
            div.textContent = str;
            return div.innerHTML;
        }

        // Helper function to add slashes
        function addSlashes(str) {
            return str.replace(/'/g, "\\'");
        }

        // Load team members when team panel is opened
        const teamPanelNav = document.querySelector('[data-target="team"]');
        if (teamPanelNav) {
            teamPanelNav.addEventListener('click', function() {
                console.log('Team panel clicked, loading members...');
                loadTeamMembers();
            });
            
            // Check if team panel is already active on page load
            if (teamPanelNav.classList.contains('active')) {
                console.log('Team panel active on load, loading members...');
                setTimeout(loadTeamMembers, 500);
            }
        }
        
        // Also auto-load when page first loads if team is the active panel
        document.addEventListener('DOMContentLoaded', function() {
            const activePanel = document.querySelector('.panel-view.active[data-panel="team"]');
            if (activePanel) {
                console.log('Team panel is active on load');
                loadTeamMembers();
            }

            // Initialize notification system
            requestNotificationPermission();
            initializeNotifications();

            // Setup mark all read button
            const markAllBtn = document.getElementById('markAllReadBtn');
            if (markAllBtn) {
                markAllBtn.addEventListener('click', markAllNotificationsAsRead);
            }

            // Auto-refresh dashboard data every 10 seconds
            refreshDashboardData();
            setInterval(refreshDashboardData, 10000);
        });

        // Refresh dashboard data in real-time
        function refreshDashboardData() {
            fetch('api/get-dashboard-data.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Update statistics
                        const statElements = {
                            'total_orders': data.stats.total_orders || 0,
                            'pending_orders': data.stats.pending_orders || 0,
                            'delivered_orders': data.stats.delivered_orders || 0,
                            'total_revenue': data.stats.total_revenue || 0,
                            'total_consultations': data.counts.consultations || 0
                        };

                        // Update stat cards if they exist
                        const statCards = document.querySelectorAll('.stat-card');
                        let statIndex = 0;
                        statCards.forEach((card) => {
                            const value = card.querySelector('.stat-value');
                            if (value) {
                                let newValue = '';
                                if (statIndex === 0) newValue = data.stats.total_orders || 0;
                                else if (statIndex === 1) newValue = data.stats.pending_orders || 0;
                                else if (statIndex === 2) newValue = data.stats.delivered_orders || 0;
                                else if (statIndex === 3) newValue = '\u20B9' + (data.stats.total_revenue || 0);
                                else if (statIndex === 4) newValue = data.counts.consultations || 0;
                                
                                if (newValue && value.textContent !== newValue.toString()) {
                                    value.textContent = newValue;
                                    value.style.animation = 'pulse 0.5s ease';
                                }
                                statIndex++;
                            }
                        });

                        // Update last refresh time
                        console.log('Dashboard data refreshed at ' + data.timestamp);
                    }
                })
                .catch(error => {
                    console.log('Auto-refresh error:', error);
                });
        }

        // Add pulse animation
        const style = document.createElement('style');
        style.textContent = `
            @keyframes pulse {
                0%, 100% { opacity: 1; }
                50% { opacity: 0.7; }
            }
        `;
        document.head.appendChild(style);

        // Profile Functions
        function saveProfileChanges() {
            const email = document.getElementById('profileEmail').value.trim();
            const phone = document.getElementById('profilePhone').value.trim();
            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmPassword').value;
            const statusDiv = document.getElementById('profileStatus');

            // Validation
            if (newPassword && newPassword !== confirmPassword) {
                showStatus(statusDiv, 'Passwords do not match!', 'error');
                return;
            }

            if (newPassword && newPassword.length < 6) {
                showStatus(statusDiv, 'New password must be at least 6 characters!', 'error');
                return;
            }

            // Prepare data
            const formData = new FormData();
            formData.append('action', 'update_profile');
            formData.append('email', email);
            formData.append('phone', phone);
            if (currentPassword) {
                formData.append('current_password', currentPassword);
            }
            if (newPassword) {
                formData.append('new_password', newPassword);
            }

            // Show loading state
            const saveBtn = document.getElementById('saveProfileBtn');
            saveBtn.disabled = true;
            saveBtn.textContent = 'Saving...';

            fetch('api/update-profile.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showStatus(statusDiv, 'Profile updated successfully!', 'success');
                    // Clear password fields
                    document.getElementById('currentPassword').value = '';
                    document.getElementById('newPassword').value = '';
                    document.getElementById('confirmPassword').value = '';
                } else {
                    showStatus(statusDiv, data.message || 'Failed to update profile', 'error');
                }
            })
            .catch(error => {
                showStatus(statusDiv, 'Error: ' + error.message, 'error');
            })
            .finally(() => {
                saveBtn.disabled = false;
                saveBtn.textContent = 'Save Changes';
            });
        }

        function createDatabaseBackup() {
            const backupBtn = document.getElementById('backupBtn');
            const statusDiv = document.getElementById('backupStatus');

            // Show loading state
            backupBtn.disabled = true;
            backupBtn.textContent = 'Creating Backup...';
            statusDiv.style.display = 'block';
            statusDiv.textContent = 'Processing...';
            statusDiv.style.background = '#e3f2fd';
            statusDiv.style.color = '#1976d2';

            fetch('api/backup-database.php', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    statusDiv.style.background = '#e8f5e9';
                    statusDiv.style.color = '#388e3c';
                    statusDiv.innerHTML = `<strong>ÃƒÂ¢Ã…â€œÃ¢â‚¬Å“ Success!</strong> Backup created: <strong>${data.filename}</strong><br><small>${data.timestamp}</small><br><button onclick="downloadBackup('${data.filename}')" style="margin-top: 8px; padding: 6px 12px; background: #388e3c; color: white; border: none; border-radius: 4px; cursor: pointer; font-weight: 600;">Download Now</button>`;
                    
                    // Auto-download the file
                    setTimeout(() => {
                        downloadBackup(data.filename);
                    }, 500);
                } else {
                    statusDiv.style.background = '#ffebee';
                    statusDiv.style.color = '#c62828';
                    statusDiv.textContent = 'ÃƒÂ¢Ã…â€œÃ¢â‚¬â€ Error: ' + (data.message || 'Failed to create backup');
                }
            })
            .catch(error => {
                statusDiv.style.background = '#ffebee';
                statusDiv.style.color = '#c62828';
                statusDiv.textContent = 'ÃƒÂ¢Ã…â€œÃ¢â‚¬â€ Error: ' + error.message;
            })
            .finally(() => {
                backupBtn.disabled = false;
                backupBtn.textContent = 'Create Backup';
            });
        }

        function downloadBackup(filename) {
            const link = document.createElement('a');
            link.href = 'api/backup-database.php?action=download&file=' + encodeURIComponent(filename);
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        function updateMaintenanceButtonLabel() {
            const maintenanceToggleBtn = document.getElementById('maintenanceToggleBtn');
            const maintenanceMode = document.getElementById('maintenanceMode');
            if (!maintenanceToggleBtn || !maintenanceMode) return;
            maintenanceToggleBtn.textContent = maintenanceMode.checked ? 'Disable Maintenance' : 'Enable Maintenance';
            maintenanceToggleBtn.style.background = maintenanceMode.checked ? '#c62828' : '#6b5738';
        }

        function toggleMaintenanceMode() {
            const maintenanceMode = document.getElementById('maintenanceMode');
            if (!maintenanceMode) return;
            maintenanceMode.checked = !maintenanceMode.checked;
            updateMaintenanceButtonLabel();
            saveSystemSettings(true);
        }

        function saveSystemSettings(redirectToMaintenance = false) {
            const siteName = document.getElementById('siteName').value.trim();
            const contactEmail = document.getElementById('contactEmail').value.trim();
            const supportPhone = document.getElementById('supportPhone').value.trim();
            const maintenanceMode = document.getElementById('maintenanceMode').checked;

            const formData = new FormData();
            formData.append('action', 'update_settings');
            formData.append('site_name', siteName);
            formData.append('contact_email', contactEmail);
            formData.append('support_phone', supportPhone);
            formData.append('maintenance_mode', maintenanceMode ? 1 : 0);

            const saveBtn = document.getElementById('saveSettingsBtn');
            saveBtn.disabled = true;
            saveBtn.textContent = 'Saving...';

            fetch('api/update-settings.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showStatus(null, 'Settings saved successfully!', 'success', 'top');
                    updateMaintenanceButtonLabel();
                    if (redirectToMaintenance && maintenanceMode) {
                        window.location.href = 'maintenance.php';
                    }
                } else {
                    showStatus(null, data.message || 'Failed to save settings', 'error', 'top');
                }
            })
            .catch(error => {
                showStatus(null, 'Error: ' + error.message, 'error', 'top');
            })
            .finally(() => {
                saveBtn.disabled = false;
                saveBtn.textContent = 'Save Settings';
            });
        }

        document.addEventListener('DOMContentLoaded', function () {
            const maintenanceMode = document.getElementById('maintenanceMode');
            updateMaintenanceButtonLabel();
            if (maintenanceMode) {
                maintenanceMode.addEventListener('change', updateMaintenanceButtonLabel);
            }
        });

        function showStatus(element, message, type, position = 'inline') {
            if (position === 'top') {
                // Show notification at top
                const notification = document.createElement('div');
                notification.style.cssText = `
                    position: fixed;
                    top: 20px;
                    right: 20px;
                    padding: 15px 20px;
                    border-radius: 6px;
                    background: ${type === 'success' ? '#e8f5e9' : '#ffebee'};
                    color: ${type === 'success' ? '#388e3c' : '#c62828'};
                    font-weight: 600;
                    z-index: 10000;
                    box-shadow: 0 2px 8px rgba(0,0,0,0.15);
                    animation: slideIn 0.3s ease;
                `;
                notification.textContent = message;
                document.body.appendChild(notification);
                setTimeout(() => notification.remove(), 3000);
            } else if (element) {
                // Show in element
                element.style.display = 'block';
                element.style.background = type === 'success' ? '#e8f5e9' : '#ffebee';
                element.style.color = type === 'success' ? '#388e3c' : '#c62828';
                element.textContent = (type === 'success' ? 'ÃƒÂ¢Ã…â€œÃ¢â‚¬Å“ ' : 'ÃƒÂ¢Ã…â€œÃ¢â‚¬â€ ') + message;
            }
        }

        // Add slideIn animation
        const styleSheet = document.createElement('style');
        styleSheet.textContent = `
            @keyframes slideIn {
                from {
                    transform: translateX(400px);
                    opacity: 0;
                }
                to {
                    transform: translateX(0);
                    opacity: 1;
                }
            }
        `;
        if (!document.querySelector('style[data-animation="slideIn"]')) {
            styleSheet.setAttribute('data-animation', 'slideIn');
            document.head.appendChild(styleSheet);
        }
    </script>
</body>
</html>


