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

$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-2.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) {}

$orders = [];
try {
  $stmt = $pdo->prepare('SELECT id, grand_total, status, created_at FROM order_requests WHERE user_id = :u ORDER BY created_at DESC');
  $stmt->execute([':u' => $userId]);
  $orders = $stmt->fetchAll() ?: [];
} catch (Throwable $e) { $orders = []; }
?>
<!doctype html>
<html class="no-js" lang="zxx">
<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>My Orders - 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>
    .orders-hero{padding:80px 0;background:linear-gradient(135deg,#f3f4f6 0%,#ffe6ef 100%)}
    .orders-sub{color:#6b7280;letter-spacing:.12em;font-weight:700;font-size:.9rem;margin-bottom:.5rem}
    .orders-title{color:#1f2937;font-weight:800;font-size:2rem;margin:0 0 .5rem}
    .orders-wrap{padding:40px 0}
    .orders-card{background:#fff;border:1px solid #e5e7eb;border-radius:16px;padding:18px;box-shadow:0 8px 24px rgba(17,24,39,.06);margin-bottom:14px}
    .orders-row{display:grid;grid-template-columns:120px 1fr 1fr 120px 120px;gap:12px;align-items:center}
    .orders-head{font-weight:700;color:#111827;border-bottom:1px solid #e5e7eb;padding-bottom:10px;margin-bottom:10px}
    .badge{display:inline-block;padding:4px 8px;border-radius:999px;font-size:12px;border:1px solid #e5e7eb;color:#374151;background:#f9fafb}
    .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}
    @media (max-width:991px){.orders-row{grid-template-columns:1fr 1fr;gap:8px}.hide-sm{display:none}}
  </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="tp-header-logo">
              <a href="index-2.php" class="brand-text">ReWear</a>
            </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>
                  <li class="has-dropdown"><a href="index-2.php">Home</a></li>
                  <li class="has-dropdown">
                    <a href="#">Categories</a>
                    <ul class="submenu tp-submenu">
                      <li><a href="category.php?category=Summer%20Clothing">Summer Clothing</a></li>
                      <li><a href="category.php?category=Winter%20Clothing">Winter Clothing</a></li>
                      <li><a href="category.php?category=Party%20%26%20Formal%20Wear">Party & Formal Wear</a></li>
                      <li><a href="category.php?category=Active%20Wear%20%2F%20Gym%20Wear">Active Wear / Gym Wear</a></li>
                      <li><a href="category.php?category=Nightwear%20%2F%20Sleepwear">Nightwear / Sleepwear</a></li>
                      <li><a href="category.php?category=Modest%20Wear">Modest Wear</a></li>
                      <li><a href="category.php?category=Casual%20Wear">Casual Wear</a></li>
                    </ul>
                  </li>
                  <li><a href="about-us.html">About Us</a></li>
                  <li class="has-dropdown"><a href="#site-contact">Contact</a></li>
                </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-btn d-none d-xl-block">
                <a class="tp-btn-theme" href="listing-ads.php"><span>Post Your Ad <i class="fa-sharp fa-regular fa-arrow-right-long"></i></span></a>
              </div>
              <div class="tp-header-bar d-xl-none">
                <button class="tp-menu-bar"><i class="fa-sharp fa-regular fa-bars-staggered"></i></button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </header>

  <main>
    <section class="orders-hero">
      <div class="container">
        <div class="orders-sub">MY ORDERS</div>
        <h1 class="orders-title">Your order history</h1>
        <p style="color:#6b7280;max-width:760px">Track your order requests, statuses, and totals. Click view to see full details.</p>
      </div>
    </section>
    <section class="orders-wrap">
      <div class="container">
        <div class="orders-card">
          <div class="orders-row orders-head">
            <div>Order ID</div>
            <div>Placed</div>
            <div>Status</div>
            <div class="hide-sm">Total</div>
            <div>Actions</div>
          </div>
          <?php if (!$orders): ?>
            <div style="padding:8px 0;color:#6b7280">No orders yet. <a href="index-2.php" style="color:#d61c5d;text-decoration:none">Browse products</a></div>
          <?php else: foreach ($orders as $o): ?>
            <div class="orders-row" style="padding:8px 0;border-top:1px solid #f3f4f6">
              <div>#<?php echo (int)$o['id']; ?></div>
              <div><?php echo htmlspecialchars((string)$o['created_at'], ENT_QUOTES); ?></div>
              <?php $st = strtolower((string)$o['status']); ?>
              <div><span class="badge status-<?php echo htmlspecialchars($st, ENT_QUOTES); ?>"><?php echo htmlspecialchars($st, ENT_QUOTES); ?></span></div>
              <div class="hide-sm">Rs <?php echo number_format((float)$o['grand_total'],2); ?></div>
              <div><a class="tp-btn-border" href="order_request.php?id=<?php echo (int)$o['id']; ?>"><span>View</span></a></div>
            </div>
          <?php endforeach; endif; ?>
        </div>
      </div>
    </section>
  </main>
  <footer>
    <div class="tp-footer-area z-index black-bg fix p-relative pt-115 pb-70" id="site-contact">
      <div class="tp-footer-big-text d-none d-md-block">
        <span>ReWear</span>
      </div>
      <div class="container">
        <div class="row">
          <div class="col-xl-6 col-lg-6 mb-50">
            <div class="tp-footer-widget">
              <div class="tp-form-box">
                <div class="tp-footer-title-box pb-50">
                  <span class="tp-section-subtitle-2 mb-10">support email</span>
                  <h4 class="tp-form-title"><a href="mailto:info@listbnb.com">info@listbnb.com</a></h4>
                </div>
                <form action="contact_submit.php" method="post" id="footer-contact-form">
                  <div class="row">
                    <div class="col-xl-6 col-lg-6 col-md-6 col-12">
                      <div class="tp-form-input-box">
                        <label>full name</label>
                        <input type="text" name="full_name" placeholder="Your name" required>
                      </div>
                    </div>
                    <div class="col-xl-6 col-lg-6 col-md-6 col-12">
                      <div class="tp-form-input-box">
                        <label>email address</label>
                        <input type="email" name="email" placeholder="Your email" required>
                      </div>
                    </div>
                    <div class="col-12">
                      <div class="tp-form-textarea-box">
                        <label>message</label>
                        <textarea name="message" placeholder="Your message" required></textarea>
                      </div>
                    </div>
                  </div>
                </form>
                <div class="tp-form-button">
                  <button class="tp-btn-black theme-bg" type="submit" form="footer-contact-form">
                    <span>Submit <i class="fa-sharp fa-regular fa-arrow-right-long"></i></span>
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div class="col-xl-6 col-lg-6 mb-50">
            <div class="tp-footer-widget">
              <div class="tp-footer-right">
                <h4 class="tp-form-title pb-30">Essential</h4>
                <div class="tp-footer-list pb-65">
                  <ul>
                    <li><a href="#">Company & Contact Info</a></li>
                    <li><a href="sitemap.html">Sitemap</a></li>
                    <li><a href="privacy.html">Privacy Policy</a></li>
                    <li><a href="faq.html">FAQ Page</a></li>
                    <li><a href="terms.html">Terms & Conditions</a></li>
                  </ul>
                </div>
                <div class="tp-footer-content tp-footer-content-border">
                  <p><i>ReWear</i> a Largest Classified Listing Marketplace offers perfect WordPress Ads classified Themes to build your own classified websites.</p>
                  <a href="contact.html"><i class="fal fa-arrow-right-long"></i> Get It Now</a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <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</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>
                  <a href="#"><i class="fa-brands fa-youtube"></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/swiper-bundle.js"></script>
  <script src="assets/js/slick.js"></script>
  <script src="assets/js/magnific-popup.js"></script>
  <script src="assets/js/nice-select.js"></script>
  <script src="assets/js/purecounter.js"></script>
  <script src="assets/js/countdown.js"></script>
  <script src="assets/js/wow.js"></script>
  <script src="assets/js/isotope-pkgd.js"></script>
  <script src="assets/js/imagesloaded-pkgd.js"></script>
  <script src="assets/js/ajax-form.js"></script>
  <script src="assets/js/main.js"></script>
</body>
</html>
