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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: ../sign-in.php");
    exit;
}

$email    = trim($_POST['email'] ?? '');
$password = trim($_POST['password'] ?? '');

/* =========================
   1. BASIC VALIDATION
========================== */
if ($email === '' || $password === '') {
    jsAlert(
        'Missing Information',
        'Please fill in both email and password.',
        'warning',
        '../sign-in.php'
    );
}

try {

    /* =========================
       2. FETCH USER + COMPANY
    ========================== */
    $stmt = $conn2->prepare("
        SELECT 
            u.id,
            u.company_id,
            u.name,
            u.email,
            u.password,
            u.role,
            u.email_verified,
            c.company_name
        FROM users u
        INNER JOIN company c ON c.id = u.company_id
        WHERE u.email = :email
        LIMIT 1
    ");
    $stmt->execute([':email' => $email]);

    if ($stmt->rowCount() === 0) {
        jsAlert(
            'Account Not Found',
            'No user account exists with this email address.',
            'error',
            '../sign-in.php'
        );
    }

    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    /* =========================
       3. EMAIL VERIFIED?
    ========================== */
    if ((int)$user['email_verified'] === 0) {
        jsAlert(
            'Email Verification Required',
            'Please verify your email before logging in.',
            'info',
            'verify-email.php?email=' . urlencode($email)
        );
    }

    /* =========================
       4. PASSWORD CHECK
    ========================== */
    if (!password_verify($password, $user['password'])) {
        jsAlert(
            'Login Failed',
            'Incorrect email or password.',
            'error',
            '../sign-in.php'
        );
    }

    /* =========================
       5. DEVICE TRUST CHECK
    ========================== */
    $deviceHash = getDeviceHash();

    $stmt = $conn2->prepare("
        SELECT id FROM user_trusted_devices
        WHERE user_id = :uid
          AND device_hash = :dh
          AND expires_at > NOW()
        LIMIT 1
    ");
    $stmt->execute([
        ':uid' => $user['id'],
        ':dh'  => $deviceHash
    ]);

    $isTrustedDevice = $stmt->rowCount() > 0;

    session_start();
    session_regenerate_id(true);

    /* =========================
       6. NEW DEVICE → SEND OTP
    ========================== */
    if (!$isTrustedDevice) {

        $otp = random_int(100000, 999999);

        $stmt = $conn2->prepare("
            INSERT INTO login_otps (user_id, otp, expires_at)
            VALUES (:uid, :otp, DATE_ADD(NOW(), INTERVAL 10 MINUTE))
        ");
        $stmt->execute([
            ':uid' => $user['id'],
            ':otp' => $otp
        ]);

        sendLoginOtpEmail($user['email'], $user['name'], $otp);

        $_SESSION['pending_user_id'] = $user['id'];

        header("Location: verify-login.php");
        exit;
    }

    /* =========================
       7. TRUSTED DEVICE → LOGIN
    ========================== */
    $_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'];

    /* =========================
       8. ROLE-BASED REDIRECT
    ========================== */
    if ($user['role'] === 'super_admin') {
        header("Location: ../master-sub.php");
    } else {
        header("Location: ../dashboard.php");
    }
    exit;

} catch (PDOException $e) {

    error_log($e->getMessage());

    jsAlert(
        'System Error',
        'An unexpected error occurred. Please try again later.',
        'error',
        '../sign-in.php'
    );
}
