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

$title .= "Verify Email";

// Must have OTP verification session
if (!isset($_SESSION["otp_verify_client_id"]) || empty($_SESSION["otp_verify_client_id"])) {
    Header("Location:" . site_url(''));
    exit();
}

$clientId = $_SESSION["otp_verify_client_id"];
$maskedEmail = $_SESSION["otp_verify_email"] ?? '';

// Get OTP settings from admin
$otpExpiryMinutes  = $settings["otp_expiry_minutes"] ?? 10;
$otpMaxAttempts    = $settings["otp_max_attempts"] ?? 5;
$otpResendCooldown = $settings["otp_resend_cooldown"] ?? 60;
$otpMaxResendHour  = $settings["otp_max_resend_per_hour"] ?? 3;

// Fetch client data
$clientStmt = $conn->prepare("SELECT * FROM clients WHERE client_id = :id");
$clientStmt->execute(["id" => $clientId]);
$otpClient = $clientStmt->fetch(PDO::FETCH_ASSOC);

if (!$otpClient) {
    unset($_SESSION["otp_verify_client_id"]);
    unset($_SESSION["otp_verify_email"]);
    Header("Location:" . site_url(''));
    exit();
}

// Already verified? Auto-login and redirect
if ($otpClient["email_verified"] == 1) {
    // Auto login
    $_SESSION["msmbilisim_userlogin"] = 1;
    $_SESSION["msmbilisim_userid"] = $otpClient["client_id"];
    $_SESSION["msmbilisim_userpass"] = $otpClient["password"];
    $_SESSION["recaptcha"] = false;
    
    $access = json_decode($otpClient["access"], true);
    if (is_array($access) && !empty($access["admin_access"])) {
        $_SESSION["msmbilisim_adminlogin"] = 1;
    }
    
    $currency_hash = get_currency_hash_by_code(get_default_currency());
    $_SESSION["currency_hash"] = $currency_hash;
    
    setcookie("u_id", $otpClient["client_id"], strtotime('+7 days'), '/', null, null, true);
    setcookie("u_password", $otpClient["password"], strtotime('+7 days'), '/', null, null, true);
    setcookie("u_login", 'ok', strtotime('+7 days'), '/', null, null, true);
    setcookie("currency_hash", $currency_hash, strtotime('+7 days'), '/', null, null, true);
    
    // Cleanup session
    unset($_SESSION["otp_verify_client_id"]);
    unset($_SESSION["otp_verify_email"]);
    unset($_SESSION["otp_resend_cooldown"]);
    
    Header("Location:" . site_url(''));
    exit();
}

$error = 0;
$errorText = '';
$success = 0;
$successText = '';

// ─── RESEND OTP (AJAX) ───
if (route(1) == "resend") {
    header("Content-Type: application/json; charset=utf-8");
    
    // CSRF check
    if (!isset($_POST["csrf_token"]) || !hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'] ?? '')) {
        echo json_encode(["success" => false, "message" => "Invalid request."]);
        exit();
    }
    
    // Cooldown check
    $cooldownSeconds = $otpResendCooldown;
    if (!canResendOtp($_SESSION["otp_resend_cooldown"] ?? null, $cooldownSeconds)) {
        $remaining = $cooldownSeconds - (time() - ($_SESSION["otp_resend_cooldown"] ?? time()));
        echo json_encode(["success" => false, "message" => "Please wait {$remaining} seconds before resending.", "cooldown" => $remaining]);
        exit();
    }
    
    // Resend limit check
    if (!checkResendLimit($conn, $clientId, $otpMaxResendHour)) {
        echo json_encode(["success" => false, "message" => "Maximum resend limit reached. Please try again later."]);
        exit();
    }
    
    // Generate and store new OTP
    $otp = generateOtp();
    storeOtp($conn, $clientId, $otp, $otpExpiryMinutes);
    
    // Send email
    $emailSent = sendOtpEmail($otpClient["email"], $otp, $settings["site_name"], $settings["smtp_user"], $otpExpiryMinutes);
    
    if ($emailSent) {
        // Update cooldown and resend count
        $_SESSION["otp_resend_cooldown"] = time();
        incrementResendCount($conn, $clientId);
        
        echo json_encode([
            "success" => true, 
            "message" => "A new verification code has been sent to your email.",
            "cooldown" => $cooldownSeconds,
            "expiry" => $otpExpiryMinutes * 60
        ]);
    } else {
        echo json_encode(["success" => false, "message" => "Failed to send email. Please try again."]);
    }
    exit();
}

