<?php
session_start();

// Security headers
header("X-Frame-Options: DENY");
header("X-Content-Type-Options: nosniff");
header("X-XSS-Protection: 1; mode=block");
header("Referrer-Policy: strict-origin-when-cross-origin");

error_reporting(E_ALL); // Show all errors for debugging
ini_set('display_errors', 1); // Display errors on page
require_once('includes/config.php');

// Generate CSRF token if not exists
if (empty($_SESSION['csrf_token'])) {
  $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Rate limiting - Track login attempts
if (!isset($_SESSION['login_attempts'])) {
  $_SESSION['login_attempts'] = 0;
  $_SESSION['last_attempt_time'] = time();
}

// Reset attempts after 15 minutes
if (time() - $_SESSION['last_attempt_time'] > 900) {
  $_SESSION['login_attempts'] = 0;
}

// Code for User login
if (isset($_POST['login'])) {
  // Verify CSRF token
  if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    $_SESSION['errmsg'] = "Invalid request. Please try again.";
  }
  // Check rate limiting - max 5 attempts
  elseif ($_SESSION['login_attempts'] >= 5) {
    $_SESSION['errmsg'] = "Too many login attempts. Please try again in 15 minutes.";
  } else {
    // Sanitize email input
    $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
    $password = $_POST['password'];

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $_SESSION['errmsg'] = "Invalid email format";
      $_SESSION['login_attempts']++;
      $_SESSION['last_attempt_time'] = time();
    } else {
      // Everyone logs in with EMAIL (admins and customers)
      // Join with user_details to get customer name, use username for admins
      $stmt = $con->prepare("SELECT u.id, u.email, u.username, u.password, u.role, d.name as customer_name 
                             FROM users u 
                             LEFT JOIN user_details d ON u.id = d.user_id 
                             WHERE u.email = ? LIMIT 1");
      $stmt->bind_param("s", $email);
      $stmt->execute();
      $result = $stmt->get_result();

      if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();

        // Check if password is MD5 (legacy) or bcrypt
        if (strlen($user['password']) === 32) {
          // Legacy MD5 password - verify and upgrade
          if (md5($password) === $user['password']) {
            // Upgrade to bcrypt
            $new_hash = password_hash($password, PASSWORD_DEFAULT);
            $update_stmt = $con->prepare("UPDATE users SET password = ? WHERE id = ?");
            $update_stmt->bind_param("si", $new_hash, $user['id']);
            $update_stmt->execute();
            $update_stmt->close();

            $login_success = true;
          } else {
            $login_success = false;
          }
        } else {
          // Modern bcrypt password
          $login_success = password_verify($password, $user['password']);
        }

        if ($login_success) {
          // Regenerate session ID to prevent session fixation
          session_regenerate_id(true);

          // Determine display name (username for admin, customer_name for customer)
          $display_name = ($user['role'] === 'admin') ? $user['username'] : $user['customer_name'];

          // Set session variables
          $_SESSION['login'] = $user['email'];
          $_SESSION['id'] = $user['id'];
          $_SESSION['username'] = $display_name;
          $_SESSION['role'] = isset($user['role']) ? $user['role'] : 'customer';
          $_SESSION['login_attempts'] = 0;

          // Backward compatibility for old admin files
          if ($user['role'] === 'admin') {
            $_SESSION['alogin'] = $user['username'];
            $_SESSION['aid'] = $user['id'];
          }

          // Log successful login
          $uip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP);
          $status = 1;
          $log_stmt = $con->prepare("INSERT INTO userlog(userEmail, userip, status) VALUES (?, ?, ?)");
          $log_stmt->bind_param("ssi", $user['email'], $uip, $status);
          $log_stmt->execute();
          $log_stmt->close();

          // Redirect to intended page or homepage
          $redirect = isset($_SESSION['redirect_after_login']) ? $_SESSION['redirect_after_login'] : 'index.php';
          unset($_SESSION['redirect_after_login']);

          $stmt->close();
          header("location: $redirect");
          exit();
        } else {
          $_SESSION['login_attempts']++;
          $_SESSION['last_attempt_time'] = time();
          $_SESSION['errmsg'] = "Invalid credentials";
        }
      } else {
        $_SESSION['login_attempts']++;
        $_SESSION['last_attempt_time'] = time();
        $_SESSION['errmsg'] = "Invalid credentials";
      }
      $stmt->close();
    }
  }

  // Regenerate CSRF token after attempt
  $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Check if already logged in
