<?php

namespace Modules\Payment\Services;

use Illuminate\Support\Facades\Http;
use Modules\ChipOrder\Services\ChipOrderService;
use Modules\Payment\Interfaces\PaymentRepositoryInterface;
use Modules\Payment\Models\Payment;
use Modules\Payment\Models\PaymentDetails;
use Modules\Subscription\Services\SubscriptionService;

class PaymentService
{

    private PaymentRepositoryInterface $paymentRepository;
    private SubscriptionService $subscriptionService;
    private ChipOrderService $chipOrderService;

    public function __construct(
        PaymentRepositoryInterface $paymentRepository,
        SubscriptionService $subscriptionService,
        ChipOrderService $chipOrderService,
    ) {
        $this->paymentRepository = $paymentRepository;
        $this->subscriptionService = $subscriptionService;
        $this->chipOrderService = $chipOrderService;
    }

    public function createPayment($orderId, $amount, $currency = 'SAR', $customer = [], $meta = [])
    {
        $payload = [
            'method' => 'create',
            'store' => config('services.telr.store_id'),
            'authkey' => config('services.telr.auth_key'),

            'order' => [
                'cartid' => (string) $orderId,
                'amount' => (float) $amount,
                'currency' => $currency,
                'description' => 'Order Payment',
                'test' => 1, // Use 0 in production
            ],

            'return' => [
                'authorised' => config('services.telr.return_url'),
                'declined' => config('services.telr.cancel_url'),
                'cancelled' => config('services.telr.cancel_url'), // optional webhook
            ],

            'customer' => [
                'name' => $customer['name'] ?? 'Test User',
                'email' => $customer['email'] ?? 'test@example.com',
                'phone' => $customer['phone'] ?? '971500000000',
            ],
        ];


        // dd($payload);
        $response = Http::post(config('services.telr.payment_url'), $payload)->json();
        unset($payload['authkey']);
        unset($payload['store']);
        $this->create([
            'status' => 'created',
            'ref' => $response['order']['ref'],
            'meta' => $meta,
            'request' => $payload,
            'response' => $response,
            'user_id' => $meta['user_id'] ?? (auth()->id() ?? null),
        ]);
        return $response;
    }
    public function checkStatus($ref)
    {
        $payload = [
            'method' => 'check',
            'store' => config('services.telr.store_id'),
            'authkey' => config('services.telr.auth_key'),
            'order' => ['ref' => $ref],
        ];
        $response = Http::post(config('services.telr.status_url'), $payload)->json();
        $code = $response['order']['status']['code'];
        $status = "failed";
        if ($code == 3) {
            $status = "success";
        } elseif ($code == 2) {
            $status = "pending";
        }
        $payment = $this->getItemByRef($ref);
        $data['status'] = $status;
        $meta = $payment->meta()->meta ?? null;
        if (in_array($code, [2, 3]) && $meta) {
            $meta = json_decode($meta, true);
            // dd($meta);
            if (isset($meta['package_id'])) {
                $subscription = $this->subscriptionService->createNewSubscription($meta);
                $data['subscription_id'] = $subscription->id;
            }
            if (isset($meta['address_id'])) {
                $order = $this->chipOrderService->create($meta);
                $data['chip_order_id'] = $order->id;
            }
        }
        // dd($data);
        $this->update($data, $payment->id);
        unset($payload['authkey']);
        unset($payload['store']);
        $this->createDetails([
            'payment_id' => $payment->id,
            'request' => json_encode($payload),
            'response' => json_encode($response),
            'type' => 'callback'
        ]);

        return $response;
    }
    public function get(array $request = [])
    {
        $builder = $this->paymentRepository->get($request);

        if (@$request['status']) {
            $builder->where('status', $request['status']);
        }
        if (@$request['chip_order_id']) {
            $builder->where('chip_order_id', $request['chip_order_id']);
        }
        if (@$request['subscription_id']) {
            $builder->where('subscription_id', $request['subscription_id']);
        }
        if (@$request['invoice_id']) {
            $builder->where('invoice_id', $request['invoice_id']);
        }
        if (@$request['user_id']) {
            $builder->where('user_id', $request['user_id']);
        }


        if (@$request['date_from']) {
            $builder->whereDate('cities.created_at', '>=', $request['date_from']);
        }

        if (@$request['date_to']) {
            $builder->whereDate('cities.created_at', '<=', $request['date_to']);
        }

        if (isset($request['status'])) {
            if (@$request['status'] == 0) {
                $builder->onlyTrashed();
            }
        }

        if (@$request['orderBy']) {
            $builder->orderBy($request['orderBy']['key'], $request['orderBy']['value']);
        } else {
            $builder->orderBy('id', 'DESC');
        }

        if (@$request['paginate']) {
            $payments = $builder->paginate(50);
        } elseif (@$request['api']) {
            $payments = $builder;
        } else {
            $payments = $builder->cursor();
        }
        return $payments;
    }



    public function checkItem($id)
    {
        $payment = $this->paymentRepository->checkItem($id);
        return $payment;
    }

    public function getItem($id)
    {
        $payment = $this->checkItem($id);

        return $payment;
    }
    public function getItemByRef($ref)
    {
        $request['ref'] = $ref;
        $request['api'] = true;
        $payment = $this->get($request)->first();

        return $payment;
    }

    public function getItemTrashed($id)
    {
        $payment = $this->paymentRepository->getItemTrashed($id);
        return $payment;
    }

    public function create(array $request): Payment
    {
        $payment = $this->paymentRepository->create($request);
        $this->createDetails([
            'payment_id' => $payment->id,
            'meta' => json_encode($request['meta']),
            'request' => json_encode($request['request']),
            'response' => json_encode($request['response']),
            'type' => 'create'
        ]);
        return $payment;
    }
    public function createDetails(array $request): PaymentDetails
    {
        $paymentDetails = $this->paymentRepository->createDetails($request);
        return $paymentDetails;
    }
    public function update(array $request, int $id): Payment
    {
        $payment = $this->checkItem($id);
        $payment = $this->paymentRepository->update($request, $payment);
        return $payment;
    }
    public function destroy(int $id): void
    {
        $payment = $this->checkItem($id);
        if ($payment) {
            $this->paymentRepository->destroy($payment);
        } else {
            $payment = $this->getItemTrashed($id);
            $this->paymentRepository->restore($payment);
        }
    }
    public function destroyAll(array $request): void
    {
        if ($request['status'] == 1) {
            $this->paymentRepository->destroyAll($request['ids']);
        } else {
            $this->paymentRepository->restoreAll($request['ids']);
        }
    }
}
