<?php
session_start();
require_once __DIR__ . '/config/db.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: staff-login.php');
    exit;
}

$userRole = (string)($_SESSION['user_role'] ?? '');
if (!in_array($userRole, ['admin', 'staff'], true)) {
    header('Location: shop.php');
    exit;
}

$userId = (int)$_SESSION['user_id'];

$user = ['name' => 'Staff Member', 'email' => '', 'phone' => ''];
$userStmt = $connection->prepare('SELECT name, email, phone FROM users WHERE id = ? LIMIT 1');
if ($userStmt) {
    $userStmt->bind_param('i', $userId);
    $userStmt->execute();
    $userRes = $userStmt->get_result();
    if ($userRes && $userRes->num_rows > 0) {
        $row = $userRes->fetch_assoc();
        $user['name'] = (string)($row['name'] ?? $user['name']);
        $user['email'] = (string)($row['email'] ?? '');
        $user['phone'] = (string)($row['phone'] ?? '');
    }
    $userStmt->close();
}

$hasVerification = false;
$colCheck = $connection->query("SHOW COLUMNS FROM consultations LIKE 'verification_status'");
if ($colCheck && $colCheck->num_rows > 0) {
    $hasVerification = true;
}
$verificationSelect = $hasVerification ? 'verification_status' : 'status AS verification_status';

function loadConsultations(mysqli $connection, string $verificationSelect): array {
    $items = [];
    $sql = "SELECT id, first_name, last_name, name, email, phone, consultation_type, preferred_date, budget_range, {$verificationSelect}, status FROM consultations ORDER BY created_at DESC LIMIT 120";
    $res = $connection->query($sql);
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $first = trim((string)($row['first_name'] ?? ''));
            $last = trim((string)($row['last_name'] ?? ''));
            $fallback = trim((string)($row['name'] ?? ''));
            $name = trim($first . ' ' . $last);
            if ($name === '') {
                $name = $fallback !== '' ? $fallback : 'Customer';
            }
            $items[] = [
                'id' => (int)($row['id'] ?? 0),
                'name' => $name,
                'email' => (string)($row['email'] ?? ''),
                'phone' => (string)($row['phone'] ?? ''),
                'consultation_type' => (string)($row['consultation_type'] ?? ''),
                'preferred_date' => (string)($row['preferred_date'] ?? ''),
                'budget_range' => (string)($row['budget_range'] ?? ''),
                'verification_status' => strtolower((string)($row['verification_status'] ?? 'pending')),
                'status' => strtolower((string)($row['status'] ?? 'pending')),
            ];
        }
    }
    return $items;
}

function loadOrders(mysqli $connection): array {
    $orders = [];
    $res = $connection->query("SELECT o.id, o.total, o.status, o.created_at, u.name AS customer_name, u.email AS customer_email, o.phone FROM orders o JOIN users u ON o.user_id = u.id ORDER BY o.created_at DESC LIMIT 120");
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $orders[] = [
                'id' => (int)($row['id'] ?? 0),
                'total' => (float)($row['total'] ?? 0),
                'status' => strtolower((string)($row['status'] ?? 'pending')),
                'created_at' => (string)($row['created_at'] ?? ''),
                'customer_name' => (string)($row['customer_name'] ?? ''),
                'customer_email' => (string)($row['customer_email'] ?? ''),
                'phone' => (string)($row['phone'] ?? ''),
            ];
        }
    }
    return $orders;
}

function loadServices(mysqli $connection): array {
    $connection->query("CREATE TABLE IF NOT EXISTS services (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        image VARCHAR(500) NOT NULL,
        link VARCHAR(500) DEFAULT '#',
        description TEXT NOT NULL,
        area_sqft INT,
        price DECIMAL(10,2),
        duration VARCHAR(100),
        status VARCHAR(50) DEFAULT 'ACTIVE',
        sort_order INT NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $items = [];
    $res = $connection->query("SELECT id, title, image, description, area_sqft, price, duration, sort_order FROM services WHERE is_active = 1 ORDER BY sort_order ASC, id ASC");
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $items[] = $row;
        }
    }
    return $items;
}

function loadProjects(mysqli $connection): array {
    $connection->query("CREATE TABLE IF NOT EXISTS projects (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255) NOT NULL,
        category VARCHAR(100) NOT NULL DEFAULT 'Interior',
        location VARCHAR(120) NOT NULL DEFAULT '',
        project_year VARCHAR(10) NOT NULL DEFAULT '',
        image VARCHAR(500) NOT NULL DEFAULT '',
        description TEXT,
        sort_order INT NOT NULL DEFAULT 0,
        is_active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
    $items = [];
    $res = $connection->query("SELECT id, title, category, location, project_year, image, description, sort_order FROM projects WHERE is_active = 1 ORDER BY sort_order ASC, id DESC");
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $items[] = $row;
        }
    }
    return $items;
}

if (isset($_GET['ajax']) && $_GET['ajax'] === 'orders') {
    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'orders' => loadOrders($connection)]);
    exit;
}
if (isset($_GET['ajax']) && $_GET['ajax'] === 'services') {
    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'services' => loadServices($connection)]);
    exit;
}
if (isset($_GET['ajax']) && $_GET['ajax'] === 'projects') {
    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'projects' => loadProjects($connection)]);
    exit;
}
if (isset($_GET['ajax']) && $_GET['ajax'] === 'profile_update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    $name = trim((string)($_POST['name'] ?? ''));
    $email = trim((string)($_POST['email'] ?? ''));
    $phone = trim((string)($_POST['phone'] ?? ''));
    $currentPassword = (string)($_POST['current_password'] ?? '');
    $newPassword = (string)($_POST['new_password'] ?? '');
    $confirmPassword = (string)($_POST['confirm_password'] ?? '');

    if ($name === '' || $email === '') {
        echo json_encode(['success' => false, 'message' => 'Name and email are required']);
        exit;
    }
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => 'Please provide a valid email']);
        exit;
    }

    $emailStmt = $connection->prepare('SELECT id FROM users WHERE email = ? AND id <> ? LIMIT 1');
    if ($emailStmt) {
        $emailStmt->bind_param('si', $email, $userId);
        $emailStmt->execute();
        $dupRes = $emailStmt->get_result();
        if ($dupRes && $dupRes->num_rows > 0) {
            $emailStmt->close();
            echo json_encode(['success' => false, 'message' => 'Email already in use by another account']);
            exit;
        }
        $emailStmt->close();
    }

    if ($newPassword !== '') {
        if (strlen($newPassword) < 6) {
            echo json_encode(['success' => false, 'message' => 'New password must be at least 6 characters']);
            exit;
        }
        if ($newPassword !== $confirmPassword) {
            echo json_encode(['success' => false, 'message' => 'Password confirmation does not match']);
            exit;
        }
        if ($currentPassword === '') {
            echo json_encode(['success' => false, 'message' => 'Current password is required']);
            exit;
        }

        $passStmt = $connection->prepare('SELECT password FROM users WHERE id = ? LIMIT 1');
        if (!$passStmt) {
            echo json_encode(['success' => false, 'message' => 'Unable to verify current password']);
            exit;
        }
        $passStmt->bind_param('i', $userId);
        $passStmt->execute();
        $passRes = $passStmt->get_result();
        $passRow = $passRes ? $passRes->fetch_assoc() : null;
        $passStmt->close();
        $dbPassword = (string)($passRow['password'] ?? '');
        if ($dbPassword === '' || !password_verify($currentPassword, $dbPassword)) {
            echo json_encode(['success' => false, 'message' => 'Current password is incorrect']);
            exit;
        }

        $newHash = password_hash($newPassword, PASSWORD_DEFAULT);
        $updateStmt = $connection->prepare('UPDATE users SET name = ?, email = ?, phone = ?, password = ? WHERE id = ?');
        if (!$updateStmt) {
            echo json_encode(['success' => false, 'message' => 'Unable to update profile']);
            exit;
        }
        $updateStmt->bind_param('ssssi', $name, $email, $phone, $newHash, $userId);
    } else {
        $updateStmt = $connection->prepare('UPDATE users SET name = ?, email = ?, phone = ? WHERE id = ?');
        if (!$updateStmt) {
            echo json_encode(['success' => false, 'message' => 'Unable to update profile']);
            exit;
        }
        $updateStmt->bind_param('sssi', $name, $email, $phone, $userId);
    }

    $ok = $updateStmt->execute();
    $updateStmt->close();
    if (!$ok) {
        echo json_encode(['success' => false, 'message' => 'Failed to save profile']);
        exit;
    }

    $_SESSION['name'] = $name;
    echo json_encode([
        'success' => true,
        'message' => 'Profile updated successfully',
        'user' => ['name' => $name, 'email' => $email, 'phone' => $phone, 'initial' => strtoupper(substr($name, 0, 1))]
    ]);
    exit;
}

