<?php
declare(strict_types=1);

$dbHost = getenv('DB_HOST') ?: 'localhost';
$dbUser = getenv('DB_USER') ?: 'root';
$dbPass = getenv('DB_PASSWORD') ?: '';
$dbName = 'listbnb';

try {
    $pdo = new PDO("mysql:host={$dbHost};dbname={$dbName};charset=utf8mb4", $dbUser, $dbPass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Database connection failed.');window.location.href='index.html';</script></body></html>";
    exit;
}

try {
    $pdo->exec('CREATE TABLE IF NOT EXISTS products (
        id INT AUTO_INCREMENT PRIMARY KEY,
        product_title VARCHAR(255) NOT NULL,
        product_size ENUM("XS","Small","Medium","Large","XL") NOT NULL,
        price DECIMAL(10,2) NOT NULL,
        `condition` ENUM("New","Used") NOT NULL,
        category VARCHAR(50) NOT NULL,
        product_type VARCHAR(100) NOT NULL,
        brand VARCHAR(100),
        description TEXT NOT NULL,
        image1 VARCHAR(255),
        image2 VARCHAR(255),
        image3 VARCHAR(255),
        image4 VARCHAR(255),
        image5 VARCHAR(255),
        status ENUM("Pending","Active","Inactive") NOT NULL DEFAULT "Pending",
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN status ENUM("Pending","Active","Inactive") NOT NULL DEFAULT "Pending"'); } catch (Throwable $e) {}

$hasStatus = false;
try { $hasStatus = (bool)$pdo->query("SHOW COLUMNS FROM products LIKE 'status'")->fetch(); } catch (Throwable $e) { $hasStatus = false; }

try {
    $pdo->exec('CREATE TABLE IF NOT EXISTS users (
        id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(100) NOT NULL,
        email VARCHAR(255) NOT NULL UNIQUE,
        password_hash VARCHAR(255) NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE users ADD COLUMN role ENUM("Seller","Buyer","Admin") NOT NULL DEFAULT "Buyer"'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE users ADD COLUMN status ENUM("Pending","Active","Inactive") NOT NULL DEFAULT "Active"'); } catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE users MODIFY COLUMN role ENUM("Seller","Buyer","Admin") NOT NULL DEFAULT "Buyer"'); } catch (Throwable $e) {}

try {
    $pdo->exec('CREATE TABLE IF NOT EXISTS orders (
        id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        status ENUM("placed","pending","cancelled") NOT NULL,
        total DECIMAL(10,2) DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}

try {
    $pdo->exec('CREATE TABLE IF NOT EXISTS contacts (
        id INT AUTO_INCREMENT PRIMARY KEY,
        full_name VARCHAR(255) NOT NULL,
        email VARCHAR(255) NOT NULL,
        message TEXT NOT NULL,
        user_id INT NULL,
        is_read TINYINT(1) NOT NULL DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}
try { $pdo->exec('ALTER TABLE contacts ADD COLUMN is_read TINYINT(1) NOT NULL DEFAULT 0'); } catch (Throwable $e) {}

try {
    $pdo->exec('CREATE TABLE IF NOT EXISTS announcements (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(255),
        body TEXT NOT NULL,
        created_by INT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}
// Home images table for hero slider
try {
    $pdo->exec('CREATE TABLE IF NOT EXISTS home_images (
        id INT AUTO_INCREMENT PRIMARY KEY,
        image_path VARCHAR(255) NOT NULL,
        sort_order TINYINT UNSIGNED NOT NULL DEFAULT 1,
        active TINYINT(1) NOT NULL DEFAULT 1,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}

$totalProducts = 0;
$totalOrders = 0;
$cancelledOrders = 0;
$pendingOrders = 0;
$totalUsers = 0;
$pendingProductsCount = 0;
$activeProducts = 0;
$inactiveProducts = 0;
$approvedOrders = 0;
$blockedUsers = 0;
$unreadMessages = 0;

try { $totalProducts = (int)$pdo->query('SELECT COUNT(*) c FROM products')->fetchColumn(); } catch (Throwable $e) {}
if ($hasStatus) {
    try { $pendingProductsCount = (int)$pdo->query("SELECT COUNT(*) c FROM products WHERE status='Pending'")->fetchColumn(); } catch (Throwable $e) {}
}
try { $totalOrders = (int)$pdo->query('SELECT COUNT(*) c FROM order_requests')->fetchColumn(); } catch (Throwable $e) {}
try { $cancelledOrders = (int)$pdo->query("SELECT COUNT(*) c FROM order_requests WHERE status='rejected'")->fetchColumn(); } catch (Throwable $e) {}
try { $pendingOrders = (int)$pdo->query("SELECT COUNT(*) c FROM order_requests WHERE status='pending'")->fetchColumn(); } catch (Throwable $e) {}
try { $approvedOrders = (int)$pdo->query("SELECT COUNT(*) c FROM order_requests WHERE status='approved'")->fetchColumn(); } catch (Throwable $e) {}
try { $totalUsers = (int)$pdo->query('SELECT COUNT(*) c FROM users')->fetchColumn(); } catch (Throwable $e) {}
try { $blockedUsers = (int)$pdo->query("SELECT COUNT(*) c FROM users WHERE status='Inactive'")->fetchColumn(); } catch (Throwable $e) {}
try { $activeProducts = (int)$pdo->query("SELECT COUNT(*) c FROM products WHERE status='Active'")->fetchColumn(); } catch (Throwable $e) {}
try { $inactiveProducts = (int)$pdo->query("SELECT COUNT(*) c FROM products WHERE status='Inactive'")->fetchColumn(); } catch (Throwable $e) {}
try { $unreadMessages = (int)$pdo->query('SELECT COUNT(*) c FROM contacts WHERE is_read=0')->fetchColumn(); } catch (Throwable $e) {}
// Chat unread count
try {
    $pdo->exec('CREATE TABLE IF NOT EXISTS chat_messages (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT UNSIGNED NOT NULL,
        sender ENUM("user","admin") NOT NULL,
        content TEXT NOT NULL,
        is_read TINYINT(1) NOT NULL DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}
$unreadChats = 0;
try { $unreadChats = (int)$pdo->query("SELECT COUNT(*) c FROM chat_messages WHERE sender='user' AND is_read=0")->fetchColumn(); } catch (Throwable $e) {}

$rawName = trim($_GET['user'] ?? 'Admin');
$first = $rawName !== '' ? preg_split('/\s+|[_-]/', $rawName)[0] : 'Guest';
$displayName = ucfirst(strtolower($first));
if (isset($_GET['action'])) {
    $action = (string)$_GET['action'];
    header('Content-Type: application/json');
    if ($action === 'unread_count') {
        echo json_encode(['count' => $unreadMessages]);
        exit;
    }
    if ($action === 'mark_all_read') {
        try { $pdo->exec('UPDATE contacts SET is_read=1'); } catch (Throwable $e) {}
        echo json_encode(['ok' => true]);
        exit;
    }
    if ($action === 'list_messages') {
        try {
            $rows = $pdo->query('SELECT id,full_name,email,message,is_read,created_at FROM contacts ORDER BY created_at DESC LIMIT 50')->fetchAll();
        } catch (Throwable $e) { $rows = []; }
        echo json_encode(['items' => $rows]);
        exit;
    }
    if ($action === 'announcement_create') {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['ok'=>false]); exit; }
        $title = trim((string)($_POST['title'] ?? ''));
        $body = trim((string)($_POST['body'] ?? ''));
        if ($body === '') { echo json_encode(['ok'=>false,'error'=>'Body required']); exit; }
        try {
            $st = $pdo->prepare('INSERT INTO announcements(title,body,created_by) VALUES(:t,:b,:u)');
            $st->execute([':t' => ($title !== '' ? $title : null), ':b' => $body, ':u' => null]);
            echo json_encode(['ok' => true]);
        } catch (Throwable $e) {
            echo json_encode(['ok' => false]);
        }
        exit;
    }
}
?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Admin Dashboard - ListBnb</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" type="image/x-icon" href="assets/img/logo/favicon.png">
    <link rel="stylesheet" href="assets/css/bootstrap.css">
    <link rel="stylesheet" href="assets/css/animate.css">
    <link rel="stylesheet" href="assets/css/swiper-bundle.css">
    <link rel="stylesheet" href="assets/css/slick.css">
    <link rel="stylesheet" href="assets/css/magnific-popup.css">
    <link rel="stylesheet" href="assets/css/font-awesome-pro.css">
    <link rel="stylesheet" href="assets/css/spacing.css">
    <link rel="stylesheet" href="assets/css/custom-animation.css">
    <link rel="stylesheet" href="assets/css/main.css">
    <style>
      :root {
        --primary: #4f46e5;
        --primary-light: #eef2ff;
        --success: #10b981;
        --warning: #f59e0b;
        --danger: #ef4444;
        --dark: #1f2937;
        --light: #f9fafb;
        --border: #e5e7eb;
        --text: #374151;
        --text-light: #6b7280;
        --radius: 12px;
        --shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
        --transition: all 0.2s ease-in-out;
      }

      body {
        color: var(--text);
        background-color: #f3f4f6;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        line-height: 1.5;
      }

      /* Layout */
      .admin-layout {
        display: flex;
        gap: 24px;
        margin-top: 20px;
      }

      /* Sidebar */
      .admin-sidebar {
        width: 280px;
        background: #fff;
        border-radius: var(--radius);
        padding: 20px;
        box-shadow: var(--shadow);
        height: fit-content;
        position: sticky;
        top: 100px;
      }

      .admin-sidebar .menu-title {
        font-size: 13px;
        color: var(--text-light);
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin: 24px 0 12px;
        padding-left: 8px;
        font-weight: 600;
      }

      .admin-sidebar ul {
        list-style: none;
        padding: 0;
        margin: 0;
      }

      .admin-sidebar li a {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 10px 12px;
        color: var(--text);
        text-decoration: none;
        border-radius: 8px;
        transition: var(--transition);
        font-weight: 500;
      }

      .admin-sidebar li a:hover,
      .admin-sidebar li a.active {
        background: var(--primary-light);
        color: var(--primary);
      }

      .admin-sidebar li a i {
        width: 20px;
        text-align: center;
        font-size: 1.1em;
      }

      .admin-profile {
        margin-top: 24px;
        padding: 16px;
        background: var(--light);
        border-radius: 10px;
        border: 1px solid var(--border);
      }

      .admin-avatar {
        width: 40px;
        height: 40px;
        border-radius: 10px;
        background: var(--primary);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        font-size: 18px;
        text-transform: uppercase;
      }

      /* Main Content */
      .admin-main {
        flex: 1;
        min-width: 0;
      }

      /* Cards */
      .cards {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
        gap: 20px;
        margin-bottom: 24px;
      }

      .card {
        background: #fff;
        border-radius: var(--radius);
        padding: 24px;
        box-shadow: var(--shadow);
        transition: var(--transition);
        border: 1px solid var(--border);
      }

      .card:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
      }

      .card h6 {
        font-size: 14px;
        color: var(--text-light);
        margin: 0 0 8px;
        font-weight: 500;
      }

      .card .value {
        font-size: 28px;
        font-weight: 700;
        color: var(--dark);
        margin: 0;
        line-height: 1.2;
      }

      /* Sections */
      .section {
        background: #fff;
        border-radius: var(--radius);
        padding: 24px;
        box-shadow: var(--shadow);
        margin-bottom: 24px;
        border: 1px solid var(--border);
      }

      .section h4 {
        margin-top: 0;
        margin-bottom: 20px;
        color: var(--dark);
        font-size: 18px;
        font-weight: 600;
      }

      /* Tables */
      .latest-table {
        width: 100%;
        overflow-x: auto;
      }

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

      .latest-table th,
      .latest-table td {
        padding: 12px 16px;
        text-align: left;
        border-bottom: 1px solid var(--border);
      }

      .latest-table th {
        font-size: 13px;
        font-weight: 600;
        color: var(--text-light);
        text-transform: uppercase;
        letter-spacing: 0.05em;
        background: var(--light);
      }

      .latest-table tr:last-child td {
        border-bottom: none;
      }

      .latest-table tr:hover td {
        background: var(--primary-light);
      }

      /* Status Badges */
      .status-badge {
        display: inline-block;
        padding: 4px 10px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
        text-transform: capitalize;
      }

      .status-pending { background: #fef3c7; color: #92400e; }
      .status-active { background: #d1fae5; color: #065f46; }
      .status-cancelled { background: #fee2e2; color: #991b1b; }

      /* Messages Drawer */
      #messages-drawer {
        position: fixed;
        right: -420px;
        top: 0;
        width: 400px;
        height: 100%;
        background: #fff;
        border-left: 1px solid var(--border);
        box-shadow: -4px 0 15px rgba(0, 0, 0, 0.05);
        transition: right 0.3s ease;
        z-index: 1000;
        display: flex;
        flex-direction: column;
      }

      #messages-drawer.open {
        right: 0;
      }

      .drawer-head {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 16px 20px;
        border-bottom: 1px solid var(--border);
        background: #fff;
      }

      .drawer-title {
        font-weight: 600;
        font-size: 16px;
        color: var(--dark);
        margin: 0;
      }

      .drawer-close {
        background: transparent;
        border: none;
        font-size: 20px;
        cursor: pointer;
        color: var(--text-light);
        padding: 4px;
        line-height: 1;
        transition: var(--transition);
      }

      .drawer-close:hover {
        color: var(--dark);
      }

      .drawer-action {
        background: var(--primary);
        color: white;
        border: none;
        border-radius: 6px;
        padding: 6px 12px;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        transition: var(--transition);
      }

      .drawer-action:hover {
        background: #4338ca;
      }

      .messages-list {
        padding: 16px;
        overflow-y: auto;
        flex: 1;
      }

      .message-item {
        border: 1px solid var(--border);
        border-radius: 8px;
        padding: 16px;
        margin-bottom: 12px;
        transition: var(--transition);
      }

      .message-item:hover {
        border-color: var(--primary);
      }

      .message-meta {
        font-size: 12px;
        color: var(--text-light);
        margin-top: 6px;
      }

      .announcement-form {
        padding: 16px;
        border-top: 1px solid var(--border);
      }

      .announcement-form .row {
        display: flex;
        flex-direction: column;
        gap: 12px;
      }

      .announcement-form input,
      .announcement-form textarea {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid var(--border);
        border-radius: 6px;
        font-size: 14px;
        transition: var(--transition);
      }

      .announcement-form input:focus,
      .announcement-form textarea:focus {
        outline: none;
        border-color: var(--primary);
        box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
      }

      .announcement-actions {
        display: flex;
        gap: 10px;
        margin-top: 12px;
        justify-content: flex-end;
      }

      /* Responsive */
      @media (max-width: 1199px) {
        .cards {
          grid-template-columns: repeat(2, minmax(200px, 1fr));
        }
        .admin-sidebar {
          width: 240px;
        }
      }

      @media (max-width: 991px) {
        .admin-layout {
          flex-direction: column;
        }
        .admin-sidebar {
          width: 100%;
          position: static;
          margin-bottom: 20px;
        }
      }

      @media (max-width: 767px) {
        .cards {
          grid-template-columns: 1fr;
        }
        
        #messages-drawer {
          width: 100%;
          max-width: 100%;
        }
        
        .section, .card {
          padding: 16px;
        }
      }
      .tp-header-menu .only-label{display:flex;justify-content:flex-start}
      .tp-header-menu .nav-label{font-weight:600;color:var(--text)}
      .header-left{display:flex;align-items:center;gap:12px}
      .admin-headline{font-weight:800;font-size:24px;color:var(--dark)}
      .tp-profile-area{padding-top:8px !important;padding-bottom:48px !important}
      .tp-header-area.tp-header-inner-style{margin-bottom:0}
      .admin-layout{margin-top:8px}
    </style>
    </head>
<body>
   <header class="tp-header-height">
      <div id="header-sticky" class="tp-header-area tp-header-inner-style">
         <div class="container">
            <div class="row align-items-center">
               <div class="col-xl-3 col-lg-6 col-md-6 col-6">
                  <div class="header-left">
                     <div class="admin-headline">Admin Dashboard</div>
                  </div>
               </div>
               <div class="col-xl-6 col-lg-4 d-none d-xl-block">
                  <div class="tp-header-menu">
                     <nav class="tp-main-menu-content">
                        <ul></ul>
                     </nav>
                  </div>
               </div>
               <div class="col-xl-3 col-lg-6 col-md-6 col-6">
                  <div class="tp-header-right d-flex align-items-center justify-content-end" style="gap:14px">
                     <a href="admin-chat.php" class="tp-btn-border d-none d-sm-inline-flex" style="align-items:center;gap:8px"><i class="fa-regular fa-message"></i> Chat <span style="margin-left:6px;min-width:22px;height:22px;display:inline-flex;align-items:center;justify-content:center;background:#ff4757;color:#fff;border-radius:999px;font-size:12px;line-height:1;padding:0 6px"><?php echo number_format($unreadChats); ?></span></a>
                     <div class="tp-header-sign-box d-none d-sm-block">
                        <a href="logout.php"><i class="fa-solid fa-right-from-bracket"></i>Logout</a>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </header>

   <main>
      <div class="tp-profile-area z-index pb-120 pt-60">
         <div class="container">
            <div class="admin-layout">
              <aside class="admin-sidebar">
                <div class="menu-title">Menu</div>
                <ul>
                  <li><a href="admin-dashboard.php"><i class="fa-regular fa-grid-2"></i> Dashboard</a></li>
                </ul>
                <div class="menu-title">Product & Order</div>
                <ul>
                  <li><a href="admin-products.php"><i class="fa-regular fa-box"></i> Manage Products</a></li>
                  <li><a href="admin-order-requests.php"><i class="fa-regular fa-cart-shopping"></i> Manage Order Requests</a></li>
                </ul>
                <div class="menu-title">Site Content</div>
                <ul>
                  <li><a href="admin-home-images.php"><i class="fa-regular fa-image"></i> Home Image</a></li>
                </ul>
                <div class="menu-title">Accounts & Roles</div>
                <ul>
                  <li><a href="admin-users.php?role=Buyer"><i class="fa-regular fa-users"></i> Customers</a></li>
                  <li><a href="admin-users.php?role=Seller"><i class="fa-regular fa-user-tie"></i> Sellers</a></li>
                  <li><a href="#"><i class="fa-regular fa-chart-pie-simple"></i> Reports</a></li>
                </ul>
                <div class="menu-title">Messages</div>
                <ul>
                  <li><a href="#" id="messages-toggle"><i class="fa-regular fa-envelope"></i> User Messages <span id="menu-unread" class="menu-badge"><?php echo number_format($unreadMessages); ?></span></a></li>
                </ul>
              </aside>
              <section class="admin-main">
                <div class="section mb-20">
                  <h4 class="tp-form-title mb-5">Dashboard</h4>
                  <p class="mb-0">Welcome Back, <?php echo htmlspecialchars($displayName, ENT_QUOTES); ?></p>
                </div>
                <div class="cards">
                  <div class="card">
                    <h6><i class="fa-regular fa-box me-2"></i>Total Products</h6>
                    <div class="value"><?php echo number_format($totalProducts); ?></div>
                    <div class="trend"><i class="fa-solid fa-arrow-trend-up text-success me-1"></i><span class="text-muted">12% from last month</span></div>
                  </div>

                  <div class="card">
                    <h6><i class="fa-regular fa-check me-2"></i>Active Products</h6>
                    <div class="value"><?php echo number_format($activeProducts); ?></div>
                    <div class="trend"><i class="fa-regular fa-bell text-warning me-1"></i><span class="text-muted">Needs attention</span></div>
                  </div>

                  <div class="card">
                    <h6><i class="fa-regular fa-pause me-2"></i>Inactive Products</h6>
                    <div class="value"><?php echo number_format($inactiveProducts); ?></div>
                    <div class="trend"><i class="fa-solid fa-arrow-trend-down text-danger me-1"></i><span class="text-muted">Review required</span></div>
                  </div>

                  <div class="card">
                    <h6><i class="fa-regular fa-cart-shopping me-2"></i>Total Orders</h6>
                    <div class="value"><?php echo number_format($totalOrders); ?></div>
                    <div class="trend"><i class="fa-solid fa-arrow-trend-up text-success me-1"></i><span class="text-muted">5% from last month</span></div>
                  </div>

                  <div class="card">
                    <h6><i class="fa-regular fa-xmark-circle me-2"></i>Cancelled Orders</h6>
                    <div class="value"><?php echo number_format($cancelledOrders); ?></div>
                    <div class="trend"><i class="fa-solid fa-arrow-trend-down text-danger me-1"></i><span class="text-muted">2% from last month</span></div>
                  </div>

                  <div class="card">
                    <h6><i class="fa-regular fa-clock me-2"></i>Pending Orders</h6>
                    <div class="value"><?php echo number_format($pendingOrders); ?></div>
                    <div class="trend"><i class="fa-solid fa-arrow-trend-up text-success me-1"></i><span class="text-muted">8% from last week</span></div>
                  </div>

                  <div class="card">
                    <h6><i class="fa-regular fa-badge-check me-2"></i>Approved Orders</h6>
                    <div class="value"><?php echo number_format($approvedOrders); ?></div>
                    <div class="trend"><i class="fa-solid fa-arrow-trend-up text-success me-1"></i><span class="text-muted">Stable</span></div>
                  </div>

                  <div class="card">
                    <h6><i class="fa-regular fa-users me-2"></i>Total Users</h6>
                    <div class="value"><?php echo number_format($totalUsers); ?></div>
                    <div class="trend"><i class="fa-solid fa-arrow-trend-up text-success me-1"></i><span class="text-muted">15% from last month</span></div>
                  </div>

                  <div class="card">
                    <h6><i class="fa-regular fa-user-lock me-2"></i>Blocked Users</h6>
                    <div class="value"><?php echo number_format($blockedUsers); ?></div>
                    <div class="trend"><i class="fa-solid fa-arrow-trend-down text-danger me-1"></i><span class="text-muted">Monitor</span></div>
                  </div>
                </div>
                <div class="section">
                  <div class="d-flex justify-content-between align-items-center mb-4">
                    <h4 class="m-0">Recent Orders</h4>
                    <a href="#" class="text-primary text-decoration-none small fw-medium">View All <i class="fa-solid fa-arrow-right ms-1"></i></a>
                  </div>
                  <div class="latest-table">
                    <table class="table">
                      <thead>
                        <tr>
                          <th>Order ID</th>
                          <th>Price</th>
                          <th>Status</th>
                          <th>Created</th>
                          <th class="text-end">Action</th>
                        </tr>
                      </thead>
                      <tbody>
                        <?php
                        try {
                          $rows = $pdo->query("SELECT id, grand_total AS total, status, created_at FROM order_requests WHERE status='pending' ORDER BY created_at DESC LIMIT 5")->fetchAll();
                        } catch (Throwable $e) { $rows = []; }
                        if (!$rows) {
                          echo '<tr><td colspan="5" class="text-center py-4 text-muted">No orders found</td></tr>';
                        } else {
                          foreach ($rows as $r) {
                            $statusClass = '';
                            if ($r['status'] === 'rejected') {
                              $statusClass = 'status-cancelled';
                            } elseif ($r['status'] === 'pending') {
                              $statusClass = 'status-pending';
                            } else {
                              $statusClass = 'status-active';
                            }
                            echo '<tr>';
                            echo '<td class="fw-medium">#' . str_pad($r['id'], 5, '0', STR_PAD_LEFT) . '</td>';
                            echo '<td>Rs ' . number_format((float)$r['total'], 2) . '</td>';
                            echo '<td><span class="status-badge ' . $statusClass . '">' . htmlspecialchars($r['status'], ENT_QUOTES) . '</span></td>';
                            echo '<td class="text-nowrap">' . date('M d, Y', strtotime($r['created_at'])) . '</td>';
                            echo '<td class="text-end"><a href="order_request.php?id=' . (int)$r['id'] . '" class="btn btn-sm btn-outline-primary">View</a></td>';
                            echo '</tr>';
                          }
                        }
                        ?>
                      </tbody>
                    </table>
                  </div>
                </div>
              </section>
              <div id="messages-drawer">
                <div class="drawer-head">
                  <div class="drawer-title">User Messages</div>
                  <button class="drawer-action" id="announcement-open">Add Announcement</button>
                  <button class="drawer-close" id="messages-close" aria-label="Close">×</button>
                </div>
                <div class="messages-list" id="messages-list"></div>
                <div class="announcement-form" id="announcement-form">
                  <div class="row">
                    <input type="text" id="ann-title" placeholder="Title (optional)">
                    <textarea id="ann-body" placeholder="Announcement..." required></textarea>
                  </div>
                  <div class="announcement-actions">
                    <button class="drawer-action" id="ann-submit">Submit</button>
                    <button class="drawer-close" id="ann-cancel">Cancel</button>
                  </div>
                </div>
              </div>
            </div>
         </div>
      </div>
   </main>

   <footer>
      <div class="tp-copyright-area black-bg">
         <div class="container">
            <div class="tp-copyright-ptb">
               <div class="row align-items-center">
                  <div class="col-xl-7 col-lg-6 col-md-6 col-sm-7">
                     <div class="tp-copyright-left d-flex align-items-center justify-content-center justify-content-md-start">
                        <div class="tp-copyright-text text-center text-md-start">
                           <p>ReWear Admin</p>
                        </div>
                     </div>
                  </div>
                  <div class="col-xl-5 col-lg-6 col-md-6 col-sm-5">
                     <div class="tp-copyright-right justify-content-center d-flex justify-content-sm-end align-items-center">
                        <div class="tp-copyright-social">
                           <a href="#"><i class="fa-brands fa-facebook-f"></i></a>
                           <a href="#"><i class="fa-brands fa-twitter"></i></a>
                        </div>
                     </div>
                  </div>
               </div>
            </div>
         </div>
      </div>
   </footer>

   <script src="assets/js/vendor/jquery.js"></script>
   <script src="assets/js/bootstrap-bundle.js"></script>
   <script src="assets/js/slick.js"></script>
   <script src="assets/js/main.js"></script>
   <script>
     (function(){
       var toggle=document.getElementById('messages-toggle');
       var drawer=document.getElementById('messages-drawer');
       var closeBtn=document.getElementById('messages-close');
       var list=document.getElementById('messages-list');
       var badge=document.getElementById('menu-unread');
       var annOpen=document.getElementById('announcement-open');
        var annForm=document.getElementById('announcement-form');
        var annSubmit=document.getElementById('ann-submit');
        var annCancel=document.getElementById('ann-cancel');
        var annTitle=document.getElementById('ann-title');
        var annBody=document.getElementById('ann-body');
       function fetchUnread(){
         fetch('admin-dashboard.php?action=unread_count').then(function(r){return r.json()}).then(function(d){
           var c=(d&&typeof d.count!=='undefined')?d.count:0;
           badge.textContent=String(c);
           badge.style.display=c>0?'inline-flex':'none';
         }).catch(function(){});
       }
       function loadMessages(){
         fetch('admin-dashboard.php?action=list_messages').then(function(r){return r.json()}).then(function(d){
           var items=(d&&d.items)?d.items:[];
           if(!items.length){ list.innerHTML='<div class="text-muted">No messages found</div>'; return; }
           var html='';
           for(var i=0;i<items.length;i++){
             var it=items[i];
             html+= '<div class="message-item">'
                + '<div><strong>'+escapeHtml(it.full_name||'')+'</strong> &lt;'+escapeHtml(it.email||'')+'&gt;</div>'
                + '<div>'+escapeHtml(it.message||'')+'</div>'
                + '<div class="message-meta">'+escapeHtml(it.created_at||'')+'</div>'
                + '</div>';
           }
           list.innerHTML=html;
         }).catch(function(){ list.innerHTML=''; });
       }
       function openDrawer(){
         drawer.classList.add('open');
         loadMessages();
         fetch('admin-dashboard.php?action=mark_all_read').then(function(){
           badge.textContent='0';
           badge.style.display='none';
         }).catch(function(){});
       }
       function closeDrawer(){ drawer.classList.remove('open'); }
       function escapeHtml(s){
         return String(s).replace(/[&<>"]+/g,function(c){return ({'&':'&amp;','<':'&lt;','>':'&gt;','\"':'&quot;'})[c]});
       }
       if(toggle){ toggle.addEventListener('click',function(e){ e.preventDefault(); openDrawer(); }); }
       if(closeBtn){ closeBtn.addEventListener('click',function(){ closeDrawer(); }); }
       function showAnnouncementForm(){
         drawer.classList.add('open');
         annForm.style.display='block';
         try { annForm.scrollIntoView({behavior:'smooth', block:'start'}); } catch(e){}
         if(annBody && typeof annBody.focus==='function'){ annBody.focus(); }
         try { location.hash = 'announcement-form'; } catch(e){}
       }
       if(annOpen){ annOpen.addEventListener('click', function(e){ e.preventDefault(); showAnnouncementForm(); }); }
       if(annCancel){ annCancel.addEventListener('click', function(){ annForm.style.display='none'; annTitle.value=''; annBody.value=''; }); }
       if(annSubmit){ annSubmit.addEventListener('click', function(){
         var t=annTitle.value.trim();
         var b=annBody.value.trim();
         if(b===''){ alert('Please write an announcement.'); return; }
         fetch('admin-dashboard.php?action=announcement_create', {method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:'title='+encodeURIComponent(t)+'&body='+encodeURIComponent(b)})
           .then(function(r){ return r.json(); })
           .then(function(d){ if(d&&d.ok){ alert('Announcement posted'); annForm.style.display='none'; annTitle.value=''; annBody.value=''; } else { alert('Failed to post'); } })
           .catch(function(){ alert('Failed to post'); });
       }); }
       fetchUnread();
       setInterval(fetchUnread, 10000);
     })();
   </script>
  </body>
  </html>
