<?php

session_start();
require '../includes/db.php';

header('Content-Type: application/json');

/*
|--------------------------------------------------------------------------
| AUTH CHECK
|--------------------------------------------------------------------------
*/
if (!isset($_SESSION['user_id'])) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Session expired'
    ]);
    exit;
}

$user_id = $_SESSION['user_id'];

/*
|--------------------------------------------------------------------------
| GET USER
|--------------------------------------------------------------------------
*/
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    echo json_encode([
        'status' => 'error',
        'message' => 'User not found'
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| INPUT DATA
|--------------------------------------------------------------------------
*/
$transfer_type     = $_POST['transfer_type'] ?? 'domestic';
$beneficiary_name  = $_POST['recipient_name'] ?? '';
$bank_name         = $_POST['bank_name'] ?? '';
$account_number    = $_POST['account_number'] ?? '';
$routing_number    = $_POST['routing_number'] ?? '';
$swift_code        = $_POST['swift_code'] ?? '';
$amount            = (float)($_POST['amount'] ?? 0);
$purpose           = $_POST['purpose'] ?? '';

/*
|--------------------------------------------------------------------------
| VALIDATION
|--------------------------------------------------------------------------
*/
if ($amount <= 0) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid amount'
    ]);
    exit;
}

if ($user['checking_balance'] < $amount) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Insufficient balance'
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| PREVENT DUPLICATE PENDING TRANSFERS
|--------------------------------------------------------------------------
*/
$stmt = $pdo->prepare("
    SELECT COUNT(*) 
    FROM transfers 
    WHERE user_id = ? AND status = 'pending'
");
$stmt->execute([$user_id]);

if ($stmt->fetchColumn() > 0) {
    echo json_encode([
        'status' => 'error',
        'message' => 'You already have a pending transfer. Please wait for approval.'
    ]);
    exit;
}

/*
|--------------------------------------------------------------------------
| PROCESS TRANSFER
|--------------------------------------------------------------------------
*/
try {

    $pdo->beginTransaction();

    // Deduct from checking balance
    $stmt = $pdo->prepare("
        UPDATE users 
        SET checking_balance = checking_balance - ? 
        WHERE id = ?
    ");
    $stmt->execute([$amount, $user_id]);

    // Insert transfer request
    $stmt = $pdo->prepare("
        INSERT INTO transfers
        (
            user_id,
            transfer_type,
            beneficiary_name,
            beneficiary_bank,
            account_number,
            routing_number,
            swift_code,
            amount,
            note,
            status,
            created_at
        )
        VALUES
        (?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
    ");

    $stmt->execute([
        $user_id,
        $transfer_type,
        $beneficiary_name,
        $bank_name,
        $account_number,
        $routing_number,
        $swift_code,
        $amount,
        $purpose
    ]);

    $transfer_id = $pdo->lastInsertId();

    $pdo->commit();

    echo json_encode([
        'status' => 'success',
        'message' => "Transfer request submitted successfully (#$transfer_id)"
    ]);

} catch (Exception $e) {

    $pdo->rollBack();

    echo json_encode([
        'status' => 'error',
        'message' => 'Transfer failed. Please try again.'
    ]);
}