<?php

namespace App\Services\Payments;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Shetabit\Multipay\Invoice;
use Shetabit\Multipay\Payment;

class PaymentService
{
    public function createPending(int $userId, string $planKey): array
    {
        $plan = DB::table('plans')->where('key', $planKey)->first();
        if (!$plan) {
            throw new \InvalidArgumentException('invalid_plan');
        }
        $amount = (int)($plan->amount_irr ?? 0);

        // Create DB row first (pending)
        $authority = 'AUTH-' . uniqid();
        $pid = DB::table('payments')->insertGetId([
            'user_id' => $userId,
            'plan_id' => $plan->id,
            'gateway' => 'zarinpal',
            'amount' => $amount,
            'status' => 'pending',
            'ref' => $authority,
            'payload_json' => json_encode(['authority' => $authority]),
            'created_at' => now(), 'updated_at' => now(),
        ]);

        // Try to initialize Shetabit (sandbox)
        try {
            $invoice = (new Invoice())->amount($amount);
            $callback = config('payments.callback_url');
            // Note: different drivers have different assumptions; keep via('zarinpal')
            $payment = app(Payment::class)
                ->via('zarinpal')
                ->callbackUrl($callback)
                ->purchase($invoice, function ($driver, $transactionId) use (&$authority, $pid) {
                    $authority = $transactionId ?: $authority;
                    DB::table('payments')->where('id', $pid)->update(['ref' => $authority, 'updated_at' => now()]);
                });
            $pay = $payment->pay();
            $redirectUrl = method_exists($pay, 'getTargetUrl') ? $pay->getTargetUrl() : (string) $pay;
        } catch (\Throwable $e) {
            Log::warning('Payment init failed, using sandbox redirect', ['e' => $e->getMessage()]);
            $redirectUrl = 'https://sandbox.zarinpal.com/pg/StartPay/' . $authority;
        }

        return [
            'payment_id' => $pid,
            'gateway' => 'zarinpal',
            'redirect_url' => $redirectUrl,
            'authority' => $authority,
            'plan' => $planKey,
            'amount' => $amount,
        ];
    }

    public function verify(string $authority, ?int $amount = null): array
    {
        // Attempt shetabit verification; fallback to success if Status=OK handled externally
        try {
            $invoice = (new Invoice());
            if ($amount) { $invoice->amount($amount); }
            $receipt = app(Payment::class)
                ->via('zarinpal')
                ->transactionId($authority)
                ->amount($amount ?? 0)
                ->verify();
            return ['ok' => true, 'ref_id' => (string)$receipt->getReferenceId()];
        } catch (\Throwable $e) {
            Log::warning('Payment verify failed', ['e' => $e->getMessage(), 'authority' => $authority]);
            return ['ok' => false, 'error' => $e->getMessage()];
        }
    }
}
