<?php

declare(strict_types=1);

/**
 * End-to-end Karvi Partner API live check (run after login credentials work).
 */
if (session_status() === PHP_SESSION_NONE) {
    @session_start();
}

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/mvc.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/api_service.php';

$email = trim((string)($argv[1] ?? 'admin'));
$password = (string)($argv[2] ?? '123456');

echo "=== Karvi Live API Check ===\n\n";

$loginResponse = \App\Services\ApiService::instance()->login($email, $password);
$loginOk = !empty($loginResponse['success']) && !empty($loginResponse['data']['token']);
echo '[login] ' . ($loginOk ? 'OK' : 'FAIL') . ' — ' . ($loginResponse['message'] ?? '') . "\n";
if (!$loginOk || !is_array($loginResponse['data'])) {
    exit(1);
}

$tokenData = $loginResponse['data'];
auth_store_api_session($tokenData);

$api = \App\Services\ApiService::instance();

// 1. List contracts
try {
    $list = api_fetch_partner_contracts('partner');
    echo '[GET /karvipartner/contracts?type=partner] OK — count=' . count($list) . "\n";
} catch (Throwable $e) {
    echo '[GET /karvipartner/contracts] FAIL — ' . $e->getMessage() . "\n";
}

// 2. Create minimal partner contract
$testToken = bin2hex(random_bytes(16));
$createPayload = api_build_partner_create_payload([
    'token' => $testToken,
    'type' => 'partner',
    'restaurant_name' => 'API Live Test ' . date('H:i:s'),
    'brand' => 'Gulab',
    'owner_name' => 'Test Owner',
    'company_phone' => '+49123456789',
    'street' => 'Test St 1',
    'postal_city' => '12345 Berlin',
    'email' => 'test@example.com',
    'status' => 'pending',
    'created_at' => date('Y-m-d H:i:s'),
]);

try {
    $created = api_create_partner_contract(array_merge($createPayload, ['token' => $testToken]));
    $id = (int)($created['id'] ?? 0);
    $signToken = (string)($created['sign_token'] ?? $created['token'] ?? '');
    echo '[POST /karvipartner/contracts] OK — id=' . $id . ' sign_token=' . substr($signToken, 0, 12) . "...\n";

    if ($id > 0) {
        $getResult = contract_service()->getContract($id);
        if ($getResult->success) {
            echo '[GET /karvipartner/contracts/{id}] OK — restaurant=' . ($getResult->contract['restaurant_name'] ?? '') . "\n";
        } else {
            echo '[GET /karvipartner/contracts/{id}] FAIL — ' . $getResult->message . "\n";
        }

        $existing = ($getResult->success && is_array($getResult->contract)) ? $getResult->contract : [];
        $editPayload = contract_service()->buildEditPayloadFromExisting($existing, [
            'restaurant_name' => ($existing['restaurant_name'] ?? 'API Live Test') . ' (edited)',
        ]);
        $updateResult = contract_service()->updateContract($id, $editPayload);
        if ($updateResult->success) {
            echo '[PUT /karvipartner/contracts/{id}] OK — updated_at=' . $updateResult->updatedAt() . "\n";
        } else {
            echo '[PUT /karvipartner/contracts/{id}] FAIL — ' . $updateResult->message . "\n";
        }

        $sendResult = contract_service()->sendContract($id);
        if ($sendResult->success) {
            echo '[POST /karvipartner/contracts/{id}/send] OK — sign_url=' . substr($sendResult->signUrl, 0, 40) . "...\n";
        } else {
            echo '[POST /karvipartner/contracts/{id}/send] FAIL — ' . $sendResult->message . "\n";
        }
    }

    // 3. Update (pdf_viewed simulation)
    if ($id > 0 && $signToken !== '') {
        try {
            api_update_contract($signToken, ['pdf_viewed_at' => date('Y-m-d H:i:s')]);
            echo '[PUT /karvipartner/contracts/{id}] OK — pdf_viewed_at synced' . "\n";
        } catch (Throwable $e) {
            echo '[PUT /karvipartner/contracts/{id}] FAIL — ' . $e->getMessage() . "\n";
        }

        // 4. Public sign endpoint reachability (expect 404/422 without real sign data — route must exist)
        $signPath = '/karvipartner/contracts/sign/' . $signToken;
        $signProbe = $api->post($signPath, [
            'terms_accepted' => true,
            'raw_data' => ['probe' => true],
        ], false);
        $signStatus = (int)($signProbe['http_status'] ?? 0);
        $signMsg = (string)($signProbe['message'] ?? '');
        $signOk = $signStatus > 0 && $signStatus !== 404;
        echo '[POST /karvipartner/contracts/sign/{token}] ' . ($signOk ? 'REACHABLE' : 'FAIL')
            . " — HTTP {$signStatus} {$signMsg}\n";

        $publicView = contract_service()->viewPublicContract($signToken);
        if ($publicView->success) {
            echo '[GET /karvipartner/contracts/sign/{token}] OK — message=' . $publicView->message . "\n";
        } else {
            echo '[GET /karvipartner/contracts/sign/{token}] FAIL — ' . $publicView->message . "\n";
        }

        $invalidView = contract_service()->viewPublicContract('invalidtoken000000000000000000000000');
        echo '[GET /karvipartner/contracts/sign/{token} invalid] '
            . ($invalidView->success ? 'UNEXPECTED OK' : ('OK — ' . $invalidView->message)) . "\n";

        if ($id > 0) {
            $deleteResult = contract_service()->deleteContract($id);
            if ($deleteResult->success) {
                echo '[DELETE /karvipartner/contracts/{id}] OK — deleted_id=' . ($deleteResult->deletedId ?? $id)
                    . ' message=' . $deleteResult->message . "\n";
            } else {
                echo '[DELETE /karvipartner/contracts/{id}] FAIL — ' . $deleteResult->message . "\n";
            }
        }
    }
} catch (Throwable $e) {
    echo '[POST /karvipartner/contracts] FAIL — ' . $e->getMessage() . "\n";
}

echo "\nDone.\n";
