<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';

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

$error = '';
$step  = 'login'; // login | otp

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) { $error = 'Invalid request. Please try again.'; goto done; }

    $action = $_POST['action'] ?? 'login';

    if ($action === 'login') {
        $email = trim($_POST['email'] ?? '');
        $pass  = $_POST['password'] ?? '';

        if (!$email || !$pass) { $error = 'Please fill in all fields.'; goto done; }

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

        if (!$user) { $error = 'Invalid email or password.'; goto done; }

        // Lockout check
        if ($user['locked_until'] && strtotime($user['locked_until']) > time()) {
            $left = ceil((strtotime($user['locked_until']) - time()) / 60);
            $error = "Account locked. Try again in $left minute(s).";
            goto done;
        }

        // Password check (supports bcrypt and legacy md5/raw hash from old system)
        $valid = false;
        if (str_starts_with($user['password'], '$2y$')) {
            $valid = password_verify($pass, $user['password']);
        } else {
            $valid = (md5($pass) === trim($user['password'])) || ($pass === $user['password']);
            if ($valid) {
                // Upgrade to bcrypt
                $pdo->prepare("UPDATE users SET password=? WHERE id=?")->execute([password_hash($pass, PASSWORD_DEFAULT), $user['id']]);
            }
        }

        if (!$valid) {
            $attempts = $user['login_attempts'] + 1;
            $lock = $attempts >= MAX_LOGIN_ATTEMPTS ? date('Y-m-d H:i:s', time() + LOCKOUT_TIME) : $user['locked_until'];
            $pdo->prepare("UPDATE users SET login_attempts=?, locked_until=? WHERE id=?")->execute([$attempts, $lock, $user['id']]);
            $error = 'Invalid email or password.' . ($attempts >= MAX_LOGIN_ATTEMPTS ? ' Account locked.' : '');
            goto done;
        }

        if ($user['account_status'] === 'suspended') { $error = 'Your account has been suspended. Contact support.'; goto done; }
        if ($user['account_status'] === 'closed')    { $error = 'This account is closed.'; goto done; }

        $pdo->prepare("UPDATE users SET login_attempts=0, locked_until=NULL WHERE id=?")->execute([$user['id']]);

        if ($user['enable_otp_login']) {
            // Send OTP
            $otp = createOTP($pdo, $user['id'], 'login');
            sendOTPEmail($user['email'], $user['first_name'], $otp, 'login');
            $_SESSION['pending_user_id'] = $user['id'];
            $step = 'otp';
        } else {
            // Log in directly
            $pdo->prepare("UPDATE users SET last_login=NOW(), last_login_ip=? WHERE id=?")->execute([$_SERVER['REMOTE_ADDR'], $user['id']]);
            $pdo->prepare("INSERT INTO login_history (user_id,login_type,ip_address,user_agent,status) VALUES (?,?,?,?,'success')")->execute([$user['id'],'user',$_SERVER['REMOTE_ADDR'],substr($_SERVER['HTTP_USER_AGENT']??'',0,500)]);
            addNotification($pdo, $user['id'], 'Login Successful', 'You have successfully logged in to your account.', 'success');
            $_SESSION['user_id'] = $user['id'];
            header('Location: ' . ($_GET['next'] ?? '/dashboard.php'));
            exit;
        }
    } elseif ($action === 'verify_otp') {
        $uid = (int)($_SESSION['pending_user_id'] ?? 0);
        $code = trim($_POST['otp_code'] ?? '');
        if (!$uid || !$code) { $error = 'Invalid request.'; goto done; }
        if (verifyOTP($pdo, $uid, $code, 'login')) {
            $user = getUserById($pdo, $uid);
            $pdo->prepare("UPDATE users SET last_login=NOW(), last_login_ip=? WHERE id=?")->execute([$_SERVER['REMOTE_ADDR'], $uid]);
            addNotification($pdo, $uid, 'Login Successful', 'You logged in via OTP verification.', 'success');
            unset($_SESSION['pending_user_id']);
            $_SESSION['user_id'] = $uid;
            header('Location: /dashboard.php');
            exit;
        } else {
            $error = 'Invalid or expired OTP.';
            $step  = 'otp';
        }
    }
}
done:
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Login | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head>
<body class="auth-page">
<div class="container">
  <div class="d-flex justify-content-center">
    <div class="auth-card fade-in-up">
      <div class="auth-logo">
        <img src="/assets/img/logo.png" alt="<?= SITE_NAME ?>">
      </div>
      <?php if ($step === 'login'): ?>
      <h2 class="auth-title">Welcome Back</h2>
      <p class="auth-subtitle">Sign in to your account</p>
      <?php if ($error): ?>
        <div class="alert alert-danger py-2 small"><i class="fa fa-exclamation-circle me-1"></i><?= sanitize($error) ?></div>
      <?php endif; ?>
      <form method="POST">
        <?= csrf_field() ?><input type="hidden" name="action" value="login">
        <div class="mb-3">
          <label class="form-label">Email Address</label>
          <div class="input-group">
            <span class="input-group-text"><i class="fa fa-envelope"></i></span>
            <input type="email" name="email" class="form-control" placeholder="you@example.com" required>
          </div>
        </div>
        <div class="mb-3">
          <label class="form-label">Password</label>
          <div class="input-group">
            <span class="input-group-text"><i class="fa fa-lock"></i></span>
            <input type="password" name="password" id="pwdField" class="form-control" placeholder="••••••••" required>
            <button type="button" class="btn btn-outline-secondary" onclick="const f=document.getElementById('pwdField');f.type=f.type==='password'?'text':'password'"><i class="fa fa-eye"></i></button>
          </div>
        </div>
        <div class="d-flex justify-content-between mb-3">
          <div class="form-check">
            <input class="form-check-input" type="checkbox" id="remember"><label class="form-check-label small" for="remember">Remember me</label>
          </div>
          <a href="/forgot-password.php" class="small text-decoration-none" style="color:var(--primary)">Forgot password?</a>
        </div>
        <button class="btn btn-primary w-100 py-2 fw-bold">Sign In <i class="fa fa-arrow-right ms-1"></i></button>
      </form>
      <hr><p class="text-center small mb-0">Don't have an account? <a href="/register.php" style="color:var(--primary)">Register here</a></p>

      <?php else: /* OTP step */ ?>
      <h2 class="auth-title">OTP Verification</h2>
      <p class="auth-subtitle">Enter the 6-digit code sent to your email</p>
      <?php if ($error): ?>
        <div class="alert alert-danger py-2 small"><i class="fa fa-exclamation-circle me-1"></i><?= sanitize($error) ?></div>
      <?php endif; ?>
      <div class="security-gate">
        <div class="gate-icon">📧</div>
        <h5>Check Your Email</h5>
        <p>A 6-digit verification code has been sent to your registered email address.</p>
      </div>
      <form method="POST">
        <?= csrf_field() ?><input type="hidden" name="action" value="verify_otp">
        <div class="mb-3">
          <label class="form-label">OTP Code</label>
          <input type="text" name="otp_code" class="form-control form-control-lg text-center fw-bold" placeholder="000000" maxlength="6" pattern="\d{6}" required style="letter-spacing:10px;font-size:1.5rem;">
        </div>
        <button class="btn btn-primary w-100 py-2 fw-bold">Verify & Login</button>
      </form>
      <hr><p class="text-center small mb-0"><a href="/login.php" style="color:var(--primary)"><i class="fa fa-arrow-left me-1"></i>Back to Login</a></p>
      <?php endif; ?>
    </div>
  </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script src="/assets/js/main.js"></script>
</body></html>
