<?php

namespace App\Services\Gateway\UddoktaPay;

use App\Services\Gateway\GatewayInterface;
use App\Services\Gateway\UddoktaPay\UddoktaPay;
use App\Models\Order;
use App\Models\Deposit;
use App\Services\OrderService;
use App\Services\DepositService;
use Exception;

class Payment implements GatewayInterface
{
    public static function prepareDepositData(Deposit $deposit, $gateway)
    {
        $settings = gs();
        $apiKey = $settings->uddoktapay_api_key;
        $apiBaseURL = $settings->uddoktapay_api_url;

        $uddoktaPay = new UddoktaPay($apiKey, $apiBaseURL);

        // Use helper url generation
        // assuming standard structure
        $successUrl = "http://localhost/TopUpModule/index.php?action=deposit_ipn&id={$deposit->id}";
        $cancelUrl = "http://localhost/TopUpModule/index.php?action=deposit_cancel";

        $requestData = [
            'cus_name' => $deposit->user()->name ?? 'Test User',
            'cus_email' => $deposit->user()->email ?? 'test@test.com',
            'amount' => $deposit->amount,
            'metadata' => [
                'track_id' => $deposit->track_id,
            ],
            'success_url' => $successUrl,
            'cancel_url' => $cancelUrl,
            'webhook_url' => $successUrl, // For testing, often same as success
        ];

        try {
            $paymentUrl = $uddoktaPay->initPayment($requestData);
            return ['redirect_url' => $paymentUrl];
        } catch (Exception $e) {
            return ['error' => true, 'message' => $e->getMessage()];
        }
    }

    public static function prepareOrderData(Order $order, $gateway)
    {
        $settings = gs();
        $apiKey = $settings->uddoktapay_api_key;
        $apiBaseURL = $settings->uddoktapay_api_url;

        $uddoktaPay = new UddoktaPay($apiKey, $apiBaseURL);
        $successUrl = "http://localhost/TopUpModule/index.php?action=order_ipn&id={$order->id}";
        $cancelUrl = "http://localhost/TopUpModule/index.php?action=order_cancel";

        $requestData = [
            'cus_name' => $order->user()->name ?? 'Test User',
            'cus_email' => $order->user()->email ?? 'test@test.com',
            'amount' => $order->amount,
            'metadata' => [
                'order_id' => $order->id,
                'track_id' => $order->track_id,
            ],
            'success_url' => $successUrl,
            'cancel_url' => $cancelUrl,
            'webhook_url' => $successUrl,
        ];

        try {
            $paymentUrl = $uddoktaPay->initPayment($requestData);
            return ['redirect_url' => $paymentUrl];
        } catch (Exception $e) {
            return ['error' => true, 'message' => $e->getMessage()];
        }
    }

    public static function depositIpn($request, Deposit $deposit, $gateway)
    {
        // $request is usually $_REQUEST or $_POST
        // UddoktaPay might send data via POST
        // Need to verify logic

        $settings = gs();
        $apiKey = $settings->uddoktapay_api_key;
        $apiBaseURL = $settings->uddoktapay_api_url;
        $uddoktaPay = new UddoktaPay($apiKey, $apiBaseURL);

        $invoiceId = $request['transaction_id'] ?? null; // Adjust parameter name based on gateway response
        // Note: UddoktaPay 'success_url' might get transaction_id in query params?
        // Let's assume passed in request

        if (!$invoiceId) {
            throw new Exception("No transaction ID provided");
        }

        try {
            $response = $uddoktaPay->verifyPayment($invoiceId);
        } catch (Exception $e) {
            throw new Exception("Verification Error: " . $e->getMessage());
        }

        if (isset($response['status']) && $response['status'] === 'COMPLETED') {
            $depositService = new DepositService();
            $depositService->completeDeposit($deposit, 'uddoktapay', $response['transaction_id']);
            return ['status' => 'success', 'message' => 'Deposit Successful'];
        }

        return ['status' => 'error', 'message' => 'Payment not completed'];
    }

    public static function orderIpn($request, Order $order, $gateway)
    {
        $settings = gs();
        $apiKey = $settings->uddoktapay_api_key;
        $apiBaseURL = $settings->uddoktapay_api_url;
        $uddoktaPay = new UddoktaPay($apiKey, $apiBaseURL);

        $invoiceId = $request['transaction_id'] ?? null;

        if (!$invoiceId) {
            throw new Exception("No transaction ID provided");
        }

        try {
            $response = $uddoktaPay->verifyPayment($invoiceId);
        } catch (Exception $e) {
            throw new Exception("Verification Error: " . $e->getMessage());
        }

        if (isset($response['status']) && $response['status'] === 'COMPLETED') {
            $orderService = new OrderService();
            $orderService->completeOrder($order, 'uddoktapay', $response['transaction_id']);
            return ['status' => 'success', 'message' => 'Order Successful'];
        }

        return ['status' => 'error', 'message' => 'Payment not completed'];
    }
}
