<?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);

$user_id = $_SESSION['user_id'];

// 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.*, 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 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 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: 1600px;
            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);
        }

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

        .badge {
            display: inline-block;
            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;
        }

        .badge-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);
        }

        .badge-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);
        }

        .badge-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);
        }

        .badge-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);
        }

        .badge-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);
        }

        .badge-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);
        }

        .badge-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);
        }
        .badge-verified {
            background: #d1fae5;
            color: #065f46;
            border-color: #a7f3d0;
        }

        .badge-approved {
            background: #d1fae5;
            color: #065f46;
            border-color: #a7f3d0;
        }

        .badge-declined {
            background: #fee2e2;
            color: #991b1b;
            border-color: #fecaca;
        }

        .badge-scheduled {
            background: #dbeafe;
            color: #1e40af;
            border-color: #93c5fd;
        }

        .badge-completed {
            background: #dcfce7;
            color: #166534;
            border-color: #bbf7d0;
        }

        .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);
        }

        .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;
            }

            .admin-table {
                min-width: 600px;
            }

            .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 {
                width: 100%;
                font-size: 16px;
            }

            .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 */
        .user-details-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: 20px;
        }

        .user-details-modal {
            background: white;
            border-radius: 12px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            width: 100%;
            max-width: 600px;
            max-height: 85vh;
            display: flex;
            flex-direction: column;
            animation: slideUp 0.3s ease;
        }

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

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 24px;
            border-bottom: 1px solid #e0e0e0;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 20px;
            color: #333;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .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;
        }

        .modal-body {
            flex: 1;
            overflow-y: auto;
            padding: 24px;
        }

        .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(250px, 1fr));
            gap: 20px;
        }

        .detail-item {
            display: flex;
            flex-direction: column;
        }

        .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-all;
        }

        .modal-footer {
            display: flex;
            gap: 12px;
            justify-content: flex-end;
            padding: 20px 24px;
            border-top: 1px solid #e0e0e0;
            background: #f8f9fa;
            border-radius: 0 0 12px 12px;
        }

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

        @media (max-width: 600px) {
            .user-details-modal-overlay {
                padding: 10px;
            }

            .user-details-modal {
                max-height: 90vh;
            }

            .modal-header {
                padding: 16px;
            }

            .modal-body {
                padding: 16px;
            }

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

            .modal-footer {
                flex-direction: column;
                padding: 16px;
            }

            .modal-footer .btn-action {
                width: 100%;
            }
        }
    </style>
