<?php

namespace Modules\Subscription\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\Response\ResponseService;
use Illuminate\Http\Request;

use Modules\Notification\Services\NotificationService;
use Modules\Package\Services\PackageService;
use Modules\Payment\Services\PaymentService;
use Modules\PaymentLog\Services\PaymentLogService;
use Modules\Subscription\Requests\Api\SubscriptionRequest;
use Modules\Subscription\Resources\Api\SubscriptionResource;
use Modules\Subscription\Services\SubscriptionService;
use Modules\User\Services\UserService;
class SubscriptionController extends Controller
{

    public function __construct(
        private PackageService $packageService,
        private SubscriptionService $subscriptionService,
        private PaymentLogService $paymentLogService,
        private UserService $userService,
        private NotificationService $notificationService,
        private PaymentService $paymentService,
    ) {
    }
    /**
     * Get Subscriptions.
     *
     * @param Request $request
     * @return void
     */
    public function index(Request $request): void
    {
        $credentials['api'] = true;
        $credentials['user_id'] = auth()->id();
        $query = $this->subscriptionService->get($credentials);

        $response = [
            "query" => $query,
            "request" => $request,
            "resourceClass" => SubscriptionResource::class,
            "returnName" => "subscriptions"
        ];
        ResponseService::fetchPainateDate($response);
    }

    /**
     * Create Subscription.
     *
     * @param SubscriptionRequest $request
     * @return void
     */
    public function createSubscription(SubscriptionRequest $request)
    {
        $id = auth()->id();
        $user = auth()->user();
        $credentials = $request->only('package_id');
        $package = $this->packageService->getItem($credentials['package_id']);
        $credentials['user_id'] = $id;
        $credentials['total'] = $package['cost'];
        $credentials['remain_points'] = $package['points'];
        $credentials['points'] = $package['points'];
        $orderId = uniqid('ORD_');

        $payment = $this->paymentService->createPayment(
            orderId: $orderId,
            amount: $package['cost'],
            currency: 'SAR',
            customer: [
                'name' => ($user->name ?? '') . ($user->last_name ?? ''),
                'email' => $user->email ?? '',
                'phone' => $user->phone ?? '',
            ],
            meta: $credentials,
        );

        if (isset($payment['order']['url'])) {
            session()->put('telr_ref', $payment['order']['ref']); // Save for status check
            $response = [
                'status' => 200,
                'message' => '',
                'data' => $payment['order']['url']
            ];
            return ResponseService::response($response);
        }
        return ResponseService::response([
            'status' => 400,
            'message' => $payment['error']['message'] ?? 'Failed to create payment',
        ]);
    }
    public function store(SubscriptionRequest $request): void
    {
        $id = auth()->id();
        $user = auth()->user();
        $credentials = $request->only('package_id');
        $package = $this->packageService->getItem($credentials['package_id']);
        $credentials['user_id'] = $id;
        $credentials['total'] = $package['cost'];
        $credentials['remain_points'] = $package['points'];
        $credentials['points'] = $package['points'];
        $subscription = $this->subscriptionService->create($credentials);
        $this->paymentLogService->create([
            'status' => 1,
            'price' => $package['cost'],
            'user_id' => $id,
            'subscription_id' => $subscription->id
        ]);
        $this->notificationService->create([
            'target' => $id,
            'user_id' => $id,
            'title_ar' => 'الاشتراك في باقة',
            'title_en' => 'Subscribe to package',
            'description_ar' => 'تم اشتراكك بنجاح',
            'description_en' => 'You have successfully subscribed',

        ]);
        $this->userService->update(['points' => $user->points + $package['points'], 'unread_notification' => $user->unread_notification + 1], $id);
        $credentialsData['api'] = true;
        $credentialsData['user_id'] = auth()->id();
        $query = $this->subscriptionService->get($credentialsData);

        $response = [
            "query" => $query,
            "request" => $request,
            "resourceClass" => SubscriptionResource::class,
            "returnName" => "subscriptions"
        ];
        ResponseService::fetchPainateDate($response);
    }

}