$consultations = loadConsultations($connection, $verificationSelect);
$orders = loadOrders($connection);
$services = loadServices($connection);
$projects = loadProjects($connection);

$consultationCount = count($consultations);
$totalOrders = count($orders);
$serviceCount = count($services);
$projectCount = count($projects);
$pendingConsultations = 0;
foreach ($consultations as $item) {
    if (($item['status'] ?? '') === 'pending') {
        $pendingConsultations++;
    }
}

$initial = strtoupper(substr(trim((string)$user['name']), 0, 1));
if ($initial === '') {
    $initial = 'S';
}

function statusClass(string $value): string {
    $v = strtolower($value);
    if (in_array($v, ['approved', 'processing', 'shipped', 'delivered', 'verified'], true)) {
        return 'ok';
    }
    if (in_array($v, ['declined', 'rejected', 'cancelled'], true)) {
        return 'bad';
    }
    return 'pend';
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
    <title>Staff Dashboard</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="assets/css/fontawesome.min.css">
    <style>
        :root{--bg:#eff2f7;--surface:#fff;--sb:#2f435a;--sbTop:#2a3d52;--active:#3a5579;--primary:#627ce8;--txt:#243242;--mut:#6f7b89;--line:#e2e8f1;--ok:#2f8f64;--bad:#b94a4a;--warn:#c08a3f}
        *{box-sizing:border-box}body{margin:0;background:var(--bg);font-family:'DM Sans',Segoe UI,sans-serif;color:var(--txt)}
        .app{min-height:100vh;display:grid;grid-template-columns:270px 1fr}.side{background:var(--sb);color:#d9e2ee;position:sticky;top:0;height:100vh;overflow-y:auto;display:flex;flex-direction:column;scrollbar-width:thin;scrollbar-color:rgba(113,144,255,0.5) transparent}.side::-webkit-scrollbar{width:8px}.side::-webkit-scrollbar-track{background:transparent}.side::-webkit-scrollbar-thumb{background:rgba(113,144,255,0.5);border-radius:4px}.side::-webkit-scrollbar-thumb:hover{background:rgba(113,144,255,0.8)}.side h2{margin:0;background:var(--sbTop);padding:clamp(12px,3vw,18px) 18px;color:#7f95ff;font-size:clamp(20px,4vw,26px);font-weight:800;flex-shrink:0}
        .nav{padding:clamp(8px,2vw,12px) 0;flex:1;overflow-y:auto;display:flex;flex-direction:column;scrollbar-width:thin;scrollbar-color:rgba(113,144,255,0.4) transparent}.nav::-webkit-scrollbar{width:6px}.nav::-webkit-scrollbar-track{background:transparent}.nav::-webkit-scrollbar-thumb{background:rgba(113,144,255,0.4);border-radius:3px}.nav::-webkit-scrollbar-thumb:hover{background:rgba(113,144,255,0.7)}.nav button{width:100%;border:0;background:none;color:#dde6f2;padding:clamp(8px,2vw,12px) 16px;text-align:left;display:flex;justify-content:space-between;align-items:center;border-left:4px solid transparent;font-weight:600;cursor:pointer;transition:all 0.3s ease;font-size:clamp(12px,2vw,14px)}.nav button:hover{background:rgba(58,85,121,0.5)}.nav button.active{background:var(--active);border-left-color:#7190ff}
        .badge{min-width:24px;height:24px;border-radius:999px;background:var(--primary);color:#fff;display:inline-flex;align-items:center;justify-content:center;font-size:11px;font-weight:800;padding:0 7px}
        .main{min-width:0}.top{height:74px;background:#fff;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;align-items:center;padding:0 16px}.title{margin:0;color:var(--primary);font-size:34px;font-weight:800}
        .right{display:flex;align-items:center;gap:10px}.avatar{width:38px;height:38px;border-radius:999px;background:var(--primary);color:#fff;display:grid;place-items:center;font-size:15px;font-weight:800}.logout{background:#de3f4f;color:#fff;text-decoration:none;border-radius:8px;padding:9px 13px;font-size:13px;font-weight:700}
        .menu{display:none;border:1px solid var(--line);background:#fff;border-radius:8px;width:36px;height:36px;align-items:center;justify-content:center}
        .content{padding:16px}.section{display:none}.section.active{display:block}.h{margin:0 0 12px;font-size:28px;font-weight:800}
        .cards{display:grid;grid-template-columns:repeat(4,1fr);gap:12px}.card{background:#fff;border:1px solid var(--line);border-left:4px solid #6e86eb;border-radius:12px;padding:14px;min-height:100px;box-shadow:0 5px 14px rgba(20,30,45,.06);display:grid;align-content:center;justify-items:center;text-align:center}.card .l{font-size:11px;color:#7b8794;text-transform:uppercase;font-weight:700}.card .n{font-size:38px;color:var(--primary);font-weight:800;line-height:1}
        .panel{margin-top:14px;background:#fff;border:1px solid var(--line);border-radius:12px;overflow:hidden;box-shadow:0 5px 14px rgba(20,30,45,.06)}.ph{padding:12px 14px;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap}.live{font-size:11px;font-weight:800;border:1px solid #cde5d8;background:#eef9f2;color:#267347;border-radius:999px;padding:6px 10px}
        .table-wrap{overflow:auto}table{width:100%;border-collapse:collapse;min-width:860px}th,td{padding:10px;border-bottom:1px solid var(--line);font-size:12px;vertical-align:top}th{background:#f8fbff;color:#6f7a87;text-transform:uppercase;font-size:11px;font-weight:800}
        .nm{display:block;font-weight:700}.ln{color:var(--mut)}
        .sb{display:inline-flex;padding:4px 9px;border-radius:999px;font-size:10px;font-weight:700;text-transform:uppercase}.pend{background:#fff4e6;color:var(--warn);border:1px solid #f0d5ae}.ok{background:#e8f7ef;color:var(--ok);border:1px solid #c8e8d7}.bad{background:#fdecec;color:var(--bad);border:1px solid #f1c9c9}
        .acts{display:flex;gap:6px;flex-wrap:wrap}.btnx{border:1px solid transparent;border-radius:8px;padding:6px 9px;font-size:11px;font-weight:700;cursor:pointer}.btn-app{background:#e8f7ef;color:var(--ok);border-color:#c8e8d7}.btn-ship{background:#eaf1ff;color:#4466d3;border-color:#cdd9fb}.btn-dec{background:#fdecec;color:var(--bad);border-color:#f1c9c9}.btnx:disabled{opacity:.5;cursor:not-allowed}
        .grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.box{background:#fff;border:1px solid var(--line);border-radius:12px;overflow:hidden;box-shadow:0 5px 14px rgba(20,30,45,.06)}.box img{width:100%;height:180px;object-fit:cover;display:block}.box .b{padding:12px}.box h4{margin:0 0 6px;font-size:16px}.box p{margin:0;color:var(--mut);font-size:12px;line-height:1.5}
        .ph .add-btn{background:#edf3ff;color:#3c63df;border:1px solid #cfdcfb;border-radius:8px;padding:7px 11px;font-size:12px;font-weight:700;cursor:pointer}
        .box .meta{margin-bottom:8px}
        .box .actions{display:flex;gap:8px;flex-wrap:wrap}
        .btn-mini{border-radius:7px;border:1px solid transparent;padding:6px 9px;font-size:11px;font-weight:700;cursor:pointer}
        .btn-edit{background:#eaf1ff;border-color:#cedbfc;color:#385ad1}
        .btn-del{background:#fdecec;border-color:#f1c9c9;color:#b94a4a}
        .modal{display:none;position:fixed;inset:0;z-index:70;background:rgba(9,17,28,.56);padding:16px;overflow:auto}
        .modal.show{display:block}
        .modal-card{max-width:760px;margin:20px auto;background:#fff;border:1px solid var(--line);border-radius:12px;box-shadow:0 14px 30px rgba(10,20,30,.18)}
        .modal-head{padding:12px 14px;border-bottom:1px solid var(--line);display:flex;justify-content:space-between;align-items:center}
        .modal-head h3{margin:0;font-size:18px;font-weight:800}
        .close-btn{border:1px solid var(--line);background:#fff;border-radius:8px;width:34px;height:34px;font-size:18px;line-height:1;cursor:pointer}
        .frm{padding:14px;display:grid;gap:10px}
        .fg2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
        .frm label{font-size:12px;font-weight:700;color:#4c5968}
        .frm input,.frm textarea{width:100%;border:1px solid #d8e0ea;border-radius:8px;padding:9px 10px;font-size:13px}
        .frm textarea{min-height:96px;resize:vertical}
        .preview{width:100%;max-height:180px;object-fit:cover;border-radius:9px;border:1px solid var(--line);display:none}
        .modal-foot{padding:12px 14px;border-top:1px solid var(--line);display:flex;justify-content:flex-end;gap:8px}
        .btn-pri{background:#4467de;color:#fff;border:1px solid #3e5fd1;border-radius:8px;padding:8px 12px;font-size:12px;font-weight:700;cursor:pointer}
        .btn-sec{background:#fff;color:#5e6b79;border:1px solid #d8e0ea;border-radius:8px;padding:8px 12px;font-size:12px;font-weight:700;cursor:pointer}
        .profile-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
        .profile-card{background:#fff;border:1px solid var(--line);border-radius:12px;box-shadow:0 5px 14px rgba(20,30,45,.06);overflow:hidden}
        .profile-card .head{padding:12px 14px;border-bottom:1px solid var(--line);font-size:14px;font-weight:800}
        .profile-form{padding:14px;display:grid;gap:10px}
        .profile-form label{font-size:12px;font-weight:700;color:#4c5968}
        .profile-form input{width:100%;border:1px solid #d8e0ea;border-radius:8px;padding:9px 10px;font-size:13px}
        .profile-actions{display:flex;justify-content:flex-end}
        .overlay{display:none}.toast{position:fixed;right:12px;bottom:12px;background:#2f435a;color:#fff;padding:11px 12px;border-radius:10px;font-size:12px;font-weight:700;opacity:0;transform:translateY(8px);transition:.2s;z-index:80}.toast.on{opacity:1;transform:none}
        @media(max-width:1100px){.cards{grid-template-columns:repeat(2,1fr)}.grid{grid-template-columns:repeat(2,minmax(0,1fr))}.consult-card-container{grid-template-columns:1fr}.table-wrap{overflow-x:auto}.table-wrap table{min-width:600px}.side{width:clamp(200px,40vw,270px)}}
        @media(max-width:991px){.app{display:block}.side{position:fixed;left:0;top:0;bottom:0;width:270px;max-width:80vw;z-index:50;transform:translateX(-100%);transition:transform 0.3s ease;height:100vh;flex-direction:column}.side.open{transform:translateX(0)}.overlay.show{display:block;position:fixed;inset:0;background:rgba(10,18,28,.46);z-index:49}.menu{display:inline-flex}.title{font-size:28px}.desktop-view{display:none!important}.mobile-view{display:block!important}}
        @media(max-width:768px){.app{display:block}.side{width:100vw;max-width:100%;padding-right:60px;overflow-y:auto}.cards,.grid,.fg2,.profile-grid,.consult-card-container{grid-template-columns:1fr}.content{padding:12px}.h{font-size:22px}.top{height:auto;min-height:68px;padding:10px 12px}.right{font-size:13px;flex-wrap:wrap;justify-content:flex-end}.desktop-view{display:none!important}.mobile-view{display:block!important}.table-wrap{overflow-x:auto}.table-wrap table{min-width:100%;font-size:10px;padding:6px}.table-wrap td,.table-wrap th{padding:6px 4px}.nav button{padding:clamp(10px,2vw,12px) 12px;font-size:clamp(11px,2vw,14px)}.side h2{padding:clamp(10px,2vw,14px) 12px;font-size:clamp(18px,4vw,24px)}}
        @media(max-width:480px){.consult-card-value{max-width:55%}.consult-card-btn{font-size:10px;padding:6px 6px}.cards{grid-template-columns:1fr}.content{padding:8px}.right{gap:6px}.side{width:100vw}.nav button{padding:clamp(8px,1.5vw,10px) 10px;font-size:clamp(11px,1.8vw,12px)}.side h2{padding:clamp(8px,1.5vw,12px) 10px;font-size:clamp(16px,3vw,20px)}}
    </style>
</head>
<body>
<div class="overlay" id="overlay"></div>
<div class="app">
    <aside class="side" id="side">
        <h2>Staff</h2>
        <nav class="nav">
            <button class="active" data-target="overview"><span>Overview</span><span class="badge">4</span></button>
            <button data-target="consultation"><span>Consultation</span><span class="badge" id="bConsult"><?php echo (int)$pendingConsultations; ?></span></button>
            <button data-target="order"><span>Order</span><span class="badge" id="bOrder"><?php echo (int)$totalOrders; ?></span></button>
            <button data-target="service"><span>Service</span><span class="badge" id="bService"><?php echo (int)$serviceCount; ?></span></button>
            <button data-target="project"><span>Project</span><span class="badge" id="bProject"><?php echo (int)$projectCount; ?></span></button>
            <button data-target="profile"><span>Profile</span><span class="badge">1</span></button>
        </nav>
    </aside>

    <main class="main">
        <header class="top">
            <div style="display:flex;align-items:center;gap:10px"><button class="menu" id="menu"><i class="fa-solid fa-bars"></i></button><h1 class="title">Staff Dashboard</h1></div>
            <div class="right"><span id="headerUserName"><?php echo htmlspecialchars((string)$user['name']); ?></span><span class="avatar" id="headerAvatar"><?php echo htmlspecialchars($initial); ?></span><a class="logout" href="auth-system/logout.php">Logout</a></div>
        </header>

        <div class="content">
            <section class="section active" data-section="overview">
                <h2 class="h">Real-Time Statistics</h2>
                <div class="cards">
                    <article class="card"><div class="l">Consultations</div><div class="n" id="stConsult"><?php echo (int)$consultationCount; ?></div></article>
                    <article class="card"><div class="l">Orders</div><div class="n" id="stOrder"><?php echo (int)$totalOrders; ?></div></article>
                    <article class="card"><div class="l">Services</div><div class="n" id="stService"><?php echo (int)$serviceCount; ?></div></article>
                    <article class="card"><div class="l">Projects</div><div class="n" id="stProject"><?php echo (int)$projectCount; ?></div></article>
                </div>
            </section>

            <section class="section" data-section="consultation">
                <div class="panel"><div class="ph"><strong>Consultation Requests</strong><span class="live">Live Updates</span></div>
                    <!-- Desktop Table View -->
                    <div class="table-wrap desktop-view"><table><thead><tr><th>Contact</th><th>Consultation</th><th>Verification</th><th>Status</th><th>Actions</th></tr></thead><tbody id="consultBody">
                        <?php if (empty($consultations)): ?>
                            <tr><td colspan="5" style="text-align:center;color:#7b8794;padding:14px">No consultation data.</td></tr>
                        <?php else: foreach ($consultations as $it): $id = (int)$it['id']; $pending = ($it['status'] === 'pending'); ?>
                            <tr data-id="<?php echo $id; ?>" class="consult-row"><td><span class="nm"><?php echo htmlspecialchars((string)$it['name']); ?></span><div class="ln"><?php echo htmlspecialchars((string)$it['email']); ?></div><div class="ln"><?php echo htmlspecialchars((string)$it['phone']); ?></div></td><td><div class="ln"><strong><?php echo htmlspecialchars(ucfirst(str_replace('_', ' ', (string)$it['consultation_type']))); ?></strong></div><div class="ln">Preferred: <?php echo htmlspecialchars((string)$it['preferred_date']); ?></div><div class="ln">Budget: <?php echo htmlspecialchars((string)$it['budget_range']); ?></div></td><td><span class="sb <?php echo statusClass((string)$it['verification_status']); ?> js-v"><?php echo htmlspecialchars((string)$it['verification_status']); ?></span></td><td><span class="sb <?php echo statusClass((string)$it['status']); ?> js-cs"><?php echo htmlspecialchars((string)$it['status']); ?></span></td><td><div class="acts"><button class="btnx btn-app btn-approve" data-id="<?php echo $id; ?>" onclick="approveConsultation(<?php echo $id; ?>)" <?php echo $pending ? '' : 'disabled'; ?>>Approve</button><button class="btnx btn-dec btn-decline" data-id="<?php echo $id; ?>" onclick="declineConsultation(<?php echo $id; ?>)" <?php echo $pending ? '' : 'disabled'; ?>>Decline</button></div></td></tr>
                        <?php endforeach; endif; ?>
                    </tbody></table></div>
                    
                    <!-- Mobile Card View -->
                    <div id="consultCardView" class="mobile-view consult-card-container" style="display:none; padding:12px;"></div>
                </div>
            </section>
            
            <style>
                /* Responsive Consultation Styles */
                .consult-card-container {
                    display: grid;
                    gap: 12px;
                    grid-template-columns: 1fr;
                }
                
                .consult-card {
                    background: #fff;
                    border: 1px solid var(--line);
                    border-radius: 10px;
                    padding: 12px;
                    box-shadow: 0 2px 8px rgba(20,30,45,.05);
                }
                
                .consult-card-header {
                    display: flex;
                    justify-content: space-between;
                    align-items: start;
                    margin-bottom: 10px;
                    gap: 8px;
                }
                
                .consult-card-name {
                    font-weight: 700;
                    color: var(--txt);
                    font-size: 13px;
                }
                
                .consult-card-status {
                    display: flex;
                    gap: 6px;
                    flex-wrap: wrap;
                }
                
                .consult-card-info {
                    display: grid;
                    gap: 6px;
                    font-size: 12px;
                    color: var(--mut);
                    margin-bottom: 10px;
                }
                
                .consult-card-row {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    padding: 6px 0;
                    border-bottom: 1px solid #f0f3f7;
                }
                
                .consult-card-row:last-child {
                    border-bottom: none;
                }
                
                .consult-card-label {
                    font-weight: 600;
                    color: #7b8794;
                    font-size: 11px;
                    text-transform: uppercase;
                }
                
                .consult-card-value {
                    color: var(--txt);
                    text-align: right;
                    max-width: 65%;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
                
                .consult-card-actions {
                    display: flex;
                    gap: 6px;
                    margin-top: 10px;
                    border-top: 1px solid #f0f3f7;
                    padding-top: 10px;
                }
                
                .consult-card-btn {
                    flex: 1;
                    border: 1px solid transparent;
                    border-radius: 6px;
                    padding: 7px 8px;
                    font-size: 11px;
                    font-weight: 700;
                    cursor: pointer;
                    transition: all 0.2s ease;
                    text-align: center;
                }
                
                .consult-card-btn:disabled {
                    opacity: 0.5;
                    cursor: not-allowed;
                }
                
                .consult-card-btn.btn-app-card {
                    background: #e8f7ef;
                    color: var(--ok);
                    border-color: #c8e8d7;
                }
                
                .consult-card-btn.btn-app-card:hover:not(:disabled) {
                    background: #d1f0e6;
                    transform: translateY(-1px);
                }
                
                .consult-card-btn.btn-dec-card {
                    background: #fdecec;
                    color: var(--bad);
                    border-color: #f1c9c9;
                }
                
                .consult-card-btn.btn-dec-card:hover:not(:disabled) {
                    background: #f8d5d5;
                    transform: translateY(-1px);
                }
                
                .btn-approve.loading::after,
                .btn-decline.loading::after {
                    content: ' ...';
                    animation: dots 1.5s steps(4, end) infinite;
                }
                
                @keyframes dots {
                    0%, 20% { content: ' .'; }
                    40% { content: ' ..'; }
                    60% { content: ' ...'; }
                }
                
                /* Desktop - Show Table */
                @media(min-width: 1024px) {
                    .desktop-view { display: block !important; }
                    .mobile-view { display: none !important; }
                }
                
                /* Tablet - Show Table but with responsive adjustments */
                @media(max-width: 1023px) and (min-width: 769px) {
                    .desktop-view { display: block !important; }
                    .mobile-view { display: none !important; }
                    table { min-width: 720px; }
                    th, td { padding: 8px; font-size: 11px; }
                    .nm { font-size: 12px; }
                    .ln { font-size: 11px; }
                }
                
                /* Mobile Tablet - Show Cards */
                @media(max-width: 768px) {
                    .desktop-view { display: none !important; }
                    .mobile-view { display: block !important; }
                    .consult-card-container {
                        grid-template-columns: 1fr;
                    }
                }
                
                /* Loading state animation */
                .btn-approve.processing,
                .btn-decline.processing {
                    opacity: 0.7;
                    pointer-events: none;
                }
                
                /* Success animation */
                .consult-row.success {
                    animation: successFlash 0.5s ease;
                }
                
                @keyframes successFlash {
                    0% { background: #e8f7ef; }
                    100% { background: transparent; }
                }
            </style>

            <section class="section" data-section="order">
                <div class="panel"><div class="ph"><strong>Customer Orders</strong><span class="live">Auto Fetch</span></div>
                    <div class="table-wrap"><table><thead><tr><th>Order</th><th>Customer</th><th>Status</th><th>Total</th><th>Actions</th></tr></thead><tbody id="orderBody">
                        <?php if (empty($orders)): ?>
                            <tr><td colspan="5" style="text-align:center;color:#7b8794;padding:14px">No orders found.</td></tr>
                        <?php else: foreach ($orders as $od): $st=(string)$od['status']; ?>
                            <tr data-id="<?php echo (int)$od['id']; ?>"><td><span class="nm">#<?php echo (int)$od['id']; ?></span><div class="ln"><?php echo htmlspecialchars((string)$od['created_at']); ?></div></td><td><span class="nm"><?php echo htmlspecialchars((string)$od['customer_name']); ?></span><div class="ln"><?php echo htmlspecialchars((string)$od['customer_email']); ?></div><div class="ln"><?php echo htmlspecialchars((string)$od['phone']); ?></div></td><td><span class="sb <?php echo statusClass($st); ?> js-os"><?php echo htmlspecialchars($st); ?></span></td><td><strong>Rs <?php echo number_format((float)$od['total'], 2); ?></strong></td><td><div class="acts"><button class="btnx btn-app" onclick="updateOrderStatus(<?php echo (int)$od['id']; ?>,'processing','Order approved')" <?php echo $st === 'pending' ? '' : 'disabled'; ?>>Approve</button><button class="btnx btn-ship" onclick="updateOrderStatus(<?php echo (int)$od['id']; ?>,'shipped','Order shipped')" <?php echo in_array($st,['shipped','delivered','cancelled'],true) ? 'disabled' : ''; ?>>Shipped</button><button class="btnx btn-dec" onclick="updateOrderStatus(<?php echo (int)$od['id']; ?>,'cancelled','Order declined')" <?php echo in_array($st,['cancelled','delivered'],true) ? 'disabled' : ''; ?>>Decline</button></div></td></tr>
                        <?php endforeach; endif; ?>
                    </tbody></table></div>
                </div>
            </section>

            <section class="section" data-section="service">
                <div class="panel"><div class="ph"><strong>All Services</strong><button class="add-btn" type="button" onclick="openServiceModal()">+ Add Service</button></div><div class="table-wrap" style="padding:12px"><div class="grid" id="serviceGrid">
                    <?php if (empty($services)): ?><p style="color:#7b8794">No services found.</p><?php else: foreach ($services as $sv): ?>
                        <article class="box" data-id="<?php echo (int)($sv['id'] ?? 0); ?>"><img src="<?php echo htmlspecialchars((string)($sv['image'] ?? 'assets/img/service/service_1_1.jpg')); ?>" alt="Service"><div class="b"><h4><?php echo htmlspecialchars((string)($sv['title'] ?? 'Service')); ?></h4><p class="meta"><?php echo htmlspecialchars((string)($sv['description'] ?? '')); ?></p><div class="actions"><button class="btn-mini btn-edit" type="button" onclick="openServiceModal(<?php echo (int)($sv['id'] ?? 0); ?>)">Edit</button><button class="btn-mini btn-del" type="button" onclick="deleteService(<?php echo (int)($sv['id'] ?? 0); ?>)">Delete</button></div></div></article>
                    <?php endforeach; endif; ?>
                </div></div></div>
            </section>

            <section class="section" data-section="project">
                <div class="panel"><div class="ph"><strong>All Projects</strong><button class="add-btn" type="button" onclick="openProjectModal()">+ Add Project</button></div><div class="table-wrap" style="padding:12px"><div class="grid" id="projectGrid">
                    <?php if (empty($projects)): ?><p style="color:#7b8794">No projects found.</p><?php else: foreach ($projects as $pr): ?>
                        <article class="box" data-id="<?php echo (int)($pr['id'] ?? 0); ?>"><img src="<?php echo htmlspecialchars((string)($pr['image'] ?? 'assets/img/project/project_1_1.jpg')); ?>" alt="Project"><div class="b"><h4><?php echo htmlspecialchars((string)($pr['title'] ?? 'Project')); ?></h4><p class="meta"><?php echo htmlspecialchars((string)($pr['category'] ?? 'Interior')); ?><?php if (!empty($pr['location'])): ?> | <?php echo htmlspecialchars((string)$pr['location']); ?><?php endif; ?><?php if (!empty($pr['project_year'])): ?> | <?php echo htmlspecialchars((string)$pr['project_year']); ?><?php endif; ?></p><p class="meta"><?php echo htmlspecialchars((string)($pr['description'] ?? '')); ?></p><div class="actions"><button class="btn-mini btn-edit" type="button" onclick="openProjectModal(<?php echo (int)($pr['id'] ?? 0); ?>)">Edit</button><button class="btn-mini btn-del" type="button" onclick="deleteProject(<?php echo (int)($pr['id'] ?? 0); ?>)">Delete</button></div></div></article>
                    <?php endforeach; endif; ?>
                </div></div></div>
            </section>

            <section class="section" data-section="profile">
                <h2 class="h">Profile Settings</h2>
                <div class="profile-grid">
                    <div class="profile-card">
                        <div class="head">Account Information</div>
                        <form class="profile-form" onsubmit="return false;">
                            <div><label for="pfName">Full Name</label><input id="pfName" value="<?php echo htmlspecialchars((string)$user['name']); ?>"></div>
                            <div><label for="pfEmail">Email</label><input id="pfEmail" type="email" value="<?php echo htmlspecialchars((string)$user['email']); ?>"></div>
                            <div><label for="pfPhone">Phone</label><input id="pfPhone" value="<?php echo htmlspecialchars((string)$user['phone']); ?>"></div>
                            <div class="profile-actions"><button class="btn-pri" type="button" onclick="saveProfileAccount()">Save Account</button></div>
                        </form>
                    </div>
                    <div class="profile-card">
                        <div class="head">Change Password</div>
                        <form class="profile-form" onsubmit="return false;">
                            <div><label for="pfCurrent">Current Password</label><input id="pfCurrent" type="password"></div>
                            <div><label for="pfNew">New Password</label><input id="pfNew" type="password"></div>
                            <div><label for="pfConfirm">Confirm New Password</label><input id="pfConfirm" type="password"></div>
                            <div class="profile-actions"><button class="btn-pri" type="button" onclick="saveProfilePassword()">Update Password</button></div>
                        </form>
                    </div>
                </div>
            </section>
        </div>
    </main>
</div>

<div class="modal" id="serviceModal">
    <div class="modal-card">
        <div class="modal-head"><h3 id="serviceModalTitle">Add Service</h3><button class="close-btn" type="button" onclick="closeServiceModal()">x</button></div>
        <form class="frm" id="serviceForm">
            <input type="hidden" id="serviceId">
            <div><label for="serviceName">Title</label><input id="serviceName" required></div>
            <div><label for="serviceDesc">Description</label><textarea id="serviceDesc" required></textarea></div>
            <div class="fg2">
                <div><label for="servicePrice">Base Price</label><input id="servicePrice" type="number" min="1" value="1" required></div>
                <div><label for="serviceArea">Area (sqft)</label><input id="serviceArea" type="number" min="0" value="0"></div>
            </div>
            <div><label for="serviceDuration">Duration</label><input id="serviceDuration" value="N/A"></div>
            <div><label for="serviceImage">Image</label><input id="serviceImage" type="file" accept="image/*"></div>
            <img class="preview" id="servicePreview" alt="Service preview">
        </form>
        <div class="modal-foot"><button class="btn-sec" type="button" onclick="closeServiceModal()">Cancel</button><button class="btn-pri" type="button" onclick="saveService()">Save Service</button></div>
    </div>
</div>

<div class="modal" id="projectModal">
    <div class="modal-card">
        <div class="modal-head"><h3 id="projectModalTitle">Add Project</h3><button class="close-btn" type="button" onclick="closeProjectModal()">x</button></div>
        <form class="frm" id="projectForm">
            <input type="hidden" id="projectId">
            <div><label for="projectTitle">Title</label><input id="projectTitle" required></div>
            <div class="fg2">
                <div><label for="projectCategory">Category</label><input id="projectCategory" value="Interior" required></div>
                <div><label for="projectLocation">Location</label><input id="projectLocation"></div>
            </div>
            <div class="fg2">
                <div><label for="projectYear">Year</label><input id="projectYear"></div>
                <div><label for="projectSortOrder">Sort Order</label><input id="projectSortOrder" type="number" min="0" value="0"></div>
            </div>
            <div><label for="projectDesc">Description</label><textarea id="projectDesc"></textarea></div>
            <div><label for="projectImage">Image</label><input id="projectImage" type="file" accept="image/*"></div>
            <img class="preview" id="projectPreview" alt="Project preview">
        </form>
        <div class="modal-foot"><button class="btn-sec" type="button" onclick="closeProjectModal()">Cancel</button><button class="btn-pri" type="button" onclick="saveProject()">Save Project</button></div>
    </div>
</div>

<div class="toast" id="toast"></div>

<script>
(function(){
    var services = <?php echo json_encode($services, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>;
    var projects = <?php echo json_encode($projects, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>;
    var currentUser = <?php echo json_encode($user, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); ?>;

    var side=document.getElementById('side'), overlay=document.getElementById('overlay'), menu=document.getElementById('menu');
    if(menu){menu.onclick=function(){side.classList.add('open');overlay.classList.add('show')}}
    if(overlay){overlay.onclick=function(){side.classList.remove('open');overlay.classList.remove('show')}}

    var navBtns=[].slice.call(document.querySelectorAll('.nav button'));
    var sections=[].slice.call(document.querySelectorAll('.section'));
    navBtns.forEach(function(btn){btn.onclick=function(){var t=btn.getAttribute('data-target');navBtns.forEach(function(x){x.classList.toggle('active',x===btn)});sections.forEach(function(s){s.classList.toggle('active',s.getAttribute('data-section')===t)});if(window.innerWidth<=991){side.classList.remove('open');overlay.classList.remove('show')}}});

    function toast(msg){var t=document.getElementById('toast');if(!t)return;t.textContent=msg;t.classList.add('on');setTimeout(function(){t.classList.remove('on')},2200)}
    function n(v){return String(v||'').toLowerCase().trim()}
    function cls(v){v=n(v);if(['approved','processing','shipped','delivered','verified'].indexOf(v)!==-1)return'ok';if(['declined','cancelled','rejected'].indexOf(v)!==-1)return'bad';return'pend'}
    function esc(v){return String(v==null?'':v).replace(/[&<>"]/g,function(c){return({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'})[c]})}
    function setCounts(){var bS=document.getElementById('bService'),bP=document.getElementById('bProject'),sS=document.getElementById('stService'),sP=document.getElementById('stProject');if(bS)bS.textContent=services.length;if(bP)bP.textContent=projects.length;if(sS)sS.textContent=services.length;if(sP)sP.textContent=projects.length}
    function syncHeaderUser(u){var nm=(u&&u.name)?String(u.name):'';var hName=document.getElementById('headerUserName'),hAvatar=document.getElementById('headerAvatar');if(hName&&nm!=='')hName.textContent=nm;if(hAvatar&&nm!=='')hAvatar.textContent=nm.trim().charAt(0).toUpperCase()||'S'}

    function renderServices(){
        var grid=document.getElementById('serviceGrid');if(!grid)return;
        if(!services.length){grid.innerHTML='<p style="color:#7b8794">No services found.</p>';setCounts();return;}
        var html='';services.forEach(function(sv){var id=Number(sv.id||0),img=sv.image||'assets/img/service/service_1_1.jpg';html+='<article class="box" data-id="'+id+'"><img src="'+esc(img)+'" alt="Service"><div class="b"><h4>'+esc(sv.title||'Service')+'</h4><p class="meta">'+esc(sv.description||'')+'</p><div class="actions"><button class="btn-mini btn-edit" type="button" onclick="openServiceModal('+id+')">Edit</button><button class="btn-mini btn-del" type="button" onclick="deleteService('+id+')">Delete</button></div></div></article>';});
        grid.innerHTML=html;setCounts();
    }

    function renderProjects(){
        var grid=document.getElementById('projectGrid');if(!grid)return;
        if(!projects.length){grid.innerHTML='<p style="color:#7b8794">No projects found.</p>';setCounts();return;}
        var html='';projects.forEach(function(pr){var id=Number(pr.id||0),img=pr.image||'assets/img/project/project_1_1.jpg',meta=(pr.category||'Interior')+(pr.location?' | '+pr.location:'')+(pr.project_year?' | '+pr.project_year:'');html+='<article class="box" data-id="'+id+'"><img src="'+esc(img)+'" alt="Project"><div class="b"><h4>'+esc(pr.title||'Project')+'</h4><p class="meta">'+esc(meta)+'</p><p class="meta">'+esc(pr.description||'')+'</p><div class="actions"><button class="btn-mini btn-edit" type="button" onclick="openProjectModal('+id+')">Edit</button><button class="btn-mini btn-del" type="button" onclick="deleteProject('+id+')">Delete</button></div></div></article>';});
        grid.innerHTML=html;setCounts();
    }

    window.approveConsultation=function(id){if(!confirm('Approve this consultation request? An email will be sent to the customer.'))return;var btn=document.querySelector('.btn-approve[data-id="'+id+'"]');if(btn){btn.classList.add('processing');btn.textContent='Sending...';}var fd=new FormData();fd.append('consultation_id',id);fd.append('send_email','1');fetch('api/approve-consultation.php',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){if(!d.success)throw new Error(d.message||'Failed');var row=document.querySelector('tr[data-id="'+id+'"]');if(row){var cs=row.querySelector('.js-cs'),vs=row.querySelector('.js-v'),ap=row.querySelector('.btn-app'),dc=row.querySelector('.btn-dec');if(cs){cs.textContent='approved';cs.className='sb js-cs ok'}if(vs){vs.textContent='approved';vs.className='sb js-v ok'}if(ap){ap.disabled=true;ap.classList.remove('processing');ap.textContent='Approved';ap.style.opacity='0.6';}if(dc)dc.disabled=true;row.classList.add('success');}if(btn){btn.classList.remove('processing');btn.textContent='Approved';btn.disabled=true;}refreshOverview();updateMobileConsultView();toast('✓ Consultation approved & email sent!')}).catch(function(e){if(btn){btn.classList.remove('processing');btn.textContent='Approve';}toast('❌ '+e.message||'Action failed')})}
    
    window.declineConsultation=function(id){if(!confirm('Decline this consultation request? An email will be sent to the customer.'))return;var btn=document.querySelector('.btn-decline[data-id="'+id+'"]');if(btn){btn.classList.add('processing');btn.textContent='Sending...';}var fd=new FormData();fd.append('consultation_id',id);fd.append('send_email','1');fetch('api/decline-consultation.php',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){if(!d.success)throw new Error(d.message||'Failed');var row=document.querySelector('tr[data-id="'+id+'"]');if(row){var cs=row.querySelector('.js-cs'),vs=row.querySelector('.js-v'),ap=row.querySelector('.btn-app'),dc=row.querySelector('.btn-dec');if(cs){cs.textContent='declined';cs.className='sb js-cs bad'}if(vs){vs.textContent='declined';vs.className='sb js-v bad'}if(ap)ap.disabled=true;if(dc){dc.disabled=true;dc.classList.remove('processing');dc.textContent='Declined';dc.style.opacity='0.6';}row.classList.add('success');}if(btn){btn.classList.remove('processing');btn.textContent='Declined';btn.disabled=true;}refreshOverview();updateMobileConsultView();toast('✓ Consultation declined & email sent!')}).catch(function(e){if(btn){btn.classList.remove('processing');btn.textContent='Decline';}toast('❌ '+e.message||'Action failed')})}

    window.updateOrderStatus=function(orderId,status,successMsg){var fd=new FormData();fd.append('order_id',orderId);fd.append('status',status);fetch('api/update-order-status.php',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){if(!d.success)throw new Error(d.message||'Update failed');toast(successMsg);pollOrders()}).catch(function(e){toast(e.message||'Update failed')})}

    function renderOrders(orders){var body=document.getElementById('orderBody');if(!body)return;var html='';if(!orders||!orders.length){html='<tr><td colspan="5" style="text-align:center;color:#7b8794;padding:14px">No orders found.</td></tr>';}else{orders.forEach(function(od){var st=n(od.status),disableApp=st!=='pending'?'disabled':'',disableShip=['shipped','delivered','cancelled'].indexOf(st)!==-1?'disabled':'',disableDec=['cancelled','delivered'].indexOf(st)!==-1?'disabled':'';var c=cls(st);html+='<tr data-id="'+od.id+'"><td><span class="nm">#'+od.id+'</span><div class="ln">'+(od.created_at||'')+'</div></td><td><span class="nm">'+(od.customer_name||'')+'</span><div class="ln">'+(od.customer_email||'')+'</div><div class="ln">'+(od.phone||'')+'</div></td><td><span class="sb '+c+' js-os">'+st+'</span></td><td><strong>Rs '+Number(od.total||0).toFixed(2)+'</strong></td><td><div class="acts"><button class="btnx btn-app" onclick="updateOrderStatus('+od.id+',\'processing\',\'Order approved\')" '+disableApp+'>Approve</button><button class="btnx btn-ship" onclick="updateOrderStatus('+od.id+',\'shipped\',\'Order shipped\')" '+disableShip+'>Shipped</button><button class="btnx btn-dec" onclick="updateOrderStatus('+od.id+',\'cancelled\',\'Order declined\')" '+disableDec+'>Decline</button></div></td></tr>';});}
        body.innerHTML=html;
        var bOrder=document.getElementById('bOrder'), stOrder=document.getElementById('stOrder');
        if(bOrder)bOrder.textContent=orders.length; if(stOrder)stOrder.textContent=orders.length;
    }
    
    function updateMobileConsultView(){
        var tableRows=document.querySelectorAll('.consult-row');
        var container=document.getElementById('consultCardView');
        if(!container)return;
        var html='';
        if(tableRows.length===0){html='<div style="text-align:center;color:#7b8794;padding:20px">No consultation data.</div>';}else{
            tableRows.forEach(function(row){
                var id=row.getAttribute('data-id');
                var nameEl=row.querySelector('.nm'),emailEl=row.querySelectorAll('.ln')[0],phoneEl=row.querySelectorAll('.ln')[1];
                var consultEl=row.querySelectorAll('td')[1],statusVerEl=row.querySelectorAll('.sb')[0],statusEl=row.querySelectorAll('.sb')[1];
                var name=nameEl?nameEl.textContent:'Unknown';
                var email=emailEl?emailEl.textContent:'N/A';
                var phone=phoneEl?phoneEl.textContent:'N/A';
                var consultType=consultEl?consultEl.querySelector('strong').textContent:'N/A';
                var prefDate=consultEl?consultEl.querySelectorAll('.ln')[1].textContent:'N/A';
                var budget=consultEl?consultEl.querySelectorAll('.ln')[2].textContent:'N/A';
                var verifStatus=statusVerEl?statusVerEl.textContent:'pending';
                var overallStatus=statusEl?statusEl.textContent:'pending';
                var isPending=row.querySelector('.btn-approve')&&!row.querySelector('.btn-approve').disabled;
                var verifClass=statusVerEl?statusVerEl.className:'sb pend';
                var statusClass=statusEl?statusEl.className:'sb pend';
                html+='<div class="consult-card" data-id="'+id+'"><div class="consult-card-header"><div class="consult-card-name">'+esc(name)+'</div><div class="consult-card-status"><span class="sb '+verifClass.replace('js-v','').replace('js-cs','').trim()+'">'+esc(verifStatus)+'</span><span class="sb '+statusClass.replace('js-v','').replace('js-cs','').trim()+'">'+esc(overallStatus)+'</span></div></div><div class="consult-card-info"><div class="consult-card-row"><span class="consult-card-label">Type</span><span class="consult-card-value">'+esc(consultType)+'</span></div><div class="consult-card-row"><span class="consult-card-label">Email</span><span class="consult-card-value" title="'+esc(email)+'">'+esc(email)+'</span></div><div class="consult-card-row"><span class="consult-card-label">Phone</span><span class="consult-card-value">'+esc(phone)+'</span></div><div class="consult-card-row"><span class="consult-card-label">Date</span><span class="consult-card-value">'+esc(prefDate)+'</span></div><div class="consult-card-row"><span class="consult-card-label">Budget</span><span class="consult-card-value">'+esc(budget)+'</span></div></div><div class="consult-card-actions"><button class="consult-card-btn btn-app-card" onclick="approveConsultation('+id+')" '+(isPending?'':'disabled')+'>Approve</button><button class="consult-card-btn btn-dec-card" onclick="declineConsultation('+id+')" '+(isPending?'':'disabled')+'>Decline</button></div></div>';
            });
        }
        container.innerHTML=html;
    }

    function pollOrders(){fetch('staff-dashboard.php?ajax=orders').then(function(r){return r.json()}).then(function(d){if(d.success&&Array.isArray(d.orders)){renderOrders(d.orders);refreshOverview();}}).catch(function(){})}
    function pollServices(){fetch('staff-dashboard.php?ajax=services').then(function(r){return r.json()}).then(function(d){if(d.success&&Array.isArray(d.services)){services=d.services;renderServices();}}).catch(function(){})}
    function pollProjects(){fetch('staff-dashboard.php?ajax=projects').then(function(r){return r.json()}).then(function(d){if(d.success&&Array.isArray(d.projects)){projects=d.projects;renderProjects();}}).catch(function(){})}

    function refreshOverview(){
        var consultRows=[].slice.call(document.querySelectorAll('#consultBody tr[data-id]'));var pending=0;consultRows.forEach(function(r){var s=r.querySelector('.js-cs');if(s&&n(s.textContent)==='pending')pending++;});
        var orderRows=[].slice.call(document.querySelectorAll('#orderBody tr[data-id]'));
        var stConsult=document.getElementById('stConsult'), stOrder=document.getElementById('stOrder'), bConsult=document.getElementById('bConsult');
        if(stConsult)stConsult.textContent=consultRows.length; if(stOrder)stOrder.textContent=orderRows.length; if(bConsult)bConsult.textContent=pending;
        setCounts();
        updateMobileConsultView();
    }

    function resetServiceForm(){document.getElementById('serviceId').value='';document.getElementById('serviceName').value='';document.getElementById('serviceDesc').value='';document.getElementById('servicePrice').value='1';document.getElementById('serviceArea').value='0';document.getElementById('serviceDuration').value='N/A';document.getElementById('serviceImage').value='';var p=document.getElementById('servicePreview');p.style.display='none';p.src='';}
    function resetProjectForm(){document.getElementById('projectId').value='';document.getElementById('projectTitle').value='';document.getElementById('projectCategory').value='Interior';document.getElementById('projectLocation').value='';document.getElementById('projectYear').value='';document.getElementById('projectSortOrder').value='0';document.getElementById('projectDesc').value='';document.getElementById('projectImage').value='';var p=document.getElementById('projectPreview');p.style.display='none';p.src='';}
    function filePreview(input,previewId){var file=input.files&&input.files[0],pv=document.getElementById(previewId);if(!pv)return;if(!file){pv.style.display='none';pv.src='';return;}var r=new FileReader();r.onload=function(){pv.src=r.result;pv.style.display='block'};r.readAsDataURL(file)}
    document.getElementById('serviceImage').addEventListener('change',function(){filePreview(this,'servicePreview')});
    document.getElementById('projectImage').addEventListener('change',function(){filePreview(this,'projectPreview')});

    window.openServiceModal=function(id){
        resetServiceForm();
        var t=document.getElementById('serviceModalTitle');
        if(id){var item=services.find(function(x){return Number(x.id)===Number(id)});if(!item)return;document.getElementById('serviceId').value=String(item.id||'');document.getElementById('serviceName').value=item.title||'';document.getElementById('serviceDesc').value=item.description||'';document.getElementById('servicePrice').value=String(item.price||1);document.getElementById('serviceArea').value=String(item.area_sqft||0);document.getElementById('serviceDuration').value=item.duration||'N/A';if(item.image){var p=document.getElementById('servicePreview');p.src=item.image;p.style.display='block';}t.textContent='Edit Service';}else{t.textContent='Add Service';}
        document.getElementById('serviceModal').classList.add('show');
    }
    window.closeServiceModal=function(){document.getElementById('serviceModal').classList.remove('show')}

    window.openProjectModal=function(id){
        resetProjectForm();
        var t=document.getElementById('projectModalTitle');
        if(id){var item=projects.find(function(x){return Number(x.id)===Number(id)});if(!item)return;document.getElementById('projectId').value=String(item.id||'');document.getElementById('projectTitle').value=item.title||'';document.getElementById('projectCategory').value=item.category||'Interior';document.getElementById('projectLocation').value=item.location||'';document.getElementById('projectYear').value=item.project_year||'';document.getElementById('projectSortOrder').value=String(item.sort_order||0);document.getElementById('projectDesc').value=item.description||'';if(item.image){var p=document.getElementById('projectPreview');p.src=item.image;p.style.display='block';}t.textContent='Edit Project';}else{t.textContent='Add Project';}
        document.getElementById('projectModal').classList.add('show');
    }
    window.closeProjectModal=function(){document.getElementById('projectModal').classList.remove('show')}

    function uploadServiceImage(file,title){var fd=new FormData();fd.append('image',file);fd.append('title',title||'service');return fetch('api/upload-service-image.php',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){if(!d.success)throw new Error(d.message||'Image upload failed');return d.image_path})}

    window.saveService=function(){
        var id=Number(document.getElementById('serviceId').value||0);
        var title=document.getElementById('serviceName').value.trim();
        var description=document.getElementById('serviceDesc').value.trim();
        var basePrice=document.getElementById('servicePrice').value.trim()||'1';
        var area=document.getElementById('serviceArea').value.trim()||'0';
        var duration=document.getElementById('serviceDuration').value.trim()||'N/A';
        var file=document.getElementById('serviceImage').files[0];
        var preview=document.getElementById('servicePreview').getAttribute('src')||'';
        if(!title||!description){toast('Please fill required fields');return;}

        function sendService(imagePath){
            var fd=new FormData();
            if(id){fd.append('action','update_service');fd.append('service_id',String(id));fd.append('title',title);fd.append('description',description);fd.append('link','#');fd.append('area',area);fd.append('basePrice',basePrice);fd.append('duration',duration);fd.append('status','ACTIVE');if(imagePath){fd.append('image',imagePath);}}
            else{fd.append('action','add_service');fd.append('title',title);fd.append('description',description);fd.append('area',area);fd.append('basePrice',basePrice);fd.append('duration',duration);fd.append('status','ACTIVE');if(file)fd.append('image',file);}
            return fetch('api/save-service.php',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){if(!d.success)throw new Error(d.message||'Save failed');closeServiceModal();toast(id?'Service updated':'Service added');pollServices();});
        }

        if(id&&file){uploadServiceImage(file,title).then(function(path){return sendService(path)}).catch(function(e){toast(e.message||'Save failed')});}
        else if(!id&&!file){toast('Please select service image');}
        else{sendService(id?preview:'').catch(function(e){toast(e.message||'Save failed')});}
    }

    window.deleteService=function(id){
        if(!confirm('Delete this service?'))return;
        var fd=new FormData();fd.append('action','delete_service');fd.append('service_id',String(id));
        fetch('api/save-service.php',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){if(!d.success)throw new Error(d.message||'Delete failed');toast('Service deleted');pollServices();}).catch(function(e){toast(e.message||'Delete failed')});
    }

    window.saveProject=function(){
        var id=Number(document.getElementById('projectId').value||0);
        var title=document.getElementById('projectTitle').value.trim();
        var category=document.getElementById('projectCategory').value.trim()||'Interior';
        var location=document.getElementById('projectLocation').value.trim();
        var year=document.getElementById('projectYear').value.trim();
        var sortOrder=document.getElementById('projectSortOrder').value.trim()||'0';
        var description=document.getElementById('projectDesc').value.trim();
        var image=document.getElementById('projectImage').files[0];
        if(!title){toast('Project title is required');return;}
        if(!id&&!image){toast('Please select project image');return;}
        var fd=new FormData();
        fd.append('action',id?'update':'add');
        if(id)fd.append('project_id',String(id));
        fd.append('title',title);fd.append('category',category);fd.append('location',location);fd.append('project_year',year);fd.append('sort_order',sortOrder);fd.append('description',description);fd.append('is_active','1');
        if(image)fd.append('image',image);
        fetch('api/manage-project.php',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){if(!d.success)throw new Error(d.message||'Save failed');closeProjectModal();toast(id?'Project updated':'Project added');pollProjects();}).catch(function(e){toast(e.message||'Save failed')});
    }

    window.deleteProject=function(id){
        if(!confirm('Delete this project?'))return;
        var fd=new FormData();fd.append('action','delete');fd.append('project_id',String(id));
        fetch('api/manage-project.php',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){if(!d.success)throw new Error(d.message||'Delete failed');toast('Project deleted');pollProjects();}).catch(function(e){toast(e.message||'Delete failed')});
    }

    window.saveProfileAccount=function(){
        var name=(document.getElementById('pfName').value||'').trim();
        var email=(document.getElementById('pfEmail').value||'').trim();
        var phone=(document.getElementById('pfPhone').value||'').trim();
        if(!name||!email){toast('Name and email are required');return;}
        var fd=new FormData();
        fd.append('name',name);fd.append('email',email);fd.append('phone',phone);
        fetch('staff-dashboard.php?ajax=profile_update',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){if(!d.success)throw new Error(d.message||'Update failed');currentUser=d.user||{name:name,email:email,phone:phone};syncHeaderUser(currentUser);toast('Profile updated');}).catch(function(e){toast(e.message||'Update failed')});
    }

    window.saveProfilePassword=function(){
        var currentPassword=(document.getElementById('pfCurrent').value||'').trim();
        var newPassword=(document.getElementById('pfNew').value||'').trim();
        var confirmPassword=(document.getElementById('pfConfirm').value||'').trim();
        if(!currentPassword||!newPassword||!confirmPassword){toast('Fill all password fields');return;}
        var fd=new FormData();
        fd.append('name',(document.getElementById('pfName').value||'').trim());
        fd.append('email',(document.getElementById('pfEmail').value||'').trim());
        fd.append('phone',(document.getElementById('pfPhone').value||'').trim());
        fd.append('current_password',currentPassword);
        fd.append('new_password',newPassword);
        fd.append('confirm_password',confirmPassword);
        fetch('staff-dashboard.php?ajax=profile_update',{method:'POST',body:fd}).then(function(r){return r.json()}).then(function(d){if(!d.success)throw new Error(d.message||'Password update failed');document.getElementById('pfCurrent').value='';document.getElementById('pfNew').value='';document.getElementById('pfConfirm').value='';toast('Password updated');}).catch(function(e){toast(e.message||'Password update failed')});
    }

    syncHeaderUser(currentUser);
    renderServices();
    renderProjects();
    refreshOverview();
    updateMobileConsultView();
    setInterval(pollOrders,10000);
    setInterval(pollServices,12000);
    setInterval(pollProjects,12000);
})();
</script>
</body>
</html>
