<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../../config.php';

// ----------------------------------------------------------------------
// Brute Force Attack Protection (৫ বার ভুল করলে ৫ মিনিটের জন্য ব্লক)
// ----------------------------------------------------------------------
if (!isset($_SESSION['login_attempts'])) {
    $_SESSION['login_attempts'] = 0;
}
if ($_SESSION['login_attempts'] >= 5) {
    if (time() - $_SESSION['last_attempt_time'] < 300) { 
        $_SESSION['error'] = "Too many failed attempts. Please try again after 5 minutes.";
        header("Location: /login/"); 
        exit();
    } else {
        $_SESSION['login_attempts'] = 0; 
    }
}

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

    if (empty($email_or_user) || empty($password)) {
        $_SESSION['error'] = "Email/Username and Password are required.";
        header("Location: /login/"); exit();
    }

    // SQL Injection Security
    $stmt = $conn->prepare("SELECT id, fullname, password, is_verified FROM users WHERE email=? OR username=?");
    $stmt->bind_param("ss", $email_or_user, $email_or_user);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $user = $result->fetch_assoc();
        
        if (password_verify($password, $user['password'])) {
            
            if ($user['is_verified'] == 0) {
                $_SESSION['verify_email'] = $email_or_user; 
                $_SESSION['error'] = "Please verify your account first!";
                header("Location: /signup/verify/"); exit();
            }

            // Session Fixation Attack প্রতিরোধ
            session_regenerate_id(true);

            $_SESSION['login_attempts'] = 0;
            unset($_SESSION['last_attempt_time']);

            // হাই-সিকিউরিটি কুকি টোকেন জেনারেট
            $cookie_token = bin2hex(random_bytes(32)); 
            $hashed_token = hash('sha256', $cookie_token); 
            
            $update = $conn->prepare("UPDATE users SET remember_token=? WHERE id=?");
            $update->bind_param("si", $hashed_token, $user['id']);
            $update->execute();
            
            // 5 Years Secure Cookie
            $cookie_expire = time() + 157680000; 
            $is_secure = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on';
            
            setcookie('auth_remember', $cookie_token,[
                'expires' => $cookie_expire,
                'path' => '/',
                'domain' => '', 
                'secure' => $is_secure,
                'httponly' => true,
                'samesite' => 'Lax'
            ]);
            
            $_SESSION['user_logged_in'] = true;
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['user_name'] = $user['fullname'];
            
            header("Location: /dashboard/"); 
            exit();

        } else {
            $_SESSION['login_attempts']++;
            $_SESSION['last_attempt_time'] = time();
            usleep(rand(200000, 500000));
            $_SESSION['error'] = "Incorrect password! Please try again.";
            header("Location: /login/"); exit();
        }
    } else {
        $_SESSION['login_attempts']++;
        $_SESSION['last_attempt_time'] = time();
        usleep(rand(200000, 500000));
        $_SESSION['error'] = "No account found with this email/username.";
        header("Location: /login/"); exit();
    }
}
?>