<?php

namespace App\Http\Controllers;

use App\Services\Payment\ZarinpalService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PaymentCallbackController extends Controller
{
    private ZarinpalService $zarinpalService;

    public function __construct(ZarinpalService $zarinpalService)
    {
        $this->zarinpalService = $zarinpalService;
    }

    /**
     * Handle payment callback from Zarinpal
     */
    public function callback(Request $request, string $trackingCode)
    {
        $authority = $request->get('Authority');
        $status = $request->get('Status');

        Log::info('Payment callback received', [
            'tracking_code' => $trackingCode,
            'authority' => $authority,
            'status' => $status,
            'request_data' => $request->all(),
        ]);

        // If payment was cancelled by user
        if ($status !== 'OK') {
            $this->zarinpalService->cancelPayment($trackingCode);
            
            return view('payment.result', [
                'success' => false,
                'message' => 'پرداخت توسط کاربر لغو شد.',
                'tracking_code' => $trackingCode,
            ]);
        }

        // Verify the payment
        $result = $this->zarinpalService->verifyPayment($authority, $trackingCode);

        return view('payment.result', [
            'success' => $result['success'],
            'message' => $result['message'],
            'payment' => $result['payment'],
            'reference_id' => $result['reference_id'] ?? null,
            'tracking_code' => $trackingCode,
        ]);
    }

    /**
     * Handle payment status check
     */
    public function status(string $trackingCode)
    {
        $payment = $this->zarinpalService->getPaymentStatus($trackingCode);

        if (!$payment) {
            return response()->json([
                'success' => false,
                'message' => 'تراکنش یافت نشد',
            ], 404);
        }

        return response()->json([
            'success' => true,
            'payment' => [
                'tracking_code' => $payment->tracking_code,
                'amount' => $payment->amount,
                'status' => $payment->status,
                'status_label' => $payment->status_label,
                'gateway' => $payment->gateway,
                'gateway_label' => $payment->gateway_label,
                'created_at' => $payment->created_at->toISOString(),
                'reference_id' => $payment->reference_id,
            ],
        ]);
    }
}