<?php
/**
 * تست سریع API پاداش
 * php run-service-reward-test.php
 */
declare(strict_types=1);

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

function api_post( string $url, array $body, array $headers = [] ): array {
    $ch = curl_init( $url );
    curl_setopt_array( $ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => array_merge( [ 'Content-Type: application/json' ], $headers ),
        CURLOPT_POSTFIELDS => json_encode( $body, JSON_UNESCAPED_UNICODE ),
    ] );
    $raw = curl_exec( $ch );
    curl_close( $ch );
    return json_decode( (string) $raw, true ) ?: [ 'error' => $raw ];
}

$results = [];

$cust = api_post( "$base/service/rewards/customer/login", [
    'phone' => '09121234567', 'name' => 'علی رضایی',
] );
$results['customer_login'] = [
    'ok' => ! empty( $cust['success'] ),
    'account_id' => $cust['account_id'] ?? null,
    'points' => $cust['data']['account']['points_available'] ?? null,
];

$session = $cust['session'] ?? '';
$me = api_post( "$base/service/rewards/me", [], [ "X-Reward-Session: $session" ] );
// GET for me - fix to use curl GET
$ch = curl_init( "$base/service/rewards/me" );
curl_setopt_array( $ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [ "X-Reward-Session: $session" ],
] );
$me = json_decode( (string) curl_exec( $ch ), true );
curl_close( $ch );
$results['customer_me'] = [ 'ok' => ! empty( $me['data'] ), 'tier' => $me['data']['tier_label'] ?? null ];

$auth = api_post( "$base/public/auth/login", [
    'username' => 'svc_tech1_demo', 'password' => 'Demo@2026',
] );
$token = $auth['token'] ?? '';
$ch = curl_init( "$base/service/rewards/staff/login" );
curl_setopt_array( $ch, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', "Authorization: Bearer $token" ],
    CURLOPT_POSTFIELDS => json_encode( [ 'actor_type' => 'technician' ] ),
] );
$staff = json_decode( (string) curl_exec( $ch ), true );
curl_close( $ch );
$results['technician_login'] = [
    'ok' => ! empty( $staff['success'] ),
    'points' => $staff['data']['account']['points_available'] ?? null,
    'tier' => $staff['data']['tier_label'] ?? null,
    'auth_error' => $auth['message'] ?? null,
    'staff_error' => $staff['message'] ?? ( $staff['code'] ?? null ),
];

$ch = curl_init( "$base/service/rewards/leaderboard?actor_type=technician" );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$lb = json_decode( (string) curl_exec( $ch ), true );
curl_close( $ch );
$results['leaderboard'] = [ 'ok' => is_array( $lb['data'] ?? null ), 'count' => count( $lb['data'] ?? [] ) ];

echo json_encode( $results, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
