<?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 order_requests (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NULL,
        items_json TEXT,
        total DECIMAL(10,2) NOT NULL,
        shipping_method VARCHAR(50) NOT NULL,
        shipping_charge DECIMAL(10,2) NOT NULL,
        discount_code VARCHAR(100) NULL,
        discount_amount DECIMAL(10,2) NOT NULL DEFAULT 0,
        grand_total DECIMAL(10,2) NOT NULL,
        contact VARCHAR(190) NOT NULL,
        contact_marketing TINYINT(1) NOT NULL DEFAULT 0,
        area VARCHAR(120) NOT NULL,
        first_name VARCHAR(120) NOT NULL,
        last_name VARCHAR(120) NOT NULL,
        address VARCHAR(255) NOT NULL,
        apartment VARCHAR(120) NULL,
        city VARCHAR(120) NOT NULL,
        postal_code VARCHAR(40) NULL,
        phone VARCHAR(60) NOT NULL,
        billing_same TINYINT(1) NOT NULL DEFAULT 1,
        billing_area VARCHAR(120) NULL,
        billing_first_name VARCHAR(120) NULL,
        billing_last_name VARCHAR(120) NULL,
        billing_address VARCHAR(255) NULL,
        billing_apartment VARCHAR(120) NULL,
        billing_city VARCHAR(120) NULL,
        billing_postal_code VARCHAR(40) NULL,
        billing_phone VARCHAR(60) NULL,
        payment_method VARCHAR(50) NOT NULL,
        payment_image_path VARCHAR(255) NULL,
        status ENUM("pending","approved","rejected") NOT NULL DEFAULT "pending",
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
} catch (Throwable $e) {}

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

$rows = [];
try {
    $rows = $pdo->query('SELECT orq.id, orq.user_id, orq.total, orq.shipping_method, orq.shipping_charge, orq.grand_total, orq.payment_method, orq.status, orq.created_at, orq.contact, orq.first_name, orq.last_name, orq.area, orq.city, orq.payment_image_path, u.email AS user_email FROM order_requests orq LEFT JOIN users u ON u.id = orq.user_id ORDER BY orq.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 Order Requests - 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:320px;background:#fff;border:1px solid var(--border);border-radius:16px;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:10px;padding:10px 12px;border-radius:8px;color:var(--text);text-decoration:none;transition:all .2s ease;font-weight:500}
      .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 var(--border);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)}
      .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-approved{background:#d1e7dd;color:#0f5132;border:1px solid #badbcc}
      .status-rejected{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}
      .segmented{display:inline-flex;border:1px solid var(--border);border-radius:12px;overflow:hidden}
      .segmented input{display:none}
      .segmented label{padding:8px 10px;cursor:pointer;font-size:12px;color:var(--text);background:#fff}
      .segmented input:checked + label{background:var(--primary-light);color:var(--primary)}
      .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)}
      .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}
      .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)}
      .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:8px !important;padding-bottom:48px !important}
      .tp-header-area.tp-header-inner-style{margin-bottom: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="tp-header-logo">
                        <a href="admin-dashboard.php" class="brand-text">ReWear</a>
                     </div>
                     <div class="admin-headline">Admin Dashboard</div>
                  </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"><i class="fa-regular fa-box"></i> Manage Products</a></li>
                    <li><a href="admin-order-requests.php" class="active"><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">
                  <h4 class="tp-form-title mb-5"><i class="fa-regular fa-cart-shopping" style="margin-right:8px"></i>Order Requests</h4>
                  <p class="mb-0" style="color:var(--text-light)">All order requests submitted by customers</p>
                </div>
                <div class="section latest-table">
                  <table>
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th>Customer</th>
                        <th>Contact</th>
                        <th>Email</th>
                        <th>City/Area</th>
                        <th>Payment</th>
                        <th>Total</th>
                        <th>Shipping</th>
                        <th>Grand</th>
                        <th>Screenshot</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 order requests found</td></tr>
                      <?php else: foreach ($rows as $r): ?>
                        <tr>
                          <td>#<?php echo (int)$r['id']; ?></td>
                          <td><?php echo htmlspecialchars((string)($r['first_name'].' '.$r['last_name']), ENT_QUOTES); ?></td>
                          <td><?php echo htmlspecialchars((string)$r['contact'], ENT_QUOTES); ?></td>
                          <td><?php echo !empty($r['user_email']) ? htmlspecialchars((string)$r['user_email'], ENT_QUOTES) : '–'; ?></td>
                          <td><?php echo htmlspecialchars((string)($r['city'].' / '.$r['area']), ENT_QUOTES); ?></td>
                          <td><?php echo htmlspecialchars((string)$r['payment_method'], ENT_QUOTES); ?></td>
                          <td>Rs <?php echo number_format((float)$r['total'], 2); ?></td>
                          <td>Rs <?php echo number_format((float)$r['shipping_charge'], 2); ?></td>
                          <td>Rs <?php echo number_format((float)$r['grand_total'], 2); ?></td>
                          <td><?php if (!empty($r['payment_image_path'])): ?><img class="thumb" src="<?php echo htmlspecialchars((string)$r['payment_image_path'], ENT_QUOTES); ?>" alt="img"/><?php else: ?>–<?php endif; ?></td>
                          <td>
                            <?php $st = strtolower((string)($r['status'] ?? 'pending')); ?>
                            <span class="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-order-requests.php">
                              <input type="hidden" name="id" value="<?php echo (int)$r['id']; ?>"/>
                              <div class="segmented">
                                <input id="st-appr-<?php echo (int)$r['id']; ?>" type="radio" name="status" value="approved" <?php echo ($st==='approved'?'checked':''); ?> required>
                                <label for="st-appr-<?php echo (int)$r['id']; ?>">Approved</label>
                                <input id="st-rej-<?php echo (int)$r['id']; ?>" type="radio" name="status" value="rejected" <?php echo ($st==='rejected'?'checked':''); ?> required>
                                <label for="st-rej-<?php echo (int)$r['id']; ?>">Rejected</label>
                              </div>
                              <button class="btn-status" type="submit"><span>Update</span></button>
                            </form>
                          </td>
                          <td>
                            <div class="actions">
                              <a class="action-btn action-view" href="admin-order-view.php?id=<?php echo (int)$r['id']; ?>"><i class="fa-solid fa-eye"></i><span>View</span></a>
                            </div>
                          </td>
                          <td><?php echo htmlspecialchars((string)$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>
