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

session_start();

/* --------------------------
   CONFIG
---------------------------*/
$otp_expiration_time = 5 * 60; // 5 minutes
$max_attempts = 3;

/* --------------------------
   FUNCTIONS
---------------------------*/
function generateOTP() {
    return rand(100000, 999999);
}

/* --------------------------
   OTP GENERATION (GET)
---------------------------*/
if ($_SERVER["REQUEST_METHOD"] === "GET") {

    if (!isset($_SESSION["msmbilisim_adminid"])) {
        die("Unauthorized access");
    }

    $admin_id = $_SESSION["msmbilisim_adminid"];

    $stmt = $conn->prepare("
        SELECT admin_email, username, chat_id 
        FROM admins 
        WHERE admin_id = :admin_id 
        LIMIT 1
    ");
    $stmt->execute(['admin_id' => $admin_id]);
    $admin = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$admin) {
        die("Admin not found");
    }

    // Generate OTP
    $otp = generateOTP();

    $_SESSION['otp'] = $otp;
    $_SESSION['otp_expiry'] = time() + $otp_expiration_time;
    $_SESSION['otp_attempts'] = 0;
    $_SESSION['username'] = $admin['username'];

    /* --------------------------
       TELEGRAM OTP
    ---------------------------*/
    if (!empty($admin['chat_id'])) {

        $adminbottoken = $settings["adminbottoken"];

        $telegramMessage =
            "*Admin Verification*\n\n" .
            "Your OTP Code: `{$otp}`\n\n" .
            "Valid for 5 minutes.\n" .
            "Do NOT share this code.";

        $telegramURL = "https://api.telegram.org/bot{$adminbottoken}/sendMessage";

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $telegramURL,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => [
                'chat_id' => $admin['chat_id'],
                'text' => $telegramMessage,
                'parse_mode' => 'Markdown'
            ],
            CURLOPT_TIMEOUT => 10
        ]);
        curl_exec($ch);
        curl_close($ch);
    }

    /* --------------------------
       EMAIL OTP
    ---------------------------*/
    $to = $admin['admin_email']; // ✅ correct email
    $from = $settings["smtp_user"];
    $subject = "Admin OTP Verification";

    $emailMessage =
        "Admin Verification\n\n" .
        "Your OTP Code: {$otp}\n\n" .
        "This code is valid for 5 minutes.\n" .
        "Do not share this code with anyone.";

    $headers  = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type:text/plain;charset=UTF-8\r\n";
    $headers .= "From: {$from}\r\n";

    if (mail($to, $subject, $emailMessage, $headers)) {
        $_SESSION['success'] = "A verification code has been sent to your email and Telegram.";
    } else {
        $error = 1;
        $errorText = "Failed to send verification email.";
    }
}

/* --------------------------
   OTP VERIFICATION (POST)
---------------------------*/
if ($_SERVER["REQUEST_METHOD"] === "POST") {

    if (!isset($_SESSION['otp'], $_SESSION['otp_expiry'])) {
        die("OTP not generated.");
    }

    if (time() > $_SESSION['otp_expiry']) {
        session_unset();
        die("OTP expired. Please request a new one.");
    }

    if ($_SESSION['otp_attempts'] >= $max_attempts) {
        session_unset();
        die("Too many failed attempts. Request a new OTP.");
    }

    $entered_otp = trim($_POST['otp']);

    if ($entered_otp == $_SESSION['otp']) {

        $_SESSION['otp_verified'] = true;

        unset($_SESSION['otp'], $_SESSION['otp_expiry'], $_SESSION['otp_attempts']);

        header('Location: ' . site_url($rentaladmin));
        exit;

    } else {
        $_SESSION['otp_attempts']++;
        $error = 1;
        $errorText = "Invalid OTP";
    }
}

require admin_view('email_verification');
