<?php
declare(strict_types=1);
if ( ! defined( 'ACC_BASE_PATH' ) ) {
    define( 'ACC_BASE_PATH', __DIR__ );
    require __DIR__ . '/standalone/bootstrap.php';
}
$base = 'http://localhost/acc-engine/api.php/acc/v1';
$code = $argv[1] ?? '1-14-4-81-0-0-0';

$ch = curl_init( "$base/public/auth/login" );
curl_setopt_array( $ch, [
    CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [ 'Content-Type: application/json' ],
    CURLOPT_POSTFIELDS => json_encode( [ 'username' => 'melk_sysadmin', 'password' => 'Melk@1404' ] ),
] );
$auth = json_decode( (string) curl_exec( $ch ), true );
curl_close( $ch );
$token = $auth['token'] ?? '';

$hub = json_decode( (string) curl_exec( curl_init( "$base/melk/renovation-hub?code=" . urlencode( $code ) ) ?: '' ), true );
// fix curl for hub
$ch = curl_init( "$base/melk/renovation-hub?code=" . urlencode( $code ) );
curl_setopt_array( $ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Authorization: Bearer $token" ] ] );
$hub = json_decode( (string) curl_exec( $ch ), true );
curl_close( $ch );

$pid = $hub['data']['gis']['parcel_id'] ?? 0;
$parcel = null;
if ( $pid ) {
    $ch = curl_init( "$base/gis/parcels/$pid" );
    curl_setopt_array( $ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Authorization: Bearer $token" ] ] );
    $parcel = json_decode( (string) curl_exec( $ch ), true );
    curl_close( $ch );
}

echo json_encode( [
    'code' => $code,
    'hub_gis' => $hub['data']['gis'] ?? null,
    'parcel_id' => $pid,
    'parcel_keys' => $parcel ? array_keys( $parcel['data'] ?? [] ) : null,
    'has_land' => ! empty( $parcel['data']['land'] ),
    'has_building' => ! empty( $parcel['data']['building'] ),
    'has_score' => isset( $parcel['data']['score'] ),
    'owners_count' => count( $parcel['data']['owners'] ?? [] ),
    'issues_count' => count( $parcel['data']['issues'] ?? [] ),
], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