if (isset($_SESSION['login']) && !empty($_SESSION['login'])) {
  header("location: index.php");
  exit();
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="Login to Awesome Mall - Your trusted online shopping destination">
  <title>Login - Awesome Mall</title>

  <!-- Bootstrap 5 CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous">

  <!-- Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
    integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
    crossorigin="anonymous">

  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">

  <style>
    :root {
      --am-primary: #E8663D;
      --am-primary-hover: #d25532;
    }

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: 'Inter', sans-serif;
      overflow-x: hidden;
    }

    .auth-container {
      min-height: 100vh;
      display: flex;
    }

    .auth-form-side {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 40px 20px;
      background: #fff;
    }

    .auth-form-wrapper {
      width: 100%;
      max-width: 450px;
    }

    .logo-section {
      text-align: center;
      margin-bottom: 40px;
    }

    .logo-section img {
      height: 45px;
      margin-bottom: 10px;
    }

    .logo-section h1 {
      font-size: 28px;
      font-weight: 700;
      color: #1a1a1a;
      margin-bottom: 8px;
    }

    .logo-section p {
      color: #666;
      font-size: 15px;
    }

    .form-group {
      margin-bottom: 20px;
    }

    .form-label {
      font-weight: 500;
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      display: block;
    }

    .form-control {
      height: 48px;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      padding: 12px 16px;
      font-size: 14px;
      transition: all 0.3s;
    }

    .form-control:focus {
      border-color: var(--am-primary);
      box-shadow: 0 0 0 3px rgba(232, 102, 61, 0.1);
    }

    .password-toggle {
      position: relative;
    }

    .password-toggle .toggle-icon {
      position: absolute;
      right: 16px;
      top: 50%;
      transform: translateY(-50%);
      cursor: pointer;
      color: #999;
      font-size: 18px;
    }

    .btn-primary {
      height: 48px;
      background: var(--am-primary);
      border: none;
      border-radius: 8px;
      font-weight: 600;
      font-size: 15px;
      transition: all 0.3s;
    }

    .btn-primary:hover {
      background: var(--am-primary-hover);
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(232, 102, 61, 0.3);
    }

    .btn-primary:disabled {
      background: #ccc;
      cursor: not-allowed;
      transform: none;
    }

    .forgot-password {
      text-align: right;
      margin-top: -10px;
      margin-bottom: 20px;
    }

    .forgot-password a {
      color: var(--am-primary);
      text-decoration: none;
      font-size: 14px;
      font-weight: 500;
    }

    .divider {
      display: flex;
      align-items: center;
      margin: 30px 0;
      color: #999;
      font-size: 14px;
    }

    .divider::before,
    .divider::after {
      content: '';
      flex: 1;
      height: 1px;
      background: #e0e0e0;
    }

    .divider span {
      padding: 0 16px;
    }

    .switch-form {
      text-align: center;
      margin-top: 30px;
      color: #666;
      font-size: 14px;
    }

    .switch-form a {
      color: var(--am-primary);
      text-decoration: none;
      font-weight: 600;
    }

    .error-message {
      background: #fee;
      border-left: 4px solid #d32f2f;
      color: #d32f2f;
      padding: 12px 16px;
      border-radius: 8px;
      margin-bottom: 20px;
      font-size: 14px;
    }

    .benefits-list {
      margin-top: 30px;
      padding: 20px;
      background: #f8f9fa;
      border-radius: 8px;
    }

    .benefits-list h6 {
      font-weight: 600;
      margin-bottom: 12px;
      color: #333;
    }

    .benefits-list ul {
      list-style: none;
      padding: 0;
      margin: 0;
    }

    .benefits-list li {
      padding: 8px 0;
      color: #666;
      font-size: 14px;
    }

    .benefits-list li i {
      color: var(--am-primary);
      margin-right: 8px;
    }

    .auth-brand-side {
      flex: 1;
      background: linear-gradient(135deg, var(--am-primary) 0%, var(--am-primary-hover) 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 60px;
      position: relative;
      overflow: hidden;
    }

    .auth-brand-side::before {
      content: '';
      position: absolute;
      top: -50%;
      right: -50%;
      width: 100%;
      height: 100%;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 50%;
    }

    .brand-content {
      position: relative;
      z-index: 1;
      text-align: center;
      color: #fff;
    }

    .brand-content i {
      font-size: 80px;
      margin-bottom: 30px;
      opacity: 0.9;
    }

    .brand-content h3 {
      font-size: 32px;
      font-weight: 700;
      margin-bottom: 16px;
    }

    .brand-content p {
      font-size: 18px;
      opacity: 0.95;
      line-height: 1.6;
    }

    .features {
      margin-top: 40px;
      display: grid;
      gap: 20px;
    }

    .feature-item {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 16px;
      background: rgba(255, 255, 255, 0.1);
      border-radius: 12px;
      backdrop-filter: blur(10px);
    }

    .feature-icon {
      width: 50px;
      height: 50px;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
    }

    .feature-text h5 {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 4px;
    }

    .feature-text p {
      font-size: 14px;
      margin: 0;
      opacity: 0.9;
    }

    @media (max-width: 991px) {
      .auth-brand-side {
        display: none;
      }
    }

    @media (max-width: 576px) {
      .logo-section h1 {
        font-size: 24px;
      }
    }

    @keyframes fadeInUp {
      from {
        opacity: 0;
        transform: translateY(20px);
      }

      to {
        opacity: 1;
        transform: translateY(0);
      }
    }

    .auth-form-wrapper {
      animation: fadeInUp 0.6s ease-out;
    }

    .rate-limit-warning {
      background: #fff3cd;
      border-left: 4px solid #ffc107;
      color: #856404;
      padding: 12px 16px;
      border-radius: 8px;
      margin-bottom: 20px;
      font-size: 14px;
    }
  </style>
</head>

<body>
  <div class="auth-container">
    <div class="auth-form-side">
      <div class="auth-form-wrapper">
        <div class="logo-section">
          <a href="index.php">
            <img src="assets/images/logo.png" alt="Awesome Mall">
          </a>
          <!-- <h1>Welcome Back</h1>
          <p>Login to access your account</p> -->
        </div>

        <?php if (!empty($_SESSION['errmsg'])): ?>
          <div class="error-message">
            <i class="fas fa-exclamation-circle"></i>
            <?php echo htmlspecialchars($_SESSION['errmsg'], ENT_QUOTES, 'UTF-8'); ?>
          </div>
          <?php $_SESSION['errmsg'] = ""; ?>
        <?php endif; ?>

        <?php if ($_SESSION['login_attempts'] >= 3 && $_SESSION['login_attempts'] < 5): ?>
          <div class="rate-limit-warning">
            <i class="fas fa-exclamation-triangle"></i>
            <?php echo (5 - $_SESSION['login_attempts']); ?> login attempts remaining
          </div>
        <?php endif; ?>

        <form method="post" autocomplete="off">
          <input type="hidden" name="csrf_token"
            value="<?php echo htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8'); ?>">

          <div class="form-group">
            <label class="form-label">Email Address</label>
            <input type="email" name="email" class="form-control" placeholder="Enter your email" required
              autocomplete="email" maxlength="255">
          </div>

          <div class="form-group">
            <label class="form-label">Password</label>
            <div class="password-toggle">
              <input type="password" name="password" class="form-control" id="loginPassword"
                placeholder="Enter your password" required autocomplete="current-password" maxlength="255">
              <i class="fas fa-eye toggle-icon" onclick="togglePassword('loginPassword', this)"></i>
            </div>
          </div>

          <div class="forgot-password">
            <a href="forgot-password.php">Forgot Password?</a>
          </div>

          <button type="submit" name="login" class="btn btn-primary w-100" <?php echo ($_SESSION['login_attempts'] >= 5) ? 'disabled' : ''; ?>>
            <i class="fas fa-sign-in-alt me-2"></i> Login
          </button>
        </form>

        <div class="divider">
          <span>OR</span>
        </div>

        <div class="switch-form">
          Don't have an account? <a href="signup.php">Sign Up Now</a>
        </div>

        <div class="benefits-list">
          <h6>Why Shop With Us?</h6>
          <ul>
            <li><i class="fas fa-check-circle"></i> Wide range of products</li>
            <li><i class="fas fa-check-circle"></i> Fast & reliable delivery</li>
            <li><i class="fas fa-check-circle"></i> Secure payment options</li>
            <li><i class="fas fa-check-circle"></i> 24/7 customer support</li>
          </ul>
        </div>
      </div>
    </div>

    <div class="auth-brand-side">
      <div class="brand-content">
        <i class="fas fa-shopping-bag"></i>
        <h3>Awesome Mall</h3>
        <p>Your trusted online shopping destination in Ghana</p>

        <div class="features">
          <div class="feature-item">
            <div class="feature-icon">
              <i class="fas fa-truck"></i>
            </div>
            <div class="feature-text text-start">
              <h5>Fast Delivery</h5>
              <p>Quick shipping across Ghana</p>
            </div>
          </div>

          <div class="feature-item">
            <div class="feature-icon">
              <i class="fas fa-shield-alt"></i>
            </div>
            <div class="feature-text text-start">
              <h5>Secure Shopping</h5>
              <p>Safe & encrypted payments</p>
            </div>
          </div>

          <div class="feature-item">
            <div class="feature-icon">
              <i class="fas fa-star"></i>
            </div>
            <div class="feature-text text-start">
              <h5>Quality Products</h5>
              <p>Carefully selected items</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <script>
    function togglePassword(inputId, icon) {
      const input = document.getElementById(inputId);
      if (input.type === 'password') {
        input.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
      } else {
        input.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
      }
    }

    // Prevent form resubmission on page refresh
    if (window.history.replaceState) {
      window.history.replaceState(null, null, window.location.href);
    }
  </script>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz"
    crossorigin="anonymous"></script>
</body>

</html>
