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

$user = $_SESSION['chap'] ?? null; // safer

// Check if accountnumber is sent
if (empty($_POST['accountnumber'])) {
    echo "error";
    exit;
}

$accountnumber = $_POST['accountnumber'];

// Use prepared statement to prevent SQL injection
$stmt = $con->prepare("SELECT * FROM users WHERE account_num = ?");
$stmt->bind_param("s", $accountnumber);
$stmt->execute();
$result = $stmt->get_result();

if ($result && $result->num_rows > 0) {
    // User exists
    echo "complete";
} else {
    // Fetch user details securely by email
    if ($user) {
        $stmt2 = $con->prepare("SELECT code_status FROM users WHERE email = ?");
        $stmt2->bind_param("s", $user);
        $stmt2->execute();
        $res2 = $stmt2->get_result();

        if ($res2 && $row = $res2->fetch_assoc()) {
            if ($row['code_status'] === "debit_success") {
                echo "debit_success";
            } else {
                echo "code";
            }
        } else {
            echo "error_user_not_found";
        }
        $stmt2->close();
    } else {
        echo "error_no_user";
    }
}

$stmt->close();
$con->close();
?>
