<?php
if (!defined('BASEPATH')) {
    die('Direct access to the script is not allowed');
}

$email = $_SESSION['email'];
$resendLimit = 2; 
$resendTimeout = 900; 

if (!isset($_SESSION['resend_count'])) {
    $_SESSION['resend_count'] = 0; 
    $_SESSION['resend_time'] = time(); 
}

if (route(1) == "send") {

    if ($_SESSION['resend_count'] >= $resendLimit && (time() - $_SESSION['resend_time']) < $resendTimeout) {
        echo json_encode(['status' => 'error', 'message' => 'Resend limit reached. Try again after 15 minutes.']);
        exit();
    }

   
    if ((time() - $_SESSION['resend_time']) >= $resendTimeout) {
        $_SESSION['resend_count'] = 0;
        $_SESSION['resend_time'] = time();
    }

    $otp_code = rand(100000, 999999);
    $_SESSION['otp'] = $otp_code;


    if (send_email($email, $otp_code)) {
        $_SESSION['resend_count']++; 
        $_SESSION['resend_time'] = time(); 
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Failed to send OTP. Please try again later.']);
    }
    exit();
}

if ($_SESSION['otp']) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['otp'])) {

        if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
            die("CSRF Token validation failed!");
        }

        if ($_POST["otp"] == $_SESSION['otp']) {
            $query = $conn->prepare("SELECT * FROM admins WHERE admin_email = :email");
            $query->execute(["email" => $email]);
            $admin = $query->fetch(PDO::FETCH_ASSOC);

            if ($admin) {
                $_SESSION["excel_adminslogin"] = 1;
                $_SESSION["excel_adminid"] = $admin["admin_id"];
                $_SESSION["excel_adminpass"] = $admin["password"];

                setcookie("a_login", 'ok', time() + (60 * 60 * 24 * 7), '/', null, null, true);
                setcookie("a_id", $admin["admin_id"], time() + (60 * 60 * 24 * 7), '/', null, null, true);
                setcookie("a_password", $admin["password"], time() + (60 * 60 * 24 * 7), '/', null, null, true);

                $conn->prepare("INSERT INTO client_report SET admin_id = :a_id, action = :action, report_ip = :ip, report_date = :date")
                    ->execute([
                        "a_id" => $admin["admin_id"],
                        "action" => "Admin logged in via 2FA page.",
                        "ip" => GetIP(),
                        "date" => date("Y-m-d H:i:s")
                    ]);

                $conn->prepare("UPDATE admins SET login_date = :date, login_ip = :ip WHERE admin_id = :admin_id")
                    ->execute([
                        "admin_id" => $admin["admin_id"],
                        "date" => date("Y-m-d H:i:s"),
                        "ip" => GetIP()
                    ]);

                unset($_SESSION['otp']);
                echo json_encode(['status' => 'success', 'redirect' => site_url($secure_admin)]);
                exit();
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Admin not found!']);
                exit();
            }
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Invalid OTP.']);
            exit();
        }
    }

    require admin_view('2faVerify');
} else {
    require PATH . '/core/temp/404.php';
}
