<?php
session_start();
header("Content-Type: application/json");

require_once "../SystemController/DbConnection.php";
require '../SystemController/CsrfProtection.php';

if(!isset($_SESSION['id']) && !isset($_SESSION['loggedid'])){
    header("Location: ../login.php");
}


$db_handle = new Dbconnection();

$date = date("d-m-Y h:i:s");

$csrf = new CsrfProtection();   
$new_token = $csrf->generateToken();


if ($_SERVER["REQUEST_METHOD"] === "POST") {
    
    if (!isset($_POST['csrf_token']) || !$csrf->validateToken($_POST['csrf_token'])) {
        die("CSRF token validation failed!");
    }
    $amount   = $db_handle->sanitize($_POST["amount"]) ?? 0;
    $acc_no = $db_handle->sanitize($_POST["acc_no"]) ?? "";
    $acc_name = $db_handle->sanitize($_POST["acc_name"]) ?? "";
    $bank = $db_handle->sanitize($_POST["bank"]) ?? "";
    
    $user_id = $db_handle->sanitize($_POST["id"]);
    
    $user = $db_handle->runBaseQuery("SELECT * FROM users WHERE id = $user_id");
    
    $acc_balance = $user[0]['balance'];
    
   $pending_withdrawal = $db_handle->runBaseQuery("SELECT * FROM withdrawals WHERE userID = '$user_id' and status = 0");
    
    if(!$pending_withdrawal){
        
        if($amount < $acc_balance){
    
    
    $acc_balance -= $amount;
    
    $insert = $db_handle->insertRecord("INSERT INTO withdrawals(userID,bank,acc_no,acc_name,amount,date) VALUES (?,?,?,?,?,?)","isssis",array($user_id,$bank,$acc_no,$acc_name,$amount,$date));
    
    if($insert){
        
        $update = $db_handle->update("UPDATE users SET balance = ? WHERE id = ?","si",array($acc_balance,$user_id));
        

    echo json_encode([
        "status" => "success",
        "token" => $new_token,
        "message" => "Withdrawal request submitted successfully!"
    ]);
    exit;
}

}else{
    echo json_encode([
        "status" => "error",
        "token" => $new_token,
        "message" => "Insufficient Funds"
    ]);
    exit;
}
}else{
    echo json_encode([
        "status" => "error",
        "token" => $new_token,
        "message" => "Sorry, withdrawal request cannot be processed because you currenly have a pending  withdrawal"
    ]);
    exit;
    
}

}

