<?php
require_once __DIR__ . '/../config.php';
requireCustomer();
$cust = currentCustomer();
$db   = getDB();
$custData = $db->query("SELECT * FROM customers WHERE id={$cust['id']}")->fetch();
$orders   = $db->query("SELECT * FROM orders WHERE customer_id={$cust['id']} ORDER BY created_at DESC")->fetchAll();

$msg = '';
// Profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $name    = trim($_POST['name']    ?? '');
    $phone   = trim($_POST['phone']   ?? '');
    $address = trim($_POST['address'] ?? '');
    $city    = trim($_POST['city']    ?? '');
    $state   = trim($_POST['state']   ?? '');
    $pincode = trim($_POST['pincode'] ?? '');
    $db->prepare("UPDATE customers SET name=?,phone=?,address=?,city=?,state=?,pincode=? WHERE id=?")
       ->execute([$name,$phone,$address,$city,$state,$pincode,$cust['id']]);
    $_SESSION['customer_name'] = $name;
    $custData = $db->query("SELECT * FROM customers WHERE id={$cust['id']}")->fetch();
    $msg = 'Profile updated successfully!';
}
// Password change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['change_password'])) {
    $cur  = trim($_POST['current_pass'] ?? '');
    $new  = trim($_POST['new_pass']     ?? '');
    $conf = trim($_POST['confirm_pass'] ?? '');
    if (!password_verify($cur, $custData['password'])) { $msg = 'error:Current password is incorrect.'; }
    elseif (strlen($new) < 6) { $msg = 'error:New password must be at least 6 characters.'; }
    elseif ($new !== $conf) { $msg = 'error:Passwords do not match.'; }
    else {
        $db->prepare("UPDATE customers SET password=? WHERE id=?")->execute([password_hash($new,PASSWORD_BCRYPT),$cust['id']]);
        $msg = 'Password changed successfully!';
    }
}

$tab = $_GET['tab'] ?? 'orders';
$page_title = 'My Account | Balimeen Private Limited';
include __DIR__ . '/../includes/header.php';
?>
<?php if (isset($_GET['welcome'])): ?>
<div style="background:linear-gradient(135deg,#1a3a8a,#2557d6);color:#fff;text-align:center;padding:14px;font-size:.92rem;">
  🎉 Welcome to Balimeen! Your account has been created successfully.
  <a href="products.php" style="color:#f59e0b;margin-left:10px;font-weight:700;">Start Shopping →</a>
</div>
<?php endif; ?>
<div class="page-hero" style="padding:36px 0;">
  <div class="container">
    <h1 style="font-size:1.6rem;">My Account</h1>
    <div class="breadcrumb"><a href="<?= SITE_URL ?>">Home</a> → My Account</div>
  </div>
</div>

