<?php
session_set_cookie_params([
    'lifetime' => 0,                  // Session ends when browser closes
    'path' => '/',
    'domain' => '',                   // Use current domain
    'secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on', // Only HTTPS
    'httponly' => true,               // JS cannot access session cookie
    'samesite' => 'Strict'            // Protect against CSRF
]);

session_start();

// Regenerate session ID once per login
if (!isset($_SESSION['regenerated'])) {
    session_regenerate_id(true);
    $_SESSION['regenerated'] = true;

    // Save browser + IP fingerprint at login
    $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
    $_SESSION['ip'] = $_SERVER['REMOTE_ADDR']; // optional
    
   
}

$session_id = session_id();

include('../db/connection.php');

date_default_timezone_set("Asia/Kolkata");
$date = date("Y-m-d H:i:s");

$mobilenumber = $_POST['phone'] ?? '';
$otp          = $_POST['otp'] ?? '';

if (empty($mobilenumber) || empty($otp)) {
    echo "33"; // invalid input
    exit;
}

// 1. OTP verification
$sql = "SELECT id FROM login_otp_verification 
        WHERE active=0 
          AND otp=? 
          AND mobile=? 
          AND date >= NOW() - INTERVAL 5 MINUTE 
        ORDER BY date DESC 
        LIMIT 1";

$sql = "
    SELECT id 
    FROM login_otp_verification 
    WHERE active=0 
      AND otp=? 
      AND mobile=? 
      AND date >= DATE_SUB(?, INTERVAL 5 MINUTE) 
    ORDER BY id DESC 
    LIMIT 1
";

$stmt = $conn->prepare($sql);

$stmt->bind_param("sss", $otp, $mobilenumber, $date);

$stmt->execute();
$result = $stmt->get_result();
$otp_row = $result->fetch_assoc();

if (!$otp_row) {
    echo "33"; // invalid or expired otp
    exit;
}

// Mark OTP as used
$update = $conn->prepare("UPDATE login_otp_verification SET active=1 WHERE id=?");
$update->bind_param("i", $otp_row['id']);
$update->execute();

// 2. Check user
$stmt = $conn->prepare("SELECT id, user_id, email_id, name, 
                            mobile, role, password, status 
                        FROM user 
                        WHERE deletion = 0 
                            AND mobile = ? 
                        LIMIT 1");
$stmt->bind_param("s", $mobilenumber);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    echo "false_login";
    exit;
}
else
{
    $otp_verification=$user['status'];
    if($otp_verification=='active')
    {
        
        $_SESSION['skybots_email_id']  = $user['email_id'];
        $_SESSION['skybots_user_name']  = $user['name'];
        $_SESSION['skybots_user_id']   = $user['user_id'];
        $_SESSION['skybots_role']   = $user['role'];
        $_SESSION['skybots_mobile']   = $user['mobile'];
        $_SESSION['skybots_starttimeout'] = time();
        
        if ($user['role'] == "user") {
            echo "user_login"; 
        } else {
            echo "true_login"; 
        }
    }
    else
    {
        echo "verification_progress";
    }
}
?>