<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/include/config.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/include/Function/sql.php");

$conn    = dbConnect();
$message = new USER();

$viesConn = "SELECT * FROM users WHERE acct_no=:acct_no";
$stmt = $conn->prepare($viesConn);
$stmt->execute([':acct_no' => $_SESSION['acct_no']]);
$row     = $stmt->fetch(PDO::FETCH_ASSOC);
$user_id = $row['id'];

$sql  = "SELECT * FROM settings WHERE id='1'";
$stmt = $conn->prepare($sql);
$stmt->execute();
$page = $stmt->fetch(PDO::FETCH_ASSOC);

$WireLimit     = $page['wirelimit'];
$TransferLimit = 50;

// ─── Form submit from wire-transfer.php ───────────────────────────────────────
if (isset($_POST['wire-transfer'])) {

    $amount         = $_POST['amount'];
    $WireFee        = $_POST['fee'];
    $account_name   = $_POST['account_name'];
    $bank_name      = $_POST['bank_name'];
    $account_number = $_POST['account_number'];
    $account_type   = $_POST['account_type'];
    $bank_country   = $_POST['bank_country'];
    $routine_number = $_POST['routine_number'] ?? '';
    $swift_code     = $_POST['swift_code']     ?? '';

    $checkFee = ($amount + $WireFee);

    if ($checkFee > $row['acct_balance']) {
        toast_alert('error', 'Insufficient Balance');
    } elseif ($row['acct_status'] == 'hold') {
        toast_alert('error', 'Account on Hold. Contact Support');
    } elseif ($amount > $WireLimit) {
        toast_alert('error', 'Transfer Limit Exceeded!');
    } elseif ($amount < $TransferLimit) {
        toast_alert('error', 'Amount Too Low!');
    } else {

        // ─── Billing code ON → redirect to COT/IMF/Tax before saving ─────────
        if ($page['billing_code'] == '1') {

            // Store transfer data in session so it can be saved after codes are completed
            $_SESSION['wire_transfer_data'] = [
                'amount'         => $amount,
                'fee'            => $WireFee,
                'account_name'   => $account_name,
                'bank_name'      => $bank_name,
                'account_number' => $account_number,
                'account_type'   => $account_type,
                'bank_country'   => $bank_country,
                'routine_number' => $routine_number,
                'swift_code'     => $swift_code
            ];

            $_SESSION['wire-transfer']    = $user_id;
            $_SESSION['is_wire_code']     = "None";
            $_SESSION['is_wire_transfer'] = "Wire";
            $_SESSION['is_transfer']      = "None";

            // Redirect to the first enabled code page
            if ($page['cot_code'] == '1') {
                header("Location:./cot.php");
                exit;
            }

            if ($page['imf_code'] == '1') {
                header("Location:./imf.php");
                exit;
            }

            if ($page['tax_code'] == '1') {
                header("Location:./tax.php");
                exit;
            }
        }

        // ─── Billing code OFF or no codes enabled → save and go to OTP/pin ───

       // ─── Billing code OFF or no codes enabled → save and go to OTP/pin ───

        // Save to temp_trans
        $refrence_id      = uniqid();
        $trans_type       = "Wire transfer";
        $transaction_type = "debit";
        $trans_status     = "pending";

        date_default_timezone_set('America/New_York');
        $created_at = date('Y-m-d H:i:s');

        $sql = "INSERT INTO temp_trans 
                    (amount, refrence_id, user_id, bank_name, account_name, account_number, account_type, bank_country, trans_type, transaction_type, trans_status, routine_number, swift_code, created_at) 
                VALUES 
                    (:amount, :refrence_id, :user_id, :bank_name, :account_name, :account_number, :account_type, :bank_country, :trans_type, :transaction_type, :trans_status, :routine_number, :swift_code, :created_at)";
        $tranfered = $conn->prepare($sql);
        $tranfered->execute([
            'amount'           => $amount,
            'refrence_id'      => $refrence_id,
            'user_id'          => $user_id,
            'bank_name'        => $bank_name,
            'account_name'     => $account_name,
            'account_number'   => $account_number,
            'account_type'     => $account_type,
            'bank_country'     => $bank_country,
            'trans_type'       => $trans_type,
            'transaction_type' => $transaction_type,
            'trans_status'     => $trans_status,
            'routine_number'   => $routine_number,
            'swift_code'       => $swift_code,
            'created_at'       => $created_at
        ]);

        // Force-update created_at after insert to override MySQL DEFAULT CURRENT_TIMESTAMP
        $lastId = $conn->lastInsertId();
        $conn->prepare("UPDATE temp_trans SET created_at = :val WHERE trans_id = :tid")
             ->execute(['val' => $created_at, 'tid' => $lastId]);

        // Send OTP
        $acct_otp = substr(number_format(time() * rand(), 0, '', ''), 0, 4);

        $sql = "UPDATE users SET acct_otp=:acct_otp WHERE id=:id";
        $stmt = $conn->prepare($sql);
        $stmt->execute(['acct_otp' => $acct_otp, 'id' => $user_id]);

        $sql = "SELECT * FROM users WHERE id=:id";
        $stmt = $conn->prepare($sql);
        $stmt->execute(['id' => $user_id]);
        $resultCode = $stmt->fetch(PDO::FETCH_ASSOC);
        $acct_otp   = $resultCode['acct_otp'];
        $number     = $resultCode['acct_phone'];

        if ($page['twillio_status'] == '1') {
            $APP_NAME    = WEB_TITLE;
            $messageText = "Dear " . $resultCode['firstname'] . " You just made a Transaction of " . $amount . " in Your " . $APP_NAME . " Account. Kindly use this code " . $acct_otp . " to complete your Transaction. Thanks";
            $sendSms->sendSmsCode($number, $messageText);
        }

        $full_name    = $resultCode['firstname'] . " " . $resultCode['lastname'];
        $APP_NAME     = WEB_TITLE;
        $APP_URL      = WEB_URL;
        $SITE_ADDRESS = $page['url_address'];
        $email        = $resultCode['acct_email'];

        $emailBody = $sendMail->pinRequest($full_name, $acct_otp, $APP_NAME, $APP_URL, $SITE_ADDRESS);
        $subject   = "One-Time Code - $APP_NAME";
        $email_message->send_mail($email, $emailBody, $subject);

        $_SESSION['wire-transfer']    = $user_id;
        $_SESSION['is_wire_transfer'] = "wire";
        $_SESSION['is__transfer']     = "None";
        $_SESSION['is_transfer']      = "transfer";
        $_SESSION['is_tax_code']      = "None";

        header("Location:./wire-pin.php");
        exit;
    }
}