<section class="section-pad-sm" style="background:var(--bg-light);">
  <div class="container">
    <?php if ($msg): ?>
    <div class="alert alert-<?= str_starts_with($msg,'error:') ? 'error' : 'success' ?>" style="margin-bottom:18px;">
      <?= h(str_replace('error:','',$msg)) ?>
    </div>
    <?php endif; ?>
    <div class="account-grid">
      <!-- Sidebar -->
      <div class="account-sidebar">
        <div class="account-profile">
          <div class="account-avatar"><?= strtoupper(substr($custData['name'],0,1)) ?></div>
          <h4><?= h($custData['name']) ?></h4>
          <p><?= h($custData['email']) ?></p>
        </div>
        <nav class="account-nav">
          <a href="?tab=orders" class="<?= $tab==='orders'?'active':'' ?>"><i class="fas fa-box"></i> My Orders</a>
          <a href="?tab=profile" class="<?= $tab==='profile'?'active':'' ?>"><i class="fas fa-user"></i> Profile</a>
          <a href="?tab=password" class="<?= $tab==='password'?'active':'' ?>"><i class="fas fa-lock"></i> Change Password</a>
          <a href="products.php"><i class="fas fa-shopping-bag"></i> Shop Products</a>
          <a href="logout.php" style="color:#ef4444;"><i class="fas fa-sign-out-alt"></i> Logout</a>
        </nav>
      </div>

      <!-- Main Content -->
      <div>
        <?php if ($tab === 'orders'): ?>
        <!-- Orders Tab -->
        <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;">
          <h2 style="font-family:'Outfit',sans-serif;font-weight:700;color:var(--blue-dark);font-size:1.1rem;">My Orders (<?= count($orders) ?>)</h2>
          <a href="products.php" class="btn btn-primary btn-sm">+ New Order</a>
        </div>
        <?php if ($orders): ?>
          <?php foreach ($orders as $o):
            $o_items = $db->query("SELECT * FROM order_items WHERE order_id={$o['id']}")->fetchAll();
          ?>
          <div class="order-card">
            <div class="order-card-header">
              <div>
                <div class="order-no"><?= h($o['order_no']) ?></div>
                <div class="order-date"><?= date('d M Y, h:i A', strtotime($o['created_at'])) ?></div>
              </div>
              <span class="status-badge status-<?= $o['order_status'] ?>"><?= ucfirst($o['order_status']) ?></span>
            </div>
            <div class="order-card-body">
              <?php foreach ($o_items as $oi): ?>
              <div class="order-item-row">
                <img src="<?= SITE_URL ?>/assets/images/<?= h($oi['product_image']) ?>" class="order-item-img" alt="">
                <div class="order-item-info">
                  <div class="name"><?= h($oi['product_name']) ?></div>
                  <div class="qty">Qty: <?= $oi['qty'] ?> × <?= rupee($oi['price']) ?></div>
                </div>
                <div class="order-item-price"><?= rupee($oi['subtotal']) ?></div>
              </div>
              <?php endforeach; ?>
              <div class="order-total-row">
                <div>
                  <div class="label">Payment: <?= ucwords(str_replace('_',' ',$o['payment_method'])) ?></div>
                  <div style="font-size:.76rem;color:var(--text-light);">Deliver to: <?= h($o['city'].', '.$o['state']) ?></div>
                </div>
                <div class="amount"><?= rupee($o['total']) ?></div>
              </div>
            </div>
          </div>
          <?php endforeach; ?>
        <?php else: ?>
        <div style="text-align:center;padding:50px 20px;background:#fff;border-radius:var(--radius);box-shadow:var(--shadow);">
          <div style="font-size:3rem;margin-bottom:14px;">📦</div>
          <h3 style="color:var(--blue-dark);margin-bottom:8px;">No orders yet</h3>
          <p style="color:var(--text-light);margin-bottom:20px;">Browse our products and place your first order!</p>
          <a href="products.php" class="btn btn-primary">Browse Products</a>
        </div>
        <?php endif; ?>

        <?php elseif ($tab === 'profile'): ?>
        <!-- Profile Tab -->
        <div class="card">
          <div class="card-header" style="padding:18px 24px;border-bottom:1px solid #f1f5f9;"><h2 style="font-family:'Outfit',sans-serif;font-size:1rem;font-weight:700;color:var(--blue-dark);">Edit Profile</h2></div>
          <div class="card-body" style="padding:24px;">
            <form method="POST">
              <input type="hidden" name="update_profile" value="1">
              <div class="form-row">
                <div class="form-group"><label>Full Name</label><input type="text" name="name" value="<?= h($custData['name']) ?>" required></div>
                <div class="form-group"><label>Phone</label><input type="tel" name="phone" value="<?= h($custData['phone']??'') ?>"></div>
              </div>
              <div class="form-group"><label>Delivery Address</label><textarea name="address" rows="2"><?= h($custData['address']??'') ?></textarea></div>
              <div class="form-row">
                <div class="form-group"><label>City</label><input type="text" name="city" value="<?= h($custData['city']??'') ?>"></div>
                <div class="form-group"><label>State</label><input type="text" name="state" value="<?= h($custData['state']??'') ?>"></div>
                <div class="form-group"><label>PIN Code</label><input type="text" name="pincode" value="<?= h($custData['pincode']??'') ?>" maxlength="6"></div>
              </div>
              <div class="form-group"><label>Email <span style="color:#94a3b8;font-size:.78rem;">(cannot be changed)</span></label><input type="email" value="<?= h($custData['email']) ?>" disabled style="background:#f8fafc;color:#94a3b8;"></div>
              <button type="submit" class="btn btn-primary">💾 Save Changes</button>
            </form>
          </div>
        </div>

        <?php elseif ($tab === 'password'): ?>
        <!-- Password Tab -->
        <div class="card">
          <div class="card-header" style="padding:18px 24px;border-bottom:1px solid #f1f5f9;"><h2 style="font-family:'Outfit',sans-serif;font-size:1rem;font-weight:700;color:var(--blue-dark);">Change Password</h2></div>
          <div class="card-body" style="padding:24px;max-width:420px;">
            <form method="POST">
              <input type="hidden" name="change_password" value="1">
              <div class="form-group"><label>Current Password</label><input type="password" name="current_pass" required></div>
              <div class="form-group"><label>New Password</label><input type="password" name="new_pass" required placeholder="Min 6 characters"></div>
              <div class="form-group"><label>Confirm New Password</label><input type="password" name="confirm_pass" required></div>
              <button type="submit" class="btn btn-primary">🔑 Update Password</button>
            </form>
          </div>
        </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
</section>
<?php include __DIR__ . '/../includes/footer.php'; ?>