// ─── VERIFY OTP (POST) ───
if ($_SERVER["REQUEST_METHOD"] == "POST" && route(1) != "resend") {
    // CSRF check
    if (!isset($_POST["csrf_token"]) || !hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'] ?? '')) {
        $error = 1;
        $errorText = "Invalid request. Please refresh and try again.";
    } else {
        // Collect OTP digits
        $otpInput = '';
        for ($i = 1; $i <= 6; $i++) {
            $digit = $_POST["otp_digit_{$i}"] ?? '';
            $otpInput .= $digit;
        }
        
        // Validate input
        if (strlen($otpInput) != 6 || !ctype_digit($otpInput)) {
            $error = 1;
            $errorText = "Please enter a valid 6-digit code.";
        } else {
            // Re-fetch fresh client data
            $freshStmt = $conn->prepare("SELECT * FROM clients WHERE client_id = :id");
            $freshStmt->execute(["id" => $clientId]);
            $freshClient = $freshStmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$freshClient) {
                $error = 1;
                $errorText = "Account not found.";
            } elseif ($freshClient["otp_attempts"] >= $otpMaxAttempts) {
                // Locked out
                $error = 1;
                $errorText = "Too many attempts. Please click 'Resend Code' to get a new code.";
                
                // Clear OTP and mark expired
                $lockStmt = $conn->prepare("UPDATE clients SET otp_code = NULL, otp_status = 'expired' WHERE client_id = :id");
                $lockStmt->execute(["id" => $clientId]);
            } elseif (!$freshClient["otp_code"]) {
                $error = 1;
                $errorText = "No verification code found. Please click 'Resend Code'.";
            } elseif (strtotime($freshClient["otp_expiry"]) < time()) {
                // Expired
                $error = 1;
                $errorText = "Your verification code has expired. Please click 'Resend Code' to get a new one.";
                
                $expStmt = $conn->prepare("UPDATE clients SET otp_status = 'expired' WHERE client_id = :id");
                $expStmt->execute(["id" => $clientId]);
            } elseif (!verifyOtpCode($freshClient["otp_code"], $otpInput)) {
                // Wrong code
                $newAttempts = $freshClient["otp_attempts"] + 1;
                $remaining = $otpMaxAttempts - $newAttempts;
                
                $incStmt = $conn->prepare("UPDATE clients SET otp_attempts = :attempts WHERE client_id = :id");
                $incStmt->execute(["attempts" => $newAttempts, "id" => $clientId]);
                
                if ($remaining <= 0) {
                    $error = 1;
                    $errorText = "Too many attempts. Please click 'Resend Code' to get a new code.";
                    $lockStmt = $conn->prepare("UPDATE clients SET otp_code = NULL, otp_status = 'expired' WHERE client_id = :id");
                    $lockStmt->execute(["id" => $clientId]);
                } else {
                    $error = 1;
                    $errorText = "Incorrect code. {$remaining} attempt(s) remaining.";
                }
            } else {
                // ✅ OTP is correct!
                $verifyStmt = $conn->prepare("UPDATE clients SET 
                    email_verified = 1, 
                    otp_status = 'verified', 
                    otp_code = NULL, 
                    otp_expiry = NULL, 
                    otp_attempts = 0,
                    otp_resend_count = 0,
                    otp_resend_reset_at = NULL
                    WHERE client_id = :id");
                $verifyStmt->execute(["id" => $clientId]);
                
                // Log the verification
                $logStmt = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date");
                $logStmt->execute([
                    "c_id"   => $clientId,
                    "action" => "Email verified via OTP.",
                    "ip"     => GetIP(),
                    "date"   => date("Y-m-d H:i:s")
                ]);
                
                // Auto login
                $_SESSION["msmbilisim_userlogin"] = 1;
                $_SESSION["msmbilisim_userid"] = $freshClient["client_id"];
                $_SESSION["msmbilisim_userpass"] = $freshClient["password"];
                $_SESSION["recaptcha"] = false;
                
                $access = json_decode($freshClient["access"], true);
                if (is_array($access) && !empty($access["admin_access"])) {
                    $_SESSION["msmbilisim_adminlogin"] = 1;
                }
                
                $currency_hash = get_currency_hash_by_code(get_default_currency());
                $_SESSION["currency_hash"] = $currency_hash;
                
                setcookie("u_id", $freshClient["client_id"], strtotime('+7 days'), '/', null, null, true);
                setcookie("u_password", $freshClient["password"], strtotime('+7 days'), '/', null, null, true);
                setcookie("u_login", 'ok', strtotime('+7 days'), '/', null, null, true);
                setcookie("currency_hash", $currency_hash, strtotime('+7 days'), '/', null, null, true);
                
                // Update login info
                $updateLogin = $conn->prepare("UPDATE clients SET login_date=:date, login_ip=:ip WHERE client_id=:c_id");
                $updateLogin->execute([
                    "c_id" => $clientId,
                    "date" => date("Y.m.d H:i:s"),
                    "ip"   => GetIP()
                ]);
                
                // Cleanup session
                unset($_SESSION["otp_verify_client_id"]);
                unset($_SESSION["otp_verify_email"]);
                unset($_SESSION["otp_resend_cooldown"]);
                
                Header("Location:" . site_url(''));
                exit();
            }
        }
    }
}

// ─── CALCULATE REMAINING TIME FOR TEMPLATE ───
$otpRemainingSeconds = 0;
if ($otpClient["otp_expiry"]) {
    $otpRemainingSeconds = max(0, strtotime($otpClient["otp_expiry"]) - time());
}

$resendCooldownRemaining = 0;
if (isset($_SESSION["otp_resend_cooldown"])) {
    $elapsed = time() - $_SESSION["otp_resend_cooldown"];
    if ($elapsed < $otpResendCooldown) {
        $resendCooldownRemaining = $otpResendCooldown - $elapsed;
    }
}

$attemptsRemaining = max(0, $otpMaxAttempts - ($otpClient["otp_attempts"] ?? 0));

// Set template directory for twgofficial.php
$templateDir = "verify_otp";
