<?php
require_once __DIR__ . "/../includes/config.php";
require_once __DIR__ . "/../includes/functions.php";

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  $email = strtolower(trim($_POST['email'] ?? ''));
  $pass  = $_POST['password'] ?? '';

  $stmt = $pdo->prepare("SELECT * FROM users WHERE email=? LIMIT 1");
  $stmt->execute([$email]);
  $user = $stmt->fetch();

  if (!$user || !password_verify($pass, $user['password_hash'])) {
    $error = "Invalid email or password";
  } else {

    // ✅ LOGIN SUCCESS
    $_SESSION['user_id']    = $user['id'];
    $_SESSION['user_name']  = $user['name'];
    $_SESSION['user_email'] = $user['email'];

    /**
     * 🔁 CASE 1:
     * User came from Add-to-Cart before login
     * → Auto add same item to cart
     */
    if (isset($_SESSION['pending_cart'])) {

      $id  = (int)$_SESSION['pending_cart']['id'];
      $qty = (int)$_SESSION['pending_cart']['qty'];

      $_SESSION['cart'][$id] =
        ($_SESSION['cart'][$id] ?? 0) + $qty;

      unset($_SESSION['pending_cart']);

      header("Location: /myukstore/cart.php");
      exit;
    }

    /**
     * 🔁 CASE 2:
     * Normal login (no pending cart)
     */
    header("Location: /myukstore/index.php");
    exit;
  }
}

include __DIR__ . "/../includes/header.php";
?>

<h3 class="mb-3">Login</h3>

<?php if ($error): ?>
  <div class="alert alert-danger"><?= e($error) ?></div>
<?php endif; ?>

<form method="post">
  <input class="form-control mb-2"
         name="email"
         type="email"
         placeholder="Email"
         required>

  <input class="form-control mb-2"
         name="password"
         type="password"
         placeholder="Password"
         required>

  <button class="btn btn-dark w-100">Login</button>
</form>

<p class="mt-3">
  New user?
  <a href="/myukstore/auth/signup.php">Create account</a>
</p>

<?php include __DIR__ . "/../includes/footer.php"; ?>
