<?php
// Quick API test script
$baseUrl = 'http://localhost/projects/naveed_trader/api';

// 1. Login
echo "=== LOGIN TEST ===" . PHP_EOL;
$loginResponse = apiCall('POST', $baseUrl . '/auth/login', [
    'username' => 'admin',
    'password' => 'admin123'
]);
$token = $loginResponse['data']['token'];
echo "Token: " . substr($token, 0, 30) . "..." . PHP_EOL;
echo "User: " . $loginResponse['data']['user']['full_name'] . PHP_EOL;

// 2. Get Accounts
echo PHP_EOL . "=== ACCOUNTS TEST ===" . PHP_EOL;
$accounts = apiCall('GET', $baseUrl . '/accounts', null, $token);
echo "Total accounts: " . count($accounts['data']) . PHP_EOL;
foreach (array_slice($accounts['data'], 0, 5) as $acc) {
    echo "  - {$acc['name']} ({$acc['type']}/{$acc['sub_type']})" . PHP_EOL;
}

// 3. Get Items
echo PHP_EOL . "=== ITEMS TEST ===" . PHP_EOL;
$items = apiCall('GET', $baseUrl . '/items', null, $token);
echo "Total items: " . count($items['data']) . PHP_EOL;
foreach ($items['data'] as $item) {
    echo "  - {$item['name']}" . PHP_EOL;
}

// 4. Dashboard Stats
echo PHP_EOL. "=== DASHBOARD STATS TEST ===" . PHP_EOL;
$stats = apiCall('GET', $baseUrl . '/dashboard/stats', null, $token);
echo "Cash in Hand: " . $stats['data']['cash_in_hand'] . PHP_EOL;
echo "Inventory Lots: " . $stats['data']['inventory_lots'] . PHP_EOL;

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