<?php
session_start();
include "../../connect/db.php";

if (!isset($_POST['code']) || !isset($_SESSION['chap'])) {
    echo "error";
    exit;
}

$code = mysqli_real_escape_string($con, $_POST['code']);
$email = $_SESSION['chap'];

// Handle admin OTP resend
if ($code === 'resend') {
    $sql = mysqli_query($con, "SELECT admin_otp FROM users WHERE email = '$email'");
    $row = mysqli_fetch_assoc($sql);
    if (!empty($row['admin_otp']) && $row['admin_otp'] == 1) {
        $adminOtp = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
        $_SESSION['admin_otp'] = $adminOtp;
        $_SESSION['admin_otp_email'] = $email;
        $_SESSION['admin_otp_time'] = time();

        $sql2 = mysqli_query($con, "SELECT firstname, lastname FROM users WHERE email = '$email'");
        $urow = mysqli_fetch_assoc($sql2);
        $customerName = $urow['firstname'] . ' ' . $urow['lastname'];
        try {
            require_once __DIR__ . '/../../includes/email.php';
            sendBankEmail($email, 'Your Verification Code', $customerName, 'Account Verification',
                '<p>Dear <strong>' . htmlspecialchars($customerName) . '</strong>,</p>
                <p>A new verification code has been generated for your account.</p>
                <p style="text-align:center;font-size:24px;font-weight:700;letter-spacing:4px;color:#0a1f44;padding:12px 24px;background:#f0f2ff;border-radius:6px;margin:12px 0;">' . $adminOtp . '</p>
                <p>Please enter this code on the login page to continue. This code expires in 10 minutes.</p>
                <p>If you did not request this code, please contact support immediately.</p>',
                null, null, ['User' => $customerName, 'Email' => $email, 'Code' => $adminOtp]);
        } catch (Exception $e) { error_log('Admin OTP email failed: ' . $e->getMessage()); }
        echo "admin_otp";
    } else {
        echo "error";
    }
    exit;
}

$sql = mysqli_query($con, "SELECT auth_code, admin_otp FROM users WHERE email = '$email'");
$row = mysqli_fetch_assoc($sql);

// Validate against the OTP stored by checkpin.php
if ($code === $row['auth_code'] && !empty($row['auth_code'])) {
    // Clear used OTP
    mysqli_query($con, "UPDATE users SET auth_code = '' WHERE email = '$email'");

    // Check if Admin OTP is enabled for this user
    if (!empty($row['admin_otp']) && $row['admin_otp'] == 1) {
        // Generate 6-digit admin OTP
        $adminOtp = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
        $_SESSION['admin_otp'] = $adminOtp;
        $_SESSION['admin_otp_email'] = $email;
        $_SESSION['admin_otp_time'] = time();

        $sql2 = mysqli_query($con, "SELECT firstname, lastname FROM users WHERE email = '$email'");
        $urow = mysqli_fetch_assoc($sql2);
        $customerName = $urow['firstname'] . ' ' . $urow['lastname'];
        try {
            require_once __DIR__ . '/../../includes/email.php';
            sendBankEmail($email, 'Your Verification Code', $customerName, 'Account Verification',
                '<p>Dear <strong>' . htmlspecialchars($customerName) . '</strong>,</p>
                <p>A verification code is required to access your account.</p>
                <p style="text-align:center;font-size:24px;font-weight:700;letter-spacing:4px;color:#0a1f44;padding:12px 24px;background:#f0f2ff;border-radius:6px;margin:12px 0;">' . $adminOtp . '</p>
                <p>Please enter the code sent to your email address to continue. This code expires in 10 minutes.
</p>
                <p>If you did not request this code, please contact support immediately.</p>',
                null, null, ['User' => $customerName, 'Email' => $email, 'Code' => $adminOtp]);
        } catch (Exception $e) { error_log('Admin OTP email failed: ' . $e->getMessage()); }

        echo "admin_otp";
    } else {
        $_SESSION['chap'] = $email;
        echo "success";
    }
} else {
    echo "incorrect";
}
