<?php
session_start();
require 'db.php';
header('Content-Type: application/json');

$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';

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

if (!$user || !password_verify($password, $user['password'])) {
    echo json_encode(["status" => "error"]);
    exit;
}

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

$pdo->beginTransaction();

try {

    // 1️⃣ Close ALL previous sessions for this user
    $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['id']]);

    // 2️⃣ Regenerate session ID for security
    session_regenerate_id(true);

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

    // 3️⃣ Insert new active session
    $stmt = $pdo->prepare("INSERT INTO login_sessions 
        (user_id, session_id, ip_address, user_agent, is_active) 
        VALUES (?, ?, ?, ?, 1)");
    $stmt->execute([
        $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"]);
}
