<?php declare(strict_types=1);
session_start();
$isAdmin = isset($_SESSION['role']) && $_SESSION['role'] === 'Admin' && isset($_SESSION['user_id']) && (int)$_SESSION['user_id'] > 0;
if (!$isAdmin) { header('Location: login.html'); exit; }

$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-order-requests.php';</script></body></html>";
  exit;
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) { echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Invalid order');window.location.href='admin-order-requests.php';</script></body></html>"; exit; }
$stmt = $pdo->prepare('SELECT orq.*, u.email AS user_email FROM order_requests orq LEFT JOIN users u ON u.id = orq.user_id WHERE orq.id = :id');
$stmt->execute([':id'=>$id]);
$order = $stmt->fetch();
if (!$order) { echo "<!doctype html><html><head><meta charset='utf-8'></head><body><script>alert('Order not found');window.location.href='admin-order-requests.php';</script></body></html>"; exit; }
$items = [];
if (!empty($order['items_json'])) { $items = json_decode((string)$order['items_json'], true) ?: []; }
?>
<!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 #<?php echo (int)$order['id']; ?></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}
    .admin-layout{display:grid;grid-template-columns:280px 1fr;gap:20px}
    .admin-sidebar{background:#fff;border:1px solid var(--border);border-radius:16px;padding:20px}
    .admin-main{flex:1}
    .section{background:#fff;border:1px solid var(--border);border-radius:16px;padding:20px}
    .tp-profile-area{padding-top:0 !important;padding-bottom:40px !important}
    .tp-header-area.tp-header-inner-style{margin-bottom:0}
    .card{background:#fff;border:1px solid var(--border);border-radius:16px}
    .card-header{display:flex;align-items:center;justify-content:space-between;padding:16px 20px;border-bottom:1px solid var(--border)}
    .card-title{font-weight:800;color:#1f2937}
    .breadcrumb{display:flex;gap:8px;color:var(--text-light);font-size:13px}
    .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-color:#ffeeba}
    .status-approved{background:#d1e7dd;color:#0f5132;border-color:#badbcc}
    .status-rejected{background:#f8d7da;color:#842029;border-color:#f5c2c7}
    .grid-2{display:grid;grid-template-columns:1fr 1fr;gap:16px}
    .panel{background:#fff;border:1px solid var(--border);border-radius:12px}
    .panel .box{padding:16px}
    .list{display:grid;grid-template-columns:56px 1fr auto;gap:12px;align-items:center}
    .thumb{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--border)}
    .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}
    .btn-secondary{padding:10px 14px;border-radius:10px;border:1px solid var(--border);background:#f8fafc;color:#111;display:inline-flex;align-items:center;gap: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="card-title">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">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="card mb-20">
              <div class="card-header">
                <div>
                  <h4 class="card-title"><i class="fa-regular fa-cart-shopping" style="margin-right:8px"></i>Order #<?php echo (int)$order['id']; ?></h4>
                  <div class="breadcrumb"><span>Orders</span><span class="sep">/</span><span>View Request</span></div>
                </div>
                <div class="actions">
                  <a href="admin-order-requests.php" class="btn-secondary"><i class="fa-regular fa-arrow-left"></i><span>Back to Requests</span></a>
                </div>
              </div>
            </div>

            <div class="section mb-20">
              <div class="grid-2">
                <div>
                  <div class="panel mb-20"><div class="box">
                    <div class="d-flex justify-content-between align-items-center">
                      <div>
                        <div class="fw-bold">Summary</div>
                        <div>Payment: <?php echo htmlspecialchars((string)$order['payment_method'], ENT_QUOTES); ?></div>
                      </div>
                      <?php $st = strtolower((string)($order['status'] ?? 'pending')); ?>
                      <span class="badge status-<?php echo htmlspecialchars($st, ENT_QUOTES); ?>"><?php echo htmlspecialchars($st, ENT_QUOTES); ?></span>
                    </div>
                    <div class="mt-12">Total: Rs <?php echo number_format((float)$order['total'],2); ?></div>
                    <div>Shipping: Rs <?php echo number_format((float)$order['shipping_charge'],2); ?></div>
                    <div>Grand: Rs <?php echo number_format((float)$order['grand_total'],2); ?></div>
                    <?php if (!empty($order['payment_image_path'])): ?>
                      <div class="mt-12"><img src="<?php echo htmlspecialchars((string)$order['payment_image_path'], ENT_QUOTES); ?>" alt="payment" style="max-width:260px;border:1px solid var(--border);border-radius:12px"></div>
                    <?php endif; ?>
                    <div class="mt-12">
                      <form class="inline-form" method="post" action="admin-order-requests.php">
                        <input type="hidden" name="id" value="<?php echo (int)$order['id']; ?>"/>
                        <select name="status" required>
                          <?php if ($st === 'pending'): ?><option value="" disabled selected>Pending</option><?php endif; ?>
                          <option value="approved" <?php echo ($st==='approved'?'selected':''); ?>>Approved</option>
                          <option value="rejected" <?php echo ($st==='rejected'?'selected':''); ?>>Rejected</option>
                        </select>
                        <button class="btn-secondary" type="submit"><i class="fa-regular fa-floppy-disk"></i><span>Update Status</span></button>
                      </form>
                    </div>
                  </div></div>

                  <div class="panel mb-20"><div class="box">
                    <div class="fw-bold">Contact</div>
                    <div><?php echo htmlspecialchars((string)$order['contact'], ENT_QUOTES); ?></div>
                    <div class="text-muted" style="font-size:12px">Email: <?php echo !empty($order['user_email']) ? htmlspecialchars((string)$order['user_email'], ENT_QUOTES) : '–'; ?></div>
                  </div></div>

                  <div class="panel"><div class="box">
                    <div class="fw-bold">Shipping Address</div>
                    <div><?php echo htmlspecialchars((string)$order['first_name'].' '.$order['last_name'], ENT_QUOTES); ?></div>
                    <div><?php echo htmlspecialchars((string)$order['address'], ENT_QUOTES); ?></div>
                    <?php if (!empty($order['apartment'])): ?><div><?php echo htmlspecialchars((string)$order['apartment'], ENT_QUOTES); ?></div><?php endif; ?>
                    <div><?php echo htmlspecialchars((string)$order['city'].' '.$order['postal_code'], ENT_QUOTES); ?></div>
                    <div><?php echo htmlspecialchars((string)$order['area'], ENT_QUOTES); ?></div>
                    <div><?php echo htmlspecialchars((string)$order['phone'], ENT_QUOTES); ?></div>
                  </div></div>
                </div>

                <div>
                  <div class="panel"><div class="box">
                    <div class="fw-bold">Items</div>
                    <?php if (!$items): ?>
                      <div class="text-muted">No items listed</div>
                    <?php else: foreach ($items as $it): ?>
                      <div class="list mb-12">
                        <img class="thumb" src="<?php echo htmlspecialchars((string)($it['image1'] ?? 'assets/img/listing/listing-1-1.png'), ENT_QUOTES); ?>" alt="thumb">
                        <div>
                          <div><?php echo htmlspecialchars((string)($it['product_title'] ?? ''), ENT_QUOTES); ?></div>
                          <?php if (!empty($it['size'])): ?><div class="text-muted" style="font-size:12px">Size: <?php echo htmlspecialchars((string)$it['size'], ENT_QUOTES); ?></div><?php endif; ?>
                        </div>
                        <div>Rs <?php echo number_format((float)($it['price'] ?? 0), 2); ?></div>
                      </div>
                    <?php endforeach; endif; ?>
                  </div></div>
                </div>
              </div>
            </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>
