<?php
ini_set('session.cookie_secure', 1);
ini_set('session.cookie_httponly', 1);
ini_set('session.use_strict_mode', 1);
session_start();
require 'db.php';
header('Content-Type: application/json');

$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
$ip = $_SERVER['REMOTE_ADDR'];

/* ==============================
   RATE LIMIT CHECK
============================== */

$stmt = $pdo->prepare("
SELECT COUNT(*) 
FROM login_attempts
WHERE email = ?
OR ip_address = ?
AND attempt_time > (NOW() - INTERVAL 15 MINUTE)
");

$stmt->execute([$email,$ip]);
$attempts = $stmt->fetchColumn();

if ($attempts >= 5) {
    echo json_encode([
        "status" => "blocked"
    ]);
    exit;
}

/* ==============================
   CLEANUP EXPIRED UNVERIFIED USERS
============================== */
$pdo->prepare("
    DELETE FROM users 
    WHERE is_verified = 0 
    AND code_created_at < NOW()+ INTERVAL 8 HOUR - INTERVAL 1 DAY
")->execute();


$stmt = $pdo->prepare("
SELECT 
    u.id AS user_id,
    u.username,
    u.email,
    u.password,
    u.is_verified,
    u.role,
    c.id AS company_id,
    c.org_name
FROM users u
JOIN company c ON u.org_id = c.id
WHERE u.email=? OR u.username=?
LIMIT 1
");
$stmt->execute([$email,$email]);
$user = $stmt->fetch();

/* ==============================
   BASIC VALIDATION
============================== */

// user not found OR wrong password
if (!$user || !password_verify($password, $user['password'])) {

    $stmt = $pdo->prepare("
        INSERT INTO login_attempts (email, ip_address)
        VALUES (?,?)
    ");
    $stmt->execute([$email, $_SERVER['REMOTE_ADDR']]);

    echo json_encode(["status" => "error"]);
    exit;
}

// account not approved
if ($user['is_verified'] == 0) {
    echo json_encode(["status" => "unverified"]);
    exit;
}

//After successful login (before echo success)
$pdo->prepare("
DELETE FROM login_attempts
WHERE email = ? AND ip_address = ?
")->execute([$email, $_SERVER['REMOTE_ADDR']]);

//Run occasionally (or during login):
$pdo->prepare("
DELETE FROM login_attempts
WHERE attempt_time < NOW() - INTERVAL 1 DAY
")->execute();

/* ==============================
   START SECURE LOGIN PROCESS
============================== */

$pdo->beginTransaction();

try {
    // Close previous sessions
    $stmt = $pdo->prepare("UPDATE login_sessions 
        SET is_active = 0, logout_time = NOW() + INTERVAL 8 HOUR
        WHERE user_id = ? AND is_active = 1");
    $stmt->execute([$user['user_id']]);

    // Regenerate session ID
    session_regenerate_id(true);

    $_SESSION['user_id']       = $user['user_id'];
    $_SESSION['role']          = $user['role'];
    $_SESSION['co_id']          = $user['company_id'];
    $_SESSION['session_id']    = session_id();
    $_SESSION['ip_address']    = $_SERVER['REMOTE_ADDR'];
    $_SESSION['user_agent']    = $_SERVER['HTTP_USER_AGENT'];
    $_SESSION['last_activity'] = time();

    // Insert new session
    $stmt = $pdo->prepare("INSERT INTO login_sessions 
        (user_id, session_id, ip_address, user_agent, is_active) 
        VALUES (?, ?, ?, ?, 1)");
    $stmt->execute([
        $user['user_id'],
        session_id(),
        $_SERVER['REMOTE_ADDR'],
        $_SERVER['HTTP_USER_AGENT']
    ]);

    $pdo->commit();

    echo json_encode(["status" => "success"]);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(["status" => "error"]);
}
