<?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 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) {}
try { $pdo->exec('ALTER TABLE products ADD COLUMN user_id INT UNSIGNED'); } catch (Throwable $e) {}

$updated = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['id'] ?? 0);
    $new = trim($_POST['status'] ?? '');
    if ($id > 0 && in_array($new, ['Active','Inactive'], true)) {
        try {
            $stmt = $pdo->prepare('UPDATE products SET status=:s WHERE id=:id');
            $stmt->execute([':s' => $new, ':id' => $id]);
            $updated = true;
        } catch (Throwable $e) {}
    }
    header('Location: admin-products.php');
    exit;
}

$rows = [];
try {
    $rows = $pdo->query('SELECT p.id, p.product_title, p.category, p.product_type, p.brand, p.product_size, p.`condition`, p.price, p.status, p.created_at, p.image1, u.username, u.email FROM products p LEFT JOIN users u ON u.id = p.user_id ORDER BY p.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 Products - 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;--dark:#1f2937;--light:#f9fafb;--border:#e5e7eb;--text:#374151;--text-light:#6b7280;--radius:12px;--shadow:0 4px 6px -1px rgba(0,0,0,.05),0 2px 4px -1px rgba(0,0,0,.03)}
      .admin-layout{display:flex;gap:20px}
      .admin-sidebar{width:280px;background:#fff;border:1px solid var(--border);border-radius:var(--radius);padding:20px;box-shadow:var(--shadow);position:sticky;top:100px}
      .admin-sidebar .menu-title{font-size:13px;color:var(--text-light);text-transform:uppercase;margin:24px 0 12px;letter-spacing:.05em;font-weight:600;padding-left:8px}
      .admin-sidebar ul{list-style:none;padding:0;margin:0}
      .admin-sidebar li a{display:flex;align-items:center;gap:12px;padding:10px 12px;border-radius:8px;color:var(--text);text-decoration:none;transition:all .2s ease;font-weight:500}
      .admin-sidebar li a i{width:20px;text-align:center;font-size:1.1em}
      .admin-sidebar li a:hover,.admin-sidebar li a.active{background:var(--primary-light);color:var(--primary)}
      .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 var(--border);border-radius:16px;padding:20px;box-shadow:var(--shadow)}
      .section .tp-form-title{color:var(--dark);font-weight:700}
      .latest-table table{width:100%;border-collapse:collapse}
      .latest-table thead th{font-size:13px;color:var(--text-light);text-transform:uppercase;letter-spacing:.05em;background:var(--light)}
      .latest-table th,.latest-table td{padding:12px 14px;border-bottom:1px solid var(--border)}
      .latest-table tr:hover td{background:var(--primary-light)}
      .thumb{width:56px;height:56px;border-radius:10px;object-fit:cover;background:#f5f7fa;border:1px solid var(--border);box-shadow:0 2px 8px rgba(0,0,0,.06)}
      .status-badge{display:inline-block;padding:6px 10px;border-radius:999px;font-size:12px;border:1px solid var(--border)}
      .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:8px 10px;border:1px solid var(--border);border-radius:10px}
      .inline-form button{padding:8px 12px;border-radius:10px}
      .actions{display:flex;gap:10px;align-items:center}
      .action-btn{display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border-radius:12px;border:1px solid var(--border);background:#fff;color:var(--text);box-shadow:0 2px 8px rgba(0,0,0,.04);text-decoration:none;transition:all .15s ease}
      .action-btn:hover{transform:translateY(-1px);box-shadow:0 6px 16px rgba(0,0,0,.08);background:#f8fafc}
      .action-view{border-color:#d0e6ff;color:#1e3a8a}
      .action-edit{border-color:#cde7ff;color:#0c4a6e}
      .action-delete{border-color:#ffd7d7;color:#7f1d1d}
      .action-delete:hover{background:#fff5f5}
      .btn-status{padding:8px 12px;border-radius:12px;background:var(--primary);color:#fff;border:none;box-shadow:0 2px 8px rgba(79,70,229,.25);transition:all .15s ease}
      .btn-status:hover{background:#4338ca}
      @media (max-width:991px){.admin-layout{flex-direction:column}.admin-sidebar{width:100%}}
      .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:0 !important;padding-bottom:40px !important}
      .tp-header-area.tp-header-inner-style{margin-bottom:0}
      .admin-layout{margin-top:0}
      .sidebar-card{padding:0}
      .sidebar-card .admin-sidebar{background:transparent;border:none;box-shadow:none;padding:20px}
    </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">
              <div class="section sidebar-card">
                <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" class="active"><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"><i class="fa-regular fa-users"></i> Customers</a></li>
                    <li><a href="#"><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>
                </aside>
              </div>
              <section class="admin-main">
                <div class="section mb-20">
                  <div class="d-flex justify-content-between align-items-center">
                    <div>
                      <h4 class="tp-form-title mb-5"><i class="fa-regular fa-box" style="margin-right:8px"></i>Product List</h4>
                      <p class="mb-0" style="color:var(--text-light)">All products in the database</p>
                    </div>
                    <div>
                      <a href="admin-add-product.php" class="btn-status"><span>Add Product</span></a>
                    </div>
                  </div>
                </div>
                <div class="section latest-table">
                  <table>
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th>Image</th>
                        <th>Title</th>
                        <th>Added By</th>
                        <th>Category</th>
                        <th>Type</th>
                        <th>Brand</th>
                        <th>Size</th>
                        <th>Condition</th>
                        <th>Price</th>
                        <th>Status</th>
                        <th>Change Status</th>
                        <th>Actions</th>
                        <th>Created</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php if (!$rows): ?>
                        <tr><td colspan="13">No products found</td></tr>
                      <?php else: foreach ($rows as $r): ?>
                        <tr>
                          <td>#<?php echo (int)$r['id']; ?></td>
                          <td><?php if (!empty($r['image1'])): ?><img class="thumb" src="<?php echo htmlspecialchars($r['image1'], ENT_QUOTES); ?>" alt="thumb"/><?php else: ?>–<?php endif; ?></td>
                          <td><?php echo htmlspecialchars($r['product_title'], ENT_QUOTES); ?></td>
                          <td><?php echo !empty($r['username']) || !empty($r['email']) ? htmlspecialchars(trim(($r['username']??'').' '.($r['email']?('• '.$r['email']):'')), ENT_QUOTES) : '–'; ?></td>
                          <td><?php echo htmlspecialchars($r['category'], ENT_QUOTES); ?></td>
                          <td><?php echo htmlspecialchars($r['product_type'], ENT_QUOTES); ?></td>
                          <td><?php echo htmlspecialchars((string)$r['brand'], ENT_QUOTES); ?></td>
                          <td><?php echo htmlspecialchars($r['product_size'], ENT_QUOTES); ?></td>
                          <td><?php echo htmlspecialchars($r['condition'], ENT_QUOTES); ?></td>
                          <td><?php echo number_format((float)$r['price'], 2); ?></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-products.php">
                              <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>"/>
                              <select name="status" required>
                                <?php if ($st === 'Pending'): ?>
                                  <option value="" disabled selected>Pending</option>
                                <?php endif; ?>
                                <option value="Active" <?php echo ($st==='Active'?'selected':''); ?>>Active</option>
                                <option value="Inactive" <?php echo ($st==='Inactive'?'selected':''); ?>>Inactive</option>
                              </select>
                              <button class="btn-status" type="submit"><span>Update</span></button>
                            </form>
                          </td>
                          <td>
                            <div class="actions">
                              <a class="action-btn action-view" href="admin-product-view.php?id=<?php echo (int)$r['id']; ?>"><i class="fa-solid fa-eye"></i><span>View</span></a>
                              <a class="action-btn action-edit" href="admin-edit-product.php?id=<?php echo (int)$r['id']; ?>"><i class="fa-solid fa-pen"></i><span>Edit</span></a>
                              <form action="product_delete.php" method="post" onsubmit="return confirm('Delete this product?')">
                                <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>"/>
                                <input type="hidden" name="redirect" value="admin-products.php"/>
                                <button class="action-btn action-delete" type="submit"><i class="fa-solid fa-trash"></i><span>Delete</span></button>
                              </form>
                            </div>
                          </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>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>
</body>
</html>
