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

// Validate if session and POST variables are set
if (isset($_SESSION['chap'], $_POST['pin'], $_POST['code'])) {
    $pin = mysqli_real_escape_string($mysqli, $_POST['pin']);
    $code = mysqli_real_escape_string($mysqli, $_POST['code']);
    $email = $_SESSION['chap'];

    // Fetch user details based on email
    $newnew = mysqli_query($mysqli, "SELECT * FROM users WHERE email = '$email'");
    if (!$newnew) {
        echo "Error fetching user details: " . mysqli_error($mysqli);
        exit();
    }

    if (mysqli_num_rows($newnew) > 0) {
        $roll = mysqli_fetch_assoc($newnew);
        $user = $roll['account_num'];
        $balance = $roll['checking_balance'];
        $transfer_ref = $roll['transfer_ref'];
        $code_count = isset($roll['code_count']) ? (int)$roll['code_count'] : 6;
        // Clamp to valid range
        $code_count = max(1, min(6, $code_count));

        // Fetch transfer details based on transfer_ref
        $sql387 = mysqli_query($mysqli, "SELECT * FROM transfers WHERE transfer_ref = '$transfer_ref'");
        if (!$sql387) {
            echo "Error fetching transfer details: " . mysqli_error($mysqli);
            exit();
        }

        if (mysqli_num_rows($sql387) > 0) {
            $row33 = mysqli_fetch_assoc($sql387);
            $amount = $row33['amount'];
            $new_bal = $balance - $amount;

            // Map provided code number to code column
            $codeColumn = "";
            $codeNum = (int)$code;
            if ($codeNum >= 1 && $codeNum <= 6) {
                $codeColumn = "code" . $codeNum;
            } else {
                echo "Invalid code level";
                exit();
            }

            // Fetch the code from the code table
            $sqlnew = mysqli_query($mysqli, "SELECT $codeColumn FROM code WHERE user = '$user'");
            if (!$sqlnew) {
                echo "Error fetching code details: " . mysqli_error($mysqli);
                exit();
            }

            if (mysqli_num_rows($sqlnew) > 0) {
                $row = mysqli_fetch_assoc($sqlnew);
                $retrievedCode = $row[$codeColumn];

                if ($retrievedCode == $pin) {
                    // Determine next code level: check if this was the last code
                    if ($codeNum >= $code_count) {
                        $nextLevel = "nothing";
                    } else {
                        $nextLevel = "code" . ($codeNum + 1);
                    }

                    // Update code level for the user
                    $updateCodeLevel = mysqli_query($mysqli, "UPDATE users SET code_level = '$nextLevel' WHERE email = '$email'");
                    if (!$updateCodeLevel) {
                        echo "Error updating code level: " . mysqli_error($mysqli);
                        exit();
                    }

                    // If this was the last code (code_count reached), complete the transaction
                    if ($codeNum >= $code_count) {
                        // Final step: update transactions and user balance
                        $updatetrans = mysqli_query($mysqli, "UPDATE transactions SET status = 'Completed' WHERE trans_id = '$transfer_ref'");
                        if (!$updatetrans) {
                            echo "Error updating transaction status: " . mysqli_error($mysqli);
                            exit();
                        }

                        $sqlselect = mysqli_query($mysqli, "SELECT account FROM transactions WHERE trans_id = '$transfer_ref'");
                        $rowed = mysqli_fetch_assoc($sqlselect);
                        $fieldbalance = $rowed['account'];

                        $updatebalance = mysqli_query($mysqli, "UPDATE users SET $fieldbalance = '$new_bal', transfer_status='active' WHERE email = '$email'");
                        if (!$updatebalance) {
                            echo "Error updating user balance: " . mysqli_error($mysqli);
                            exit();
                        }

                        // Send transfer confirmation email (does not block on failure)
                        include_once __DIR__ . "/../../includes/email_helper.php";
                        sendTransferConfirmation($mysqli, $email, $transfer_ref);
                    }

                    echo "success";
                } else {
                    echo "Incorrect PIN";
                }
            } else {
                echo "Code not found";
            }
        } else {
            echo "Transfer not found";
        }
    } else {
        echo "User not found";
    }
} else {
    echo "Invalid request";
}
?>
