<?php
require_once '../includes/config.php';
require_once 'login-otp-security.php';
require_once 'smtp_mail.php';
require_once 'helpers.php';

session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $otp = trim($_POST['otp'] ?? '');
    $uid = $_SESSION['pending_user_id'] ?? null;

    if (!$uid || $otp === '') {
        jsAlert('Error', 'Invalid session or OTP', 'error', '../sign-in.php');
    }

    $stmt = $conn2->prepare("
        SELECT * FROM login_otps
        WHERE user_id = :uid
          AND otp = :otp
          AND used = 0
          AND expires_at > NOW()
        LIMIT 1
    ");
    $stmt->execute([
        ':uid' => $uid,
        ':otp' => $otp
    ]);

    if ($stmt->rowCount() === 0) {
        jsAlert('Invalid Code', 'OTP is incorrect or expired', 'error');
    }

    // Mark OTP used
    $conn2->prepare("
        UPDATE login_otps SET used = 1 WHERE user_id = :uid
    ")->execute([':uid' => $uid]);

    /* TRUST DEVICE FOR 7 DAYS */
    $deviceHash = getDeviceHash();

    $conn2->prepare("
        INSERT INTO user_trusted_devices (user_id, device_hash, expires_at)
        VALUES (:uid, :dh, DATE_ADD(NOW(), INTERVAL 7 DAY))
    ")->execute([
        ':uid' => $uid,
        ':dh'  => $deviceHash
    ]);

    unset($_SESSION['pending_user_id']);

    // Finish login
    $stmt = $conn2->prepare("
        SELECT u.*, c.company_name
        FROM users u
        JOIN company c ON c.id = u.company_id
        WHERE u.id = :uid
        LIMIT 1
    ");
    $stmt->execute([':uid' => $uid]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    $_SESSION['loggedin'] = true;
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['company_id'] = $user['company_id'];
    $_SESSION['company_name'] = $user['company_name'];
    $_SESSION['email'] = $user['email'];
    $_SESSION['user_name'] = $user['name'];
    $_SESSION['role'] = $user['role'];

    header(
        $user['role'] === 'super_admin'
            ? "Location: ../master-sub.php"
            : "Location: ../dashboard.php"
    );
    exit;
}
