<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Direct test: http://localhost/newbank/apps/login/login.php?test=1
if (isset($_GET['test'])) {
    header('Content-Type: text/plain');
    echo "Backend is reachable\n";
    echo "settings-helper: " . (function_exists('rate_limit_check') ? 'OK' : 'MISSING') . "\n";
    echo "rate_limit_check: ";
    $r = @rate_limit_check('test_direct_' . rand(1000,9999));
    echo ($r ? 'OK' : 'LIMITED') . "\n";
    echo "session_start: OK\n";
    echo "DB: " . (file_exists('../../connect/db.php') ? 'file exists' : 'MISSING') . "\n";
    exit;
}

session_start();

// Ensure settings functions are available (fallback if auto-prepend fails)
if (!function_exists('rate_limit_check')) {
    require_once __DIR__ . '/../../includes/settings-helper.php';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !rate_limit_check('login_' . $_SERVER['REMOTE_ADDR'])) {
    echo 'rate_limited';
    exit();
}

include "../../connect/db.php";

function getUserBrowser() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) return 'Opera';
    elseif (strpos($user_agent, 'Edge')) return 'Edge';
    elseif (strpos($user_agent, 'Chrome')) return 'Chrome';
    elseif (strpos($user_agent, 'Safari')) return 'Safari';
    elseif (strpos($user_agent, 'Firefox')) return 'Firefox';
    elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) return 'Internet Explorer';
    return 'Other';
}

if (isset($_POST['pass'])) {
    $id = mysqli_real_escape_string($mysqli, $_POST['id']);
    $pass = mysqli_real_escape_string($mysqli, $_POST['pass']);
    $timezone = mysqli_real_escape_string($mysqli, $_POST['timezone'] ?? 'UTC');

    $sql = mysqli_query($mysqli, "SELECT * FROM users WHERE account_num = '$id' OR email = '$id'");

    if (mysqli_num_rows($sql) != 0) {
        $row = mysqli_fetch_assoc($sql);
        $status = $row['status'];
        $reg_step = $row['reg_step'];
        $email = $row['email'];
        $otp_stat = $row['otp_stat'];
        $pin_stat = isset($row['pin_stat']) ? $row['pin_stat'] : 'active';
        $admin_otp_flag = $row['admin_otp'];

        if ($pass == $row['password']) {
            $browser = getUserBrowser();
            $ip_address = $_SERVER['REMOTE_ADDR'];
            $log_time = date('Y-m-d H:i:s');
            $log_query = "INSERT INTO user_logs (browser, log_time, user) VALUES ('$browser', '$log_time', '$email')";
            mysqli_query($mysqli, $log_query);

            if ($reg_step == "step1") {
                $_SESSION['inactive'] = $email;
                echo "step2";
            } elseif ($reg_step == "step2") {
                $_SESSION['inactive'] = $email;
                echo "step3";
            } elseif ($row['kyc_status'] == "pending") {
                $_SESSION['chap'] = $email;
                $_SESSION['user_timezone'] = $timezone;
                echo "kyc";
            } elseif ($status == "suspended") {
                echo "suspended";
            } elseif ($status == "inactive") {
                $_SESSION['inactive'] = $email;
                echo "inactive";
            } elseif ($status == "terminated") {
                echo "terminated";
            } elseif ($status == "review") {
                $_SESSION['chap'] = $email;
                $_SESSION['user_timezone'] = $timezone;
                echo "review";
            } else {
                $sql22 = mysqli_query($con, "UPDATE users SET last_login = '$log_time' WHERE email = '$email'");
                $_SESSION['chap'] = $email;
                $_SESSION['user_timezone'] = $timezone;

                // If PIN challenge is disabled, handle auth flow inline
                if ($pin_stat === 'inactive') {
                    require_once __DIR__ . '/../../includes/email.php';

                    if (!empty($admin_otp_flag) && $admin_otp_flag == 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();

                        $customerName = $row['firstname'] . ' ' . $row['lastname'];
                        try {
                            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 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 "success";
                    }
                } else {
                    echo "pin_required";
                }
            }
        } else {
            echo "incorrect";
        }
    } else {
        echo "notexist";
    }
}
