<?php
// Scratch script to test direct deposit API

$baseUrl = 'http://localhost/projects/naveed_trader/api';

echo "1. Logging in as admin..." . PHP_EOL;
$loginResponse = apiCall('POST', $baseUrl . '/auth/login', [
    'username' => 'admin',
    'password' => 'admin123'
]);
$token = $loginResponse['data']['token'];
echo "Logged in successfully. User: " . $loginResponse['data']['user']['full_name'] . PHP_EOL;

echo PHP_EOL . "2. Finding a Bank/Cash Account to deposit to..." . PHP_EOL;
$accounts = apiCall('GET', $baseUrl . '/accounts?type=bank_cash', null, $token);
$bankAccount = null;
foreach ($accounts['data'] as $acc) {
    // Look for any bank account
    if ($acc['sub_type'] === 'bank' || $acc['sub_type'] === 'cash') {
        $bankAccount = $acc;
        break;
    }
}

if (!$bankAccount) {
    echo "ERROR: No bank or cash account found." . PHP_EOL;
    exit(1);
}
echo "Selected Account: {$bankAccount['name']} (ID: {$bankAccount['id']}, Type: {$bankAccount['sub_type']})" . PHP_EOL;

// Get current balance
$balanceRes = apiCall('GET', $baseUrl . "/ledger/{$bankAccount['id']}/balance", null, $token);
$oldBalance = floatval($balanceRes['data']['balance']);
echo "Current Balance: {$oldBalance} PKR" . PHP_EOL;

echo PHP_EOL . "3. Posting a Direct Deposit of 25,000 PKR..." . PHP_EOL;
$depositPayload = [
    'date' => date('Y-m-d'),
    'type' => 'direct_deposit',
    'amount' => 25000,
    'account_id' => $bankAccount['id'],
    'narration' => 'Test direct deposit from scratch script'
];

$depositRes = apiCall('POST', $baseUrl . '/cash-bank', $depositPayload, $token);
echo "API Message: " . $depositRes['message'] . PHP_EOL;
$voucherId = $depositRes['data']['id'];
echo "Voucher ID Created: {$voucherId}" . PHP_EOL;

// Get new balance
$balanceRes2 = apiCall('GET', $baseUrl . "/ledger/{$bankAccount['id']}/balance", null, $token);
$newBalance = floatval($balanceRes2['data']['balance']);
echo "New Balance: {$newBalance} PKR" . PHP_EOL;

$diff = $newBalance - $oldBalance;
echo "Balance Difference: {$diff} PKR" . PHP_EOL;

if (abs($diff - 25000) < 0.01) {
    echo "SUCCESS: 25,000 PKR successfully deposited!" . PHP_EOL;
} else {
    echo "ERROR: Balance difference does not match 25,000 PKR!" . PHP_EOL;
    exit(1);
}

echo PHP_EOL . "4. Reversing the Direct Deposit to keep database clean..." . PHP_EOL;
$reverseRes = apiCall('POST', $baseUrl . "/cash-bank/{$voucherId}/reverse", null, $token);
echo "Reversal API Message: " . $reverseRes['message'] . PHP_EOL;

// Get final balance
$balanceRes3 = apiCall('GET', $baseUrl . "/ledger/{$bankAccount['id']}/balance", null, $token);
$finalBalance = floatval($balanceRes3['data']['balance']);
echo "Final Balance after reversal: {$finalBalance} PKR" . PHP_EOL;

if (abs($finalBalance - $oldBalance) < 0.01) {
    echo "SUCCESS: Reversal completed, balance restored!" . PHP_EOL;
} else {
    echo "ERROR: Reversal failed to restore original balance!" . PHP_EOL;
    exit(1);
}

echo PHP_EOL . "=== ALL DIRECT DEPOSIT API TESTS PASSED ===" . PHP_EOL;

function apiCall($method, $url, $data = null, $token = null) {
    $headers = ['Content-Type: application/json', 'Accept: application/json'];
    if ($token) $headers[] = 'Authorization: Bearer ' . $token;
    
    $opts = [
        'http' => [
            'method' => $method,
            'header' => implode("\r\n", $headers),
            'ignore_errors' => true
        ]
    ];
    if ($data) $opts['http']['content'] = json_encode($data);
    
    $result = file_get_contents($url, false, stream_context_create($opts));
    $decoded = json_decode($result, true);
    
    if (!$decoded || !$decoded['success']) {
        echo "ERROR: " . ($decoded['message'] ?? $result) . PHP_EOL;
        exit(1);
    }
    return $decoded;
}
