<?php
// Scratch script to test delete protection for accounts in use

$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 PHP_EOL . "2. Creating a temporary account..." . PHP_EOL;
$createRes = apiCall('POST', $baseUrl . '/accounts', [
    'name' => 'Temp Protective Account',
    'type' => 'bank_cash',
    'sub_type' => 'bank',
    'opening_balance' => 0,
    'balance_type' => 'Dr'
], $token);
$accountId = $createRes['data']['id'];
echo "Created Account ID: {$accountId}" . PHP_EOL;

echo PHP_EOL . "3. Verification: Deleting it BEFORE transactions (Should succeed)..." . PHP_EOL;
$delRes1 = apiCall('DELETE', $baseUrl . "/accounts/{$accountId}", null, $token);
echo "API Message: " . $delRes1['message'] . PHP_EOL;

// Re-activate it for the next phase of the test by updating is_active = 1
echo "Re-activating account..." . PHP_EOL;
apiCall('PUT', $baseUrl . "/accounts/{$accountId}", ['is_active' => 1], $token);

echo PHP_EOL . "4. Posting a transaction (Direct Deposit) to the account..." . PHP_EOL;
$depositRes = apiCall('POST', $baseUrl . '/cash-bank', [
    'date' => date('Y-m-d'),
    'type' => 'direct_deposit',
    'amount' => 5000,
    'account_id' => $accountId,
    'narration' => 'Temporary test transaction'
], $token);
$voucherId = $depositRes['data']['id'];
echo "Voucher Created ID: {$voucherId}" . PHP_EOL;

echo PHP_EOL . "5. Verification: Trying to delete it AFTER transactions (Should FAIL)..." . PHP_EOL;
$ch = curl_init($baseUrl . "/accounts/{$accountId}");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $token
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$decoded = json_decode($response, true);
echo "HTTP Status Code: {$httpCode}" . PHP_EOL;
echo "API Error Message: " . ($decoded['message'] ?? $response) . PHP_EOL;

if ($httpCode === 400 && strpos($decoded['message'], 'استعمال ہو چکا ہے') !== false) {
    echo "SUCCESS: Deletion was successfully blocked as expected!" . PHP_EOL;
} else {
    echo "ERROR: Deletion was not blocked or returned unexpected status/message." . PHP_EOL;
    exit(1);
}

echo PHP_EOL . "6. Clean up: Reversing the test transaction..." . PHP_EOL;
apiCall('POST', $baseUrl . "/cash-bank/{$voucherId}/reverse", null, $token);
echo "Cleanup completed successfully." . PHP_EOL;

echo PHP_EOL . "=== ALL PROTECTION 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;
}
