<?php

namespace App\Services\Payments\Gateways;

use App\Services\Payments\PaymentGatewayInterface;
use Illuminate\Support\Facades\Http;
use Exception;

class SSLCommerzGateway implements PaymentGatewayInterface
{
    protected $storeId;
    protected $storePassword;
    protected $baseUrl;
    protected $mode;

    public function __construct($config, $mode)
    {
        $this->mode = $mode;
        $credentials = ($mode === 'live') ? $config['live_credentials'] : $config['test_credentials'];
        
        $this->storeId = $credentials['store_id'] ?? '';
        $this->storePassword = $credentials['store_password'] ?? '';
        
        $this->baseUrl = ($mode === 'live') 
            ? 'https://securepay.sslcommerz.com' 
            : 'https://sandbox.sslcommerz.com';
    }

    /**
     * Initialize payment and return Gateway URL
     */
    public function pay(float $amount, string $currency, array $metadata)
    {
        if (empty($this->storeId) || empty($this->storePassword)) {
            throw new Exception("SSLCommerz credentials missing in Admin Panel.");
        }

        // Get the generated Order Number from metadata
        $orderNumber = $metadata['order_number'];

        $post_data = [
            'store_id' => $this->storeId,
            'store_passwd' => $this->storePassword,
            'total_amount' => $amount,
            'currency' => strtoupper($currency),
            'tran_id' => $orderNumber, // Crucial: We use Order Number as Transaction ID
            'success_url' => route('payment.callback', ['gateway' => 'sslcommerz', 'order' => $orderNumber]),
            'fail_url' => route('payment.callback', ['gateway' => 'sslcommerz', 'order' => $orderNumber]),
            'cancel_url' => route('home'), 
            'emi_option' => 0,
            
            // Customer Details (Required by SSLCommerz)
            'cus_name' => auth()->user()->name ?? 'Customer',
            'cus_email' => auth()->user()->email ?? 'customer@example.com',
            'cus_add1' => 'Dhaka',
            'cus_city' => 'Dhaka',
            'cus_country' => 'Bangladesh',
            'cus_phone' => '01700000000',
            'shipping_method' => 'NO'
        ];

        $response = Http::asForm()->post("{$this->baseUrl}/gwprocess/v4/api.php", $post_data);
        
        if ($response->successful() && isset($response->json()['GatewayPageURL'])) {
            return ['url' => $response->json()['GatewayPageURL']];
        }

        throw new Exception("SSLCommerz Session Creation Failed: " . $response->body());
    }

    /**
     * Verify payment and return success status + order number
     */
    public function verify(array $requestData): array
    {
        // SSLCommerz sends back the Order Number in 'tran_id'
        $orderNumber = $requestData['tran_id'] ?? ($requestData['order'] ?? null);

        // 1. Immediate check for failure
        if (isset($requestData['status']) && $requestData['status'] === 'FAILED') {
            return [
                'success' => false,
                'order_number' => $orderNumber
            ];
        }

        // 2. Validate the payment token (val_id) securely with SSLCommerz server
        $val_id = $requestData['val_id'] ?? null;

        if (!$val_id) {
            return [
                'success' => false,
                'order_number' => $orderNumber
            ];
        }

        $response = Http::get("{$this->baseUrl}/validator/api/validationserverAPI.php", [
            'val_id' => $val_id,
            'store_id' => $this->storeId,
            'store_passwd' => $this->storePassword,
            'v' => 1,
            'format' => 'json'
        ]);

        $isSuccess = false;
        if ($response->successful()) {
            $data = $response->json();
            $isSuccess = isset($data['status']) && ($data['status'] === 'VALID' || $data['status'] === 'AUTHENTICATED');
        }

        return [
            'success' => $isSuccess,
            'order_number' => $orderNumber
        ];
    }
}