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

session_start();

/* =========================
   1. CHECK PENDING LOGIN
========================== */
if (!isset($_SESSION['pending_user_id'])) {
    jsAlert(
        'Session Expired',
        'Please log in again.',
        'warning',
        '../sign-in.php'
    );
}

$userId = (int) $_SESSION['pending_user_id'];

try {

    /* =========================
       2. FETCH USER
    ========================== */
    $stmt = $conn2->prepare("
        SELECT id, name, email
        FROM users
        WHERE id = :id
        LIMIT 1
    ");
    $stmt->execute([':id' => $userId]);

    if ($stmt->rowCount() === 0) {
        jsAlert(
            'Error',
            'User account not found.',
            'error',
            '../sign-in.php'
        );
    }

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

    /* =========================
       3. OPTIONAL RATE LIMIT
       (1 OTP per 60 seconds)
    ========================== */
    $stmt = $conn2->prepare("
        SELECT created_at
        FROM login_otps
        WHERE user_id = :uid
        ORDER BY created_at DESC
        LIMIT 1
    ");
    $stmt->execute([':uid' => $userId]);

    if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $lastSent = strtotime($row['created_at']);
        if (time() - $lastSent < 60) {
            jsAlert(
                'Please Wait',
                'You can request a new code after 60 seconds.',
                'info',
                'verify-login-otp.php'
            );
        }
    }

    /* =========================
       4. INVALIDATE OLD OTPS
    ========================== */
    $conn2->prepare("
        UPDATE login_otps
        SET used = 1
        WHERE user_id = :uid
    ")->execute([':uid' => $userId]);

    /* =========================
       5. GENERATE NEW OTP
    ========================== */
    $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' => $userId,
        ':otp' => $otp
    ]);

    /* =========================
       6. SEND EMAIL OTP
    ========================== */
    sendLoginOtpEmail($user['email'], $user['name'], $otp);

    jsAlert(
        'Verification Code Sent',
        'A new verification code has been sent to your email.',
        'success',
        'verify-login.php'
    );

} catch (PDOException $e) {

    error_log($e->getMessage());

    jsAlert(
        'System Error',
        'Unable to resend verification code. Please try again later.',
        'error',
        'verify-login.php'
    );
}
