<?php
/**
 * تست API گراف هزینه ملک با لاگین
 * C:\xampp\php\php.exe run-melk-abc-api-check.php
 */
declare(strict_types=1);

define('ACC_BASE_PATH', __DIR__);
require __DIR__ . '/standalone/bootstrap.php';

header('Content-Type: application/json; charset=utf-8');

$api = 'http://localhost/acc-engine/api.php/acc/v1';

function http_json(string $method, string $url, ?array $body = null, string $token = ''): array {
    $ch = curl_init($url);
    $headers = ['Content-Type: application/json', 'Accept: application/json'];
    if ($token) $headers[] = 'Authorization: Bearer ' . $token;
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_TIMEOUT => 30,
    ]);
    if ($body !== null) curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body, JSON_UNESCAPED_UNICODE));
    $raw = curl_exec($ch);
    $code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ['code' => $code, 'json' => json_decode((string) $raw, true) ?: [], 'raw' => $raw];
}

$login = http_json('POST', "$api/public/auth/login", [
    'username' => 'ostadowner',
    'password' => 'Melk1234',
]);

$token = $login['json']['token'] ?? '';
if (!$token) {
    echo json_encode(['ok' => false, 'step' => 'login', 'login' => $login], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    exit(1);
}

$graph = http_json('GET', "$api/melk/acct/cost-graph", null, $token);
$acts  = http_json('GET', "$api/melk/acct/activities", null, $token);

$pid = (int) (($graph['json']['data']['projects'][0]['project_id'] ?? 0));
$detail = $pid
    ? http_json('GET', "$api/melk/acct/activity-cost/$pid", null, $token)
    : ['code' => 0, 'json' => null];

echo json_encode([
    'ok' => ($graph['code'] === 200 && !empty($graph['json']['success'])),
    'login' => 'ok',
    'activities' => count($acts['json']['data'] ?? []),
    'graph_http' => $graph['code'],
    'nodes' => count($graph['json']['data']['nodes'] ?? []),
    'edges' => count($graph['json']['data']['edges'] ?? []),
    'projects' => count($graph['json']['data']['projects'] ?? []),
    'sample_project' => $pid,
    'detail_lines' => count($detail['json']['data']['lines'] ?? []),
    'ui' => 'http://localhost/acc-engine/melk.php',
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
