<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();

if (isCustomerLoggedIn()) { header('Location: /customer/dashboard.php'); exit; }

$pageTitle = 'Customer Login';
$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $pass  = trim($_POST['password'] ?? '');

    if (!$email || !$pass) {
        $errors[] = 'Email and password are required.';
    } else {
        $cust = Database::fetchOne("SELECT * FROM customers WHERE email=? AND status='active'", [$email]);
        if ($cust && password_verify($pass, $cust['password'])) {
            $_SESSION['customer_id']   = $cust['id'];
            $_SESSION['customer_name'] = $cust['contact_name'];
            logActivity('customer', $cust['id'], 'Login');
            $redirect = $_GET['redirect'] ?? '/customer/dashboard.php';
            header('Location: ' . $redirect);
            exit;
        } else {
            $errors[] = 'Invalid email or password.';
        }
    }
}

include dirname(__DIR__) . '/includes/header.php';
?>

<div class="min-h-[80vh] flex items-center justify-center px-4 py-10">
  <div class="w-full max-w-md">
    <div class="text-center mb-8">
      <div class="text-2xl font-black font-display mb-1"><span class="text-orange-500">RIG</span> N <span class="text-orange-500">DIG</span></div>
      <h1 class="text-xl font-bold">Customer Portal</h1>
      <p class="text-sm text-gray-400 mt-1">Track your quotes, estimates, and invoices</p>
    </div>

    <?php foreach ($errors as $e): ?>
    <div class="bg-red-900 border border-red-600 text-red-200 rounded p-3 text-sm mb-4"><?= e($e) ?></div>
    <?php endforeach; ?>

    <div class="card-dark p-6">
      <form method="POST">
        <div class="mb-4">
          <label class="text-xs text-gray-400 block mb-1.5">Email Address</label>
          <input type="email" name="email" required value="<?= e($_POST['email'] ?? '') ?>">
        </div>
        <div class="mb-5">
          <label class="text-xs text-gray-400 block mb-1.5">Password</label>
          <input type="password" name="password" required>
        </div>
        <button type="submit" class="btn-primary w-full py-3">Sign In →</button>
      </form>
      <div class="text-center mt-5 text-sm text-gray-400">
        Don't have an account? <a href="/customer/register.php" class="text-orange-500 hover:underline">Register here</a>
      </div>
    </div>

    <div class="text-center mt-4 text-xs text-gray-500">
      Need help? <a href="/contact.php" class="hover:text-white">Contact us</a>
    </div>
  </div>
</div>

<?php include dirname(__DIR__) . '/includes/footer.php'; ?>
