<?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='admin-dashboard.php';</script></body></html>";
    exit;
}

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("UPDATE users SET status='Active' WHERE status IS NULL"); } catch (Throwable $e) {}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $sel = trim($_POST['status_action'] ?? '');
    if ($id > 0) {
        $new = null;
        if ($sel === 'Active') { $new = 'Active'; }
        elseif ($sel === 'Block') { $new = 'Inactive'; }
        elseif ($sel === 'Unblock') { $new = 'Active'; }
        if ($new !== null) {
            try {
                $stmt = $pdo->prepare('UPDATE users SET status=:s WHERE id=:id');
                $stmt->execute([':s' => $new, ':id' => $id]);
            } catch (Throwable $e) {}
        }
    }
    $roleParam = isset($_GET['role']) ? ('?role=' . urlencode($_GET['role'])) : '';
    header('Location: admin-users.php' . $roleParam);
    exit;
}

$filterRole = isset($_GET['role']) ? trim($_GET['role']) : '';
$rows = [];
$isSellerView = ($filterRole === 'Seller');
$isBuyerView = ($filterRole === 'Buyer');
try {
    if ($isSellerView) {
        $pdo->exec('CREATE TABLE IF NOT EXISTS products (id INT AUTO_INCREMENT PRIMARY KEY, product_title VARCHAR(255) NOT NULL, user_id INT UNSIGNED, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
        try { $pdo->exec('ALTER TABLE products ADD COLUMN user_id INT UNSIGNED'); } catch (Throwable $e) {}
        $stmt = $pdo->query('SELECT u.id, u.username, u.email, u.status, u.role, u.created_at, GROUP_CONCAT(p.product_title ORDER BY p.created_at DESC SEPARATOR "||") AS products FROM users u INNER JOIN products p ON p.user_id = u.id GROUP BY u.id ORDER BY u.created_at DESC');
        $rows = $stmt ? $stmt->fetchAll() : [];
    } elseif ($isBuyerView) {
        $pdo->exec('CREATE TABLE IF NOT EXISTS order_requests (id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NULL, items_json TEXT, status ENUM("pending","approved","rejected") NOT NULL DEFAULT "pending", created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
        $stmt = $pdo->query('SELECT u.id, u.username, u.email, u.status, u.role, u.created_at, orq.id AS order_id, orq.items_json FROM users u INNER JOIN order_requests orq ON orq.user_id = u.id ORDER BY u.created_at DESC, orq.created_at DESC');
        $raw = $stmt ? $stmt->fetchAll() : [];
        $grouped = [];
        foreach ($raw as $r) {
            $uid = (int)$r['id'];
            if (!isset($grouped[$uid])) {
                $grouped[$uid] = [
                    'id' => $uid,
                    'username' => (string)$r['username'],
                    'email' => (string)$r['email'],
                    'status' => (string)$r['status'],
                    'role' => (string)$r['role'],
                    'created_at' => (string)$r['created_at'],
                    'ordered_products' => [],
                ];
            }
            $itemsJson = (string)($r['items_json'] ?? '');
            if ($itemsJson !== '') {
                $items = json_decode($itemsJson, true);
                if (is_array($items)) {
                    foreach ($items as $it) {
                        if (isset($it['product_title'])) {
                            $grouped[$uid]['ordered_products'][] = (string)$it['product_title'];
                        }
                    }
                }
            }
        }
        $rows = array_values($grouped);
    } else {
        $rows = $pdo->query('SELECT id, username, email, status, role, created_at FROM users ORDER BY created_at DESC')->fetchAll();
    }
} catch (Throwable $e) { $rows = []; }
?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Admin Users - 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>
      .admin-layout{display:flex;gap:20px}
      .admin-sidebar{width:280px;background:#fff;border:1px solid #eee;border-radius:16px;padding:16px;box-shadow:0 6px 24px rgba(0,0,0,.06)}
      .admin-sidebar .menu-title{font-size:14px;color:#999;text-transform:uppercase;margin-bottom:10px}
      .admin-sidebar ul{list-style:none;padding:0;margin:0}
      .admin-sidebar li a{display:flex;align-items:center;gap:10px;padding:10px 12px;border-radius:12px;color:#222}
      .admin-sidebar li a:hover{background:#f5f7f9}
      .admin-profile{margin-top:14px;border:1px solid #eee;border-radius:14px;padding:12px;display:flex;align-items:center;gap:12px}
      .admin-avatar{width:42px;height:42px;border-radius:10px;background:#f5f7fa;display:flex;align-items:center;justify-content:center;font-weight:600}
      .admin-main{flex:1}
      .section{background:#fff;border:1px solid #eee;border-radius:16px;padding:16px;box-shadow:0 6px 24px rgba(0,0,0,.06)}
      .latest-table table{width:100%}
      .latest-table th,.latest-table td{padding:10px 12px;border-bottom:1px solid #eee}
      .status-badge{display:inline-block;padding:4px 8px;border-radius:999px;font-size:12px}
      .status-Pending{background:#fff3cd;color:#856404;border:1px solid #ffeeba}
      .status-Active{background:#d1e7dd;color:#0f5132;border:1px solid #badbcc}
      .status-Inactive{background:#f8d7da;color:#842029;border:1px solid #f5c2c7}
      .inline-form{display:flex;gap:8px;align-items:center}
      .inline-form select{padding:6px 8px;border:1px solid #ddd;border-radius:8px}
      .inline-form button{padding:6px 10px;border-radius:8px}
      .header-left{display:flex;align-items:center;gap:12px}
      .admin-headline{font-weight:800;font-size:24px;color:#1f2937}
      .tp-header-area.tp-header-inner-style{margin-bottom:0}
      .tp-profile-area{padding-top:8px !important;padding-bottom:48px !important}
    </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">
                     <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="admin-profile">
                  <div class="admin-avatar">Admin</div>
                  <div>
                    <div class="tp-form-title mb-5">Admin</div>
                    <div class="text-muted" style="font-size:12px">Administrator</div>
                  </div>
                </div>
              </aside>
              <section class="admin-main">
                <div class="section mb-20">
                  <h4 class="tp-form-title mb-5">User List</h4>
                  <p class="mb-0">Role filter: <?php echo $filterRole ? htmlspecialchars($filterRole, ENT_QUOTES) : 'All'; ?></p>
                </div>
                <div class="section latest-table">
                  <table>
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th>Username</th>
                        <th>Email</th>
                        <?php if ($isSellerView): ?><th>Products Added</th><?php endif; ?>
                        <?php if ($isBuyerView): ?><th>Products Ordered</th><?php endif; ?>
                        <th>Role</th>
                        <th>Current Status</th>
                        <th>Status (Active / Block / Unblock)</th>
                        <th>Created</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php if (!$rows): ?>
                        <tr><td colspan="<?php echo ($isSellerView||$isBuyerView)?8:7; ?>">No users found</td></tr>
                      <?php else: foreach ($rows as $r): ?>
                        <tr>
                          <td>#<?php echo (int)$r['id']; ?></td>
                          <td><?php echo htmlspecialchars($r['username'], ENT_QUOTES); ?></td>
                          <td><?php echo htmlspecialchars($r['email'], ENT_QUOTES); ?></td>
                          <?php if ($isSellerView): ?>
                          <td>
                            <?php
                              $plist = isset($r['products']) ? (string)$r['products'] : '';
                              $items = $plist !== '' ? explode('||', $plist) : [];
                              if (!$items) { echo '<span class="text-muted">No products</span>'; }
                              else { echo '<ul style="margin:0;padding-left:18px">'; foreach ($items as $it) { echo '<li>'.htmlspecialchars($it, ENT_QUOTES).'</li>'; } echo '</ul>'; }
                            ?>
                          </td>
                          <?php endif; ?>
                          <?php if ($isBuyerView): ?>
                          <td>
                            <?php
                              $olist = isset($r['ordered_products']) ? (array)$r['ordered_products'] : [];
                              if (!$olist) { echo '<span class="text-muted">No products</span>'; }
                              else {
                                // dedupe
                                $titles = array_values(array_unique(array_map('strval', $olist)));
                                echo '<ul style="margin:0;padding-left:18px">';
                                foreach ($titles as $t) { echo '<li>'.htmlspecialchars($t, ENT_QUOTES).'</li>'; }
                                echo '</ul>';
                              }
                            ?>
                          </td>
                          <?php endif; ?>
                          <td><?php echo htmlspecialchars((string)$r['role'], ENT_QUOTES); ?></td>
                          <td>
                            <?php $st = (string)($r['status'] ?? 'Pending'); ?>
                            <span class="status-badge status-<?php echo htmlspecialchars($st, ENT_QUOTES); ?>"><?php echo htmlspecialchars($st, ENT_QUOTES); ?></span>
                          </td>
                          <td>
                            <form class="inline-form" method="post" action="admin-users.php<?php echo $filterRole?('?role='.urlencode($filterRole)) : ''; ?>">
                              <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>"/>
                              <select name="status_action" required>
                                <option value="Active" <?php echo ($st==='Active'?'selected':''); ?>>Active</option>
                                <option value="Block" <?php echo ($st==='Inactive'?'selected':''); ?>>Block</option>
                                <option value="Unblock">Unblock</option>
                              </select>
                              <button class="tp-btn-theme" type="submit"><span>Update</span></button>
                            </form>
                          </td>
                          <td><?php echo htmlspecialchars($r['created_at'], ENT_QUOTES); ?></td>
                        </tr>
                      <?php endforeach; endif; ?>
                    </tbody>
                  </table>
                </div>
              </section>
            </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>Listbnb 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>
</body>
</html>

