<?php

use App\Application\Services\InvoiceService;
use App\Models\Merchant;
use Illuminate\Contracts\Console\Kernel;

require __DIR__.'/../../vendor/autoload.php';

$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();

$merchantEmail = $argv[1] ?? 'ahmadshahzaib2490+3@gmail.com';
$amount = $argv[2] ?? '5.00';

$merchant = Merchant::where('email', $merchantEmail)->first();

if (! $merchant) {
    fwrite(STDERR, "Merchant not found: {$merchantEmail}\n");
    exit(1);
}

$invoice = app(InvoiceService::class)->create($merchant, [
    'price_amount' => $amount,
    'price_currency' => 'USD',
    'pay_currency' => 'USDTTRC20',
    'order_id' => 'TRON-SANDBOX-'.now()->format('YmdHis'),
    'payer' => [
        'id' => 'sandbox-customer',
        'name' => 'Sandbox Customer',
        'email' => 'sandbox.customer@example.com',
    ],
    'items' => [
        [
            'sku' => 'TRON-TEST',
            'name' => 'TRON payment test',
            'quantity' => 1,
            'unit_amount' => $amount,
        ],
    ],
    'metadata' => [
        'source' => 'codex_tron_test',
        'purpose' => 'real blockchain deposit verification',
    ],
], 'sandbox', 'manual-tron-test-'.now()->timestamp);

$invoice->loadMissing(['asset', 'address']);

$decimals = $invoice->asset->decimals;
$atomic = ltrim((string) $invoice->quoted_pay_amount_atomic, '0') ?: '0';
$payAmount = strlen($atomic) <= $decimals
    ? '0.'.str_pad($atomic, $decimals, '0', STR_PAD_LEFT)
    : substr($atomic, 0, -$decimals).'.'.substr($atomic, -$decimals);
$payAmount = rtrim(rtrim($payAmount, '0'), '.');

$address = $invoice->address?->address;

echo json_encode([
    'invoice_id' => $invoice->public_id,
    'order_id' => $invoice->order_id,
    'status' => $invoice->status,
    'merchant_email' => $merchantEmail,
    'price_amount' => number_format($invoice->price_amount_minor / 100, 2, '.', ''),
    'price_currency' => $invoice->price_currency,
    'pay_currency' => $invoice->asset->code,
    'network' => $invoice->asset->network,
    'pay_amount' => $payAmount,
    'pay_address' => $address,
    'checkout_url' => rtrim(config('gateway.checkout_url'), '/').'/'.$invoice->public_id,
    'api_checkout_url' => rtrim(config('app.url'), '/').'/api/v1/checkout/'.$invoice->public_id,
    'tronscan_address_url' => $address ? 'https://tronscan.org/#/address/'.$address : null,
    'expires_at' => optional($invoice->expires_at)->utc()->toIso8601String(),
], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL;