</head>
<body>
    
    <div class="admin-wrapper">
        <!-- Admin Header -->
        <div class="admin-header" style="margin:0px">
            <div class="admin-header-content">
                <h1>
                    <i class="fas fa-chart-pie"></i> Admin Dashboard
                </h1>
                <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>
                    <a href="auth-system/logout.php" class="logout-btn">
                        <i class="fas fa-sign-out-alt"></i> Logout
                    </a>
                </div>
            </div>
        </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="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">₹<?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>

                    </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">
                                            <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()): ?>
                                                    <tr class="order-row" data-status="<?php echo htmlspecialchars($order['status']); ?>">
                                                        <td><strong>#<?php echo htmlspecialchars($order['id']); ?></strong></td>
                                                        <td><?php echo htmlspecialchars($order['customer_name']); ?></td>
                                                        <td><?php echo htmlspecialchars($order['customer_email']); ?></td>
                                                        <td><?php echo date('M d, Y', strtotime($order['created_at'])); ?></td>
                                                        <td><strong>₹<?php echo number_format($order['total'], 0); ?></strong></td>
                                                        <td>
                                                            <?php 
                                                                $status = htmlspecialchars($order['status']);
                                                                $icons = [
                                                                    'pending' => '⏳',
                                                                    'processing' => '⚙️',
                                                                    'shipped' => '📦',
                                                                    'delivered' => '✅',
                                                                    'cancelled' => '❌'
                                                                ];
                                                                $labels = [
                                                                    'pending' => 'Awaiting Action',
                                                                    'processing' => 'Being Prepared',
                                                                    'shipped' => 'In Transit',
                                                                    'delivered' => 'Successfully Delivered',
                                                                    'cancelled' => 'Order Cancelled'
                                                                ];
                                                                $icon = $icons[$status] ?? '';
                                                                $label = $labels[$status] ?? ucfirst($status);
                                                            ?>
                                                            <span class="badge badge-<?php echo $status; ?>" style="padding: 10px 16px; border-radius: 20px; font-weight: 600; display: inline-flex; align-items: center; gap: 8px; border: 2px solid; font-size: 13px; white-space: nowrap;">
                                                                <span style="font-size: 16px;"><?php echo $icon; ?></span>
                                                                <div style="text-align: left;">
                                                                    <div style="font-weight: 700; font-size: 14px;"><?php echo ucfirst($status); ?></div>
                                                                    <div style="font-weight: 400; font-size: 11px; opacity: 0.8;"><?php echo $label; ?></div>
                                                                </div>
                                                            </span>
                                                        </td>
                                                        <td><?php echo ucfirst(str_replace('_', ' ', htmlspecialchars($order['payment_method'] ?? 'N/A'))); ?></td>
                                                        <td>
                                                            <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">
                                    <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><strong><?php echo htmlspecialchars(($consultation['first_name'] ?? '') . ' ' . ($consultation['last_name'] ?? '')); ?></strong></td>
                                                <td><?php echo htmlspecialchars($consultation['email'] ?? 'N/A'); ?></td>
                                                <td><?php echo htmlspecialchars($consultation['phone'] ?? 'N/A'); ?></td>
                                                <td><?php echo ucfirst(str_replace('_', ' ', htmlspecialchars($consultation['consultation_type'] ?? 'N/A'))); ?></td>
                                                <td><?php echo isset($consultation['preferred_date']) ? date('M d, Y', strtotime($consultation['preferred_date'])) : 'N/A'; ?></td>
                                                <td><?php echo htmlspecialchars($consultation['budget_range'] ?? 'N/A'); ?></td>
                                                <td>
                                                    <?php 
                                                        $status = $consultation['status'] ?? 'pending';
                                                        $status_display = [
                                                            'pending' => 'Pending',
                                                            'approved' => 'Approved',
                                                            'declined' => 'Declined',
                                                            'scheduled' => 'Scheduled',
                                                            'completed' => 'Completed',
                                                            'cancelled' => 'Cancelled'
                                                        ];
                                                        $display_text = $status_display[$status] ?? ucfirst($status);
                                                    ?>
                                                    <span class="badge badge-<?php echo htmlspecialchars($status); ?>" style="padding: 8px 12px; border-radius: 6px; font-weight: 600; display: inline-block;">
                                                        <?php echo htmlspecialchars($display_text); ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <div class="action-buttons">
                                                        <?php 
                                                            $current_status = $consultation['status'] ?? 'pending';
                                                            $is_pending = ($current_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'] ?? '')); ?>')">✓ 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'] ?? '')); ?>')">✗ 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="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><strong>#<?php echo htmlspecialchars($user['id']); ?></strong></td>
                                                        <td><?php echo htmlspecialchars($user['name'] ?? 'N/A'); ?></td>
                                                        <td><?php echo htmlspecialchars($user['email'] ?? 'N/A'); ?></td>
                                                        <td><?php echo htmlspecialchars($user['phone'] ?? 'N/A'); ?></td>
                                                        <td>
                                                            <span class="badge <?php echo (trim($user['role']) === 'admin') ? 'badge-admin' : 'badge-customer'; ?>">
                                                                <?php echo ucfirst(htmlspecialchars(trim($user['role'] ?? 'customer'))); ?>
                                                            </span>
                                                        </td>
                                                        <td><?php echo date('M d, Y', strtotime($user['created_at'])); ?></td>
                                                        <td>
                                                            <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>₹<?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
                                    // Parse gallery.html to get dynamic gallery items
                                    $gallery_file = __DIR__ . '/gallery.html';
                                    $galleries = [];
                                    
                                    if (file_exists($gallery_file)) {
                                        $html_content = file_get_contents($gallery_file);
                                        
                                        // Extract gallery items with regex
                                        if (preg_match_all('/<div class="col-lg-6 col-xl-4 col-xxl-auto filter-item[^>]*data-gallery-id="(\d+)"[^>]*>.*?<img src="([^"]+)"[^>]*alt="([^"]*)"[^>]*>.*?<h2 class="box-title">([^<]+)<\/h2>/s', $html_content, $matches)) {
                                            for ($i = 0; $i < count($matches[1]); $i++) {
                                                $galleries[] = [
                                                    'id' => intval($matches[1][$i]),
                                                    'image' => $matches[2][$i],
                                                    'alt' => $matches[3][$i],
                                                    'title' => $matches[4][$i],
                                                    'category' => 'Gallery' // Default category
                                                ];
                                            }
                                        }
                                    }
                                    
                                    // 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>
                            
                            <!-- Tabs for Recent Projects and Projects -->
                            <div style="display: flex; gap: 10px; margin-bottom: 20px; border-bottom: 2px solid #eee;">
                                <button class="tab-btn active" onclick="switchProjectTab('recent', event)" style="padding: 10px 20px; background: none; border: none; border-bottom: 3px solid #3366cc; color: #3366cc; font-weight: 600; cursor: pointer;">Recent Projects (index.php)</button>
                                <button class="tab-btn" onclick="switchProjectTab('projects', event)" style="padding: 10px 20px; background: none; border: none; border-bottom: 3px solid transparent; color: #999; font-weight: 600; cursor: pointer;">Projects (project.php)</button>
                            </div>

                            <!-- Recent Projects Tab -->
                            <div id="recent-projects-tab" class="project-tab active">
                                <div class="table-wrapper">
                                    <div class="table-header">
                                        <h2>Recent Projects</h2>
                                        <button class="btn-action btn-update" onclick="openAddProjectModal('recent')" style="padding:8px 12px;">Add Project</button>
                                    </div>

                                    <div style="padding: 20px; display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px;">
                                        <?php
                                        // Parse index.php to get dynamic projects
                                        $project_file = __DIR__ . '/index.php';
                                        $recent_projects = [];
                                        
                                        if (file_exists($project_file)) {
                                            $php_content = file_get_contents($project_file);
                                            
                                            // Extract project items from projects-grid section in index.php
                                            if (preg_match_all('/<div class="project-card"[^>]*>.*?<img src="([^"]+)"[^>]*alt="([^"]*)"[^>]*>.*?<span class="category">([^<]+)<\/span>.*?<h3[^>]*><a[^>]*>([^<]+)<\/a>/s', $php_content, $matches)) {
                                                for ($i = 0; $i < count($matches[1]); $i++) {
                                                    $recent_projects[] = [
                                                        'id' => $i + 1,
                                                        'image' => $matches[1][$i],
                                                        'alt' => $matches[2][$i],
                                                        'category' => $matches[3][$i],
                                                        'title' => $matches[4][$i]
                                                    ];
                                                }
                                            }
                                        }
                                        
                                        if (empty($recent_projects)) {
                                            echo '<p style="grid-column: 1/-1; text-align: center; color: #999;">No recent projects found.</p>';
                                        } else {
                                            foreach ($recent_projects as $project): ?>
                                                <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: 180px; overflow: hidden; position: relative;">
                                                        <img src="<?php echo htmlspecialchars($project['image']); ?>" alt="<?php echo htmlspecialchars($project['title']); ?>" style="width: 100%; height: 100%; object-fit: cover;">
                                                    </div>
                                                    <div style="padding: 15px;">
                                                        <span style="display: inline-block; background: #f0f0f0; color: #666; padding: 4px 8px; border-radius: 4px; font-size: 12px; margin-bottom: 8px;"><?php echo htmlspecialchars($project['category']); ?></span>
                                                        <p style="margin: 0 0 10px 0; font-size: 15px; font-weight: 600; color: #333;"><?php echo htmlspecialchars($project['title']); ?></p>
                                                        <div class="action-buttons" style="gap: 8px;">
                                                            <button class="btn-action btn-update" onclick="openEditProjectModal(<?php echo $project['id']; ?>, '<?php echo addslashes(htmlspecialchars($project['title'])); ?>', '<?php echo htmlspecialchars($project['category']); ?>', '<?php echo htmlspecialchars($project['image']); ?>', 'recent')" style="flex: 1; padding: 6px;">Edit</button>
                                                            <button class="btn-action btn-delete" onclick="deleteProject(<?php echo $project['id']; ?>, 'recent')" style="flex: 1; padding: 6px;">Delete</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach;
                                        }
                                        ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Projects Tab -->
                            <div id="projects-tab" class="project-tab" style="display: none;">
                                <div class="table-wrapper">
                                    <div class="table-header">
                                        <h2>Projects</h2>
                                        <button class="btn-action btn-update" onclick="openAddProjectModal('projects')" style="padding:8px 12px;">Add Project</button>
                                    </div>

                                    <div style="padding: 20px; display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px;">
                                        <?php
                                        // Parse project.php to get dynamic projects
                                        $projects_file = __DIR__ . '/project.php';
                                        $projects_list = [];
                                        
                                        if (file_exists($projects_file)) {
                                            $php_content = file_get_contents($projects_file);
                                            
                                            // Extract projects from project-grid-sec in project.php
                                            if (preg_match_all('/<div class="project-card"[^>]*>.*?<img src="([^"]+)"[^>]*alt="([^"]*)"[^>]*>.*?<span class="category">([^<]+)<\/span>.*?<h3[^>]*><a[^>]*>([^<]+)<\/a>/s', $php_content, $matches)) {
                                                for ($i = 0; $i < count($matches[1]); $i++) {
                                                    $projects_list[] = [
                                                        'id' => $i + 1,
                                                        'image' => $matches[1][$i],
                                                        'alt' => $matches[2][$i],
                                                        'category' => $matches[3][$i],
                                                        'title' => $matches[4][$i]
                                                    ];
                                                }
                                            }
                                        }
                                        
                                        if (empty($projects_list)) {
                                            echo '<p style="grid-column: 1/-1; text-align: center; color: #999;">No projects found.</p>';
                                        } else {
                                            foreach ($projects_list as $project): ?>
                                                <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: 180px; overflow: hidden; position: relative;">
                                                        <img src="<?php echo htmlspecialchars($project['image']); ?>" alt="<?php echo htmlspecialchars($project['title']); ?>" style="width: 100%; height: 100%; object-fit: cover;">
                                                    </div>
                                                    <div style="padding: 15px;">
                                                        <span style="display: inline-block; background: #f0f0f0; color: #666; padding: 4px 8px; border-radius: 4px; font-size: 12px; margin-bottom: 8px;"><?php echo htmlspecialchars($project['category']); ?></span>
                                                        <p style="margin: 0 0 10px 0; font-size: 15px; font-weight: 600; color: #333;"><?php echo htmlspecialchars($project['title']); ?></p>
                                                        <div class="action-buttons" style="gap: 8px;">
                                                            <button class="btn-action btn-update" onclick="openEditProjectModal(<?php echo $project['id']; ?>, '<?php echo addslashes(htmlspecialchars($project['title'])); ?>', '<?php echo htmlspecialchars($project['category']); ?>', '<?php echo htmlspecialchars($project['image']); ?>', 'projects')" style="flex: 1; padding: 6px;">Edit</button>
                                                            <button class="btn-action btn-delete" onclick="deleteProject(<?php echo $project['id']; ?>, 'projects')" style="flex: 1; padding: 6px;">Delete</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            <?php endforeach;
                                        }
                                        ?>
                                    </div>
                                </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
                                    // Parse blog-grid-sidebar.html to get dynamic blog posts
                                    $blog_file = __DIR__ . '/blog-grid-sidebar.html';
                                    $blog_posts = [];
                                    
                                    if (file_exists($blog_file)) {
                                        $html_content = file_get_contents($blog_file);
                                        
                                        // Extract blog posts from blog grid section
                                        if (preg_match_all('/<div class="col-xl-6">.*?<div class="th-blog blog-single has-post-thumbnail single-grid">.*?<img\s+src="([^"]+)"[^>]*alt="([^"]*)"[^>]*>.*?<a href="blog.html">([^<]+)<\/a>.*?<a class="author"\s+href="blog.html">by\s+([^<]+)<\/a>.*?<h2 class="box-title"><a[^>]*>([^<]+)<\/a><\/h2>.*?<span class="date">(\d+)<\/span>\s*<span class="month">([^<]+)<\/span>/s', $html_content, $matches)) {
                                            for ($i = 0; $i < count($matches[1]); $i++) {
                                                $blog_posts[] = [
                                                    'id' => $i + 1,
                                                    'image' => $matches[1][$i],
                                                    'alt' => $matches[2][$i],
                                                    'category' => $matches[3][$i],
                                                    'author' => $matches[4][$i],
                                                    'title' => $matches[5][$i],
                                                    'day' => $matches[6][$i],
                                                    'month' => $matches[7][$i]
                                                ];
                                            }
                                        }
                                    }
                                    
                                    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 $post['id']; ?>, '<?php echo addslashes(htmlspecialchars($post['title'])); ?>', '<?php echo htmlspecialchars($post['category']); ?>', '<?php echo htmlspecialchars($post['author']); ?>', '<?php echo htmlspecialchars($post['image']); ?>', '<?php echo htmlspecialchars($post['day']); ?>', '<?php echo htmlspecialchars($post['month']); ?>')" 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>
                                <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 20px; padding: 20px;">
                                    <?php
                                    $service_file = __DIR__ . '/service.html';
                                    $service_index = 0;
                                    if (file_exists($service_file)) {
                                        $html_content = file_get_contents($service_file);
                                        // Extract service boxes with image, title, and description
                                        if (preg_match_all('/<div class="service-box[^>]*>.*?<div class="box-img[^>]*><img src="([^"]+)"[^>]*><\/div>.*?<h3[^>]*>.*?<a[^>]*>([^<]+)<\/a>.*?<\/h3>.*?<p class="box-text">\s*([^<]+(?:<[^>]*>[^<]*)*?)\s*<\/p>/s', $html_content, $matches)) {
                                            for ($i = 0; $i < count($matches[1]); $i++) {
                                                $image = trim($matches[1][$i]);
                                                $title = trim($matches[2][$i]);
                                                $desc = trim(preg_replace('/<[^>]+>/', '', $matches[3][$i]));
                                                echo '<div style="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;">';
                                                echo '<img src="' . htmlspecialchars($image) . '" alt="' . htmlspecialchars($title) . '" style="width: 100%; height: 200px; object-fit: cover;">';
                                                echo '<div style="padding: 20px;">';
                                                echo '<h3 style="color: #1b8a67; margin: 0 0 10px 0; font-size: 18px;">' . htmlspecialchars($title) . '</h3>';
                                                echo '<p style="color: #555; font-size: 14px; line-height: 1.6; margin: 0 0 15px 0;">' . htmlspecialchars(substr($desc, 0, 100)) . '...</p>';
                                                echo '<div style="display: flex; gap: 8px;">';
                                                echo '<button class="btn-action btn-view" onclick="editService(' . $i . ', ' . htmlspecialchars(json_encode(['title' => $title, 'image' => $image, 'description' => $desc, 'index' => $i])) . ')" style="flex: 1;">Edit</button>';
                                                echo '<button class="btn-action btn-delete" onclick="deleteService(' . $i . ', \'' . addslashes($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>

                    <!-- 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 style="max-width: 600px; margin: 20px auto;">
                                <div style="background: white; padding: 30px; border-radius: 10px; border: 1px solid #ddd; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                    <div style="margin-bottom: 20px;">
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #333;">Admin Name</label>
                                        <input type="text" value="<?php echo htmlspecialchars($_SESSION['user_name']); ?>" readonly style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; background: #f9f9f9;">
                                    </div>
                                    <div style="margin-bottom: 20px;">
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #333;">Email Address</label>
                                        <input type="email" id="profileEmail" placeholder="admin@email.com" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
                                    </div>
                                    <div style="margin-bottom: 20px;">
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #333;">Phone Number</label>
                                        <input type="tel" id="profilePhone" placeholder="Enter phone number" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
                                    </div>
                                    <hr style="margin: 25px 0; border: none; border-top: 1px solid #ddd;">
                                    <div style="margin-bottom: 20px;">
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #333;">Current Password</label>
                                        <input type="password" id="currentPassword" placeholder="Enter current password" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
                                    </div>
                                    <div style="margin-bottom: 20px;">
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #333;">New Password</label>
                                        <input type="password" id="newPassword" placeholder="Leave empty to keep current" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
                                    </div>
                                    <div style="margin-bottom: 20px;">
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #333;">Confirm New Password</label>
                                        <input type="password" id="confirmPassword" placeholder="Confirm new password" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
                                    </div>
                                    <div id="profileStatus" style="margin-bottom: 15px; display: none; padding: 12px; border-radius: 4px; font-size: 14px;"></div>
                                    <div style="display: flex; gap: 10px; justify-content: flex-end;">
                                        <button onclick="saveProfileChanges()" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; transition: background 0.3s;">Save Changes</button>
                                    </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 style="max-width: 600px; margin: 20px auto;">
                                <div style="background: white; padding: 30px; border-radius: 10px; border: 1px solid #ddd; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                                    <div style="margin-bottom: 20px;">
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #333;">Site Name</label>
                                        <input type="text" id="siteName" value="FAREN Interior Design" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
                                    </div>
                                    <div style="margin-bottom: 20px;">
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #333;">Contact Email</label>
                                        <input type="email" id="contactEmail" value="contact@faren.com" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
                                    </div>
                                    <div style="margin-bottom: 20px;">
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #333;">Support Phone</label>
                                        <input type="tel" id="supportPhone" value="+1 (555) 123-4567" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px;">
                                    </div>
                                    <div style="margin-bottom: 20px;">
                                        <label style="display: block; font-weight: 600; margin-bottom: 8px; color: #333;">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;">
                                            <span style="color: #666;">When enabled, users will see maintenance notice</span>
                                        </div>
                                    </div>
                                    <div style="margin-bottom: 20px; padding: 15px; background: #f5f5f5; border-radius: 6px;">
                                        <label style="display: block; font-weight: 600; margin-bottom: 12px; color: #333;">Database Backup</label>
                                        <p style="font-size: 13px; color: #666; margin-bottom: 12px;">Create a backup of your database. The backup will be stored securely and can be used for recovery.</p>
                                        <button id="backupBtn" onclick="createDatabaseBackup()" style="padding: 10px 20px; background: #666; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; transition: background 0.3s;">Create Backup</button>
                                        <div id="backupStatus" style="margin-top: 10px; display: none; padding: 10px; border-radius: 4px; font-size: 14px;"></div>
                                    </div>
                                    <div style="display: flex; gap: 10px; justify-content: flex-end;">
                                        <button onclick="saveSystemSettings()" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: 600; transition: background 0.3s;">Save Settings</button>
                                    </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');

            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));
            }

            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); });
                }
            });
        })();

        // 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) {
                        const msg = sendEmail ? 'Consultation approved! Approval email sent to ' + email : 'Consultation approved! (Email was not sent)';
                        alert(msg);
                        showBrowserNotification('Consultation Approved', `Approval sent to ${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) {
                        const msg = sendEmail ? 'Consultation declined! Decline email sent to ' + email : 'Consultation declined! (Email was not sent)';
                        alert(msg);
                        location.reload();
                    } else {
                        alert('Error: ' + (data.message || 'Unknown error'));
                    }
                })
                .catch(error => {
                    console.error('Fetch error:', error);
                    alert('Error declining consultation: ' + error.message);
                });
            }
        }

        // View user details modal
        function viewUserDetailsModal(userId) {
            // 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 modal = document.createElement('div');
                        modal.className = 'user-details-modal-overlay';
                        modal.innerHTML = `
                            <div class="user-details-modal">
                                <div class="modal-header">
                                    <h3><i class="fas fa-user-circle"></i> User Details</h3>
                                    <button class="modal-close-btn" onclick="this.parentElement.parentElement.parentElement.remove()">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                                
                                <div class="modal-body">
                                    <div class="detail-section">
                                        <h4>Account Information</h4>
                                        <div class="detail-grid">
                                            <div class="detail-item">
                                                <label>User ID:</label>
                                                <p>#${user.id}</p>
                                            </div>
                                            <div class="detail-item">
                                                <label>Email Address:</label>
                                                <p>${user.email || 'N/A'}</p>
                                            </div>
                                            <div class="detail-item">
                                                <label>Phone Number:</label>
                                                <p>${user.phone || 'N/A'}</p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="detail-section">
                                        <h4>Account Type</h4>
                                        <div class="detail-grid">
                                            <div class="detail-item">
                                                <label>User Role:</label>
                                                <p>
                                                    <span class="badge badge-shipped">Customer</span>
                                                </p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="detail-section">
                                        <h4>Registration Details</h4>
                                        <div class="detail-grid">
                                            <div class="detail-item">
                                                <label>Registration Date:</label>
                                                <p>${joinDateFormatted}</p>
                                            </div>
                                            <div class="detail-item">
                                                <label>Registration Time:</label>
                                                <p>${joinTimeFormatted}</p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="modal-footer">
                                    <button class="btn-action btn-delete" onclick="confirmDeleteUser(${user.id})">Delete User</button>
                                    <button class="btn-action btn-view" onclick="this.parentElement.parentElement.parentElement.remove()">Close</button>
                                </div>
                            </div>
                        `;
                        document.body.appendChild(modal);
                    } 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 = `
                <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: 600px; box-shadow: 0 10px 40px rgba(0,0,0,0.3); max-height: 85vh; overflow-y: auto;">
                        <h3 style="margin-top: 0; color: #333;">Add New Service</h3>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Service Title</label>
                            <input type="text" id="newServiceTitle" placeholder="e.g., Kitchen Design" 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;">Service Image</label>
                            <div style="position: relative; border: 2px dashed #d4a574; border-radius: 6px; padding: 20px; 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: 10px; display: none;">
                                    <img id="previewImg" style="max-width: 100%; max-height: 200px; border-radius: 4px;">
                                    <p id="fileName" style="margin: 5px 0 0 0; font-size: 12px; color: #666;"></p>
                                </div>
                            </div>
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Service Link (Optional)</label>
                            <input type="text" id="newServiceLink" placeholder="e.g., kitchen-design.html" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            <small style="color: #999; display: block; margin-top: 5px;">Leave blank for no link</small>
                        </div>
                        <div style="margin-bottom: 20px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Service Description</label>
                            <textarea id="newServiceDesc" placeholder="Enter detailed service description..." style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px; min-height: 120px; resize: vertical;"></textarea>
                        </div>
                        <div style="display: flex; gap: 10px; justify-content: flex-end;">
                            <button onclick="this.parentElement.parentElement.parentElement.remove()" style="padding: 10px 20px; background: #ddd; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                            <button onclick="saveNewService()" style="padding: 10px 20px; background: #d4a574; color: white; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Add Service</button>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            
            // Setup file upload handlers
            const fileInput = document.getElementById('newServiceImage');
            const uploadArea = document.getElementById('uploadArea');
            
            // Click to upload
            uploadArea.addEventListener('click', () => fileInput.click());
            
            // File selection handler
            fileInput.addEventListener('change', (e) => {
                handleImageSelect(e.target.files[0]);
            });
            
            // Drag and drop
            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 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('fileName').textContent = file.name;
                document.getElementById('imagePreview').style.display = 'block';
                document.getElementById('newServiceImage').files = new DataTransfer().items;
            };
            reader.readAsDataURL(file);
            
            // Store file for later upload
            document.getElementById('newServiceImage').file = file;
        }

        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(serviceIndex, serviceData) {
            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: 600px; 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 Service</h3>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Service Title</label>
                            <input type="text" id="editServiceTitle" value="${serviceData.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;">Service Image URL</label>
                            <input type="text" id="editServiceImage" value="${serviceData.image}" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px;">
                            <small style="color: #999; display: block; margin-top: 5px;">e.g., assets/img/service/service_2_1.jpg</small>
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 600; color: #333;">Service Description</label>
                            <textarea id="editServiceDesc" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 14px; min-height: 100px; resize: vertical;" placeholder="Enter service description">${serviceData.description}</textarea>
                        </div>
                        <div style="display: flex; gap: 10px; justify-content: flex-end;">
                            <button onclick="this.parentElement.parentElement.parentElement.remove()" style="padding: 10px 20px; background: #ddd; border: none; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                            <button onclick="saveServiceChanges(${serviceData.index})" 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 saveServiceChanges(serviceIndex) {
            const title = document.getElementById('editServiceTitle').value;
            const image = document.getElementById('editServiceImage').value;
            const description = document.getElementById('editServiceDesc').value;

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

            const formData = new FormData();
            formData.append('action', 'update_service');
            formData.append('service_index', serviceIndex);
            formData.append('title', title);
            formData.append('image', image);
            formData.append('description', description);

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

        function deleteService(serviceIndex, serviceTitle) {
            if (!confirm(`Are you sure you want to delete the service "${serviceTitle}"? This will also delete the service.php file.`)) {
                return;
            }

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

            fetch('api/delete-service.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Service deleted successfully!');
                    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
        function switchProjectTab(tabName, event) {
            event.preventDefault();
            
            // Hide all tabs
            document.getElementById('recent-projects-tab').style.display = 'none';
            document.getElementById('projects-tab').style.display = 'none';
            
            // Remove active class from all buttons
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.style.borderBottom = '3px solid transparent';
                btn.style.color = '#999';
            });
            
            // Show selected tab
            if (tabName === 'recent') {
                document.getElementById('recent-projects-tab').style.display = 'block';
            } else {
                document.getElementById('projects-tab').style.display = 'block';
            }
            
            // Add active class to clicked button
            event.target.style.borderBottom = '3px solid #3366cc';
            event.target.style.color = '#3366cc';
        }

        function openAddProjectModal(projectType = 'recent') {
            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: 500px; box-shadow: 0 10px 40px rgba(0,0,0,0.3);">
                        <h3 style="margin-top: 0; color: #333;">Add ${projectType === 'recent' ? 'Recent Project' : 'Project'}</h3>
                        <form id="projectForm" enctype="multipart/form-data">
                            <input type="hidden" id="projectType" value="${projectType}">
                            <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="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" 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, image, projectType = 'recent') {
            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: 500px; box-shadow: 0 10px 40px rgba(0,0,0,0.3);">
                        <h3 style="margin-top: 0; color: #333;">Edit ${projectType === 'recent' ? 'Recent Project' : 'Project'}</h3>
                        <form id="projectEditForm" enctype="multipart/form-data">
                            <input type="hidden" id="editProjectType" value="${projectType}">
                            <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="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" 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() {
            const title = document.getElementById('projectTitle').value.trim();
            const category = document.getElementById('projectCategory').value.trim();
            const projectType = document.getElementById('projectType').value;
            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;
            }

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

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

        function submitEditProject(id) {
            const title = document.getElementById('editProjectTitle').value.trim();
            const category = document.getElementById('editProjectCategory').value.trim();
            const projectType = document.getElementById('editProjectType').value;
            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;
            }

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

            const endpoint = projectType === 'recent' ? 'admin-edit-project.php' : 'admin-edit-project-php.php';

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

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

            const formData = new FormData();
            formData.append('project_id', id);
            formData.append('project_type', projectType);

            const endpoint = projectType === 'recent' ? 'admin-delete-project.php' : 'admin-delete-project-php.php';

            fetch(endpoint, {
                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 = '₹' + (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 = event.target;
            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 saveSystemSettings() {
            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 = event.target;
            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');
                } 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';
            });
        }

        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>

