<?php

namespace App\Http\Controllers\Api\Mobile;

use App\Http\Controllers\Controller;
use App\Models\Config;
use App\Models\Currency;
use App\Models\Package;
use App\Models\PaymentHistory;
use App\Models\Subscription;
use App\Models\User;
use App\Repositories\Interfaces\Admin\PackageInterface;
use App\Repositories\Interfaces\Website\SubscriptionRepositoryInterface;
use App\Traits\Mobile\ApiResponseTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class PaymentController extends Controller
{
    use ApiResponseTrait;

    protected $subscriptionRepository;
    protected $packageRepo;


    public function __construct(PackageInterface $packageRepo, SubscriptionRepositoryInterface $subscriptionRepository)
    {
        $this->subscriptionRepository = $subscriptionRepository;
        $this->packageRepo = $packageRepo;
    }

    public function packages()
    {

        $data = [
            'packages' => Package::where('status', 1)->get()->transform(function ($item) {
                $item->price = get_currency($item->price);
                $item->storeSubscriptionId = slugify($item->name) . '_' . $item->price . '_' . ($item->type == 'monthly' ? '1m' : '1y');
                return $item;
            }),
        ];
        return $this->responseWithSuccess($data, __('package_retrieve_successfully'));
    }

    public function payment_history(Request $request)
    {
        $client_id = User::where('id', $request->user_id)->value('client_id');
        $data = [
            'payment_history' => Subscription::where('client_id', $client_id)->paginate(20),
        ];
        return $this->responseWithSuccess($data, __('payment_history_retrieve_successfully'));
    }

    public function webhook_callback(Request $request)
    {
        // Handle the webhook callback logic here
        $trx_id = $request->transaction_key;
        $plan   = $this->packageRepo->find($request->plan_id);
        $plan['client_id'] = 1;
        $status = $request->status == 'offline' ? true : false;
        $data = $this->subscriptionRepository->create($plan, $trx_id, '', $request, $status);
        return $this->responseWithSuccess($data, __('Webhook_callback_received_successfully'));
    }

    public function getSubscription(Request $request)
    {
        $user = User::find($request->user_id);
        if (!$user) {
            return $this->responseWithError('User not found', 404);
        }
        // Fetch the latest subscription payment history for the user
        $payment_history = Subscription::where('client_id', $user->client_id)
            ->latest()
            ->first();

        // Default response if no subscription found
        if (!$payment_history) {
            return $this->responseWithSuccess([
                'is_subscribed' => false,
                'message' => 'No subscription found.'
            ], __('subscription_checked_successfully'));
        }

        // Check if the subscription is still valid
        $now = now();

        // You must have a subscription end date or calculate from start + duration
        // Here, we assume you have `subscription_end` or you can compute from `created_at` + duration
        $subscriptionEnd = $payment_history->created_at->addDays($payment_history->package->day); // default 30 days

        $isValid = $now->lt($subscriptionEnd);

        $data = [
            'is_subscribed' => $isValid,
            'subscription_start' => $payment_history->created_at->toDateTimeString(),
            'subscription_end' => $subscriptionEnd->toDateTimeString(),
            'remaining_days' => $now->diffInDays($subscriptionEnd, false)
        ];

        return $this->responseWithSuccess($data, __('subscription_checked_successfully'));
    }

    public function offline_success(Request $request)
    {
        $trx_id = $request->transaction_key;
        $data   = null;
        $message = '';

        if ($request->payment_type == 'rental') {
            // Rental logic
            Log::info('info', $request->status);
            if ($request->status == 1 && $request->payment_method != 'offline') {
                // Online rental -> activate immediately
                $data = $this->subscriptionRepository->rentVideo($request->all(), 'rental');
                $data['status'] = true;
                $message = __('video_rented_successfully');
            } else {
                // Offline rental -> needs admin approval
                $data = $this->subscriptionRepository->rentVideo($request->all(), 'offline');
                $data['status'] = false; // pending
                $message = __('successful!!_wait_for_admin_approval');
            }
        } else {
            // Subscription logic
            if ($request->status == 1 && $request->payment_method !== 'offline') {
                // Online subscription -> activate immediately
                $plan    = $this->packageRepo->find($request->plan_id);
                $user_id = User::where('id', $request->user_id)->value('client_id');
                $plan['client_id'] = $user_id;

                $data = $this->subscriptionRepository->create($plan, $trx_id, '', $request, false);
                $data['status'] = true;
                $message = __('Subscription successfully');
            } else {
                // Offline subscription -> needs admin approval
                $plan    = $this->packageRepo->find($request->plan_id);
                $user_id = User::where('id', $request->user_id)->value('client_id');
                $plan['client_id'] = $user_id;
                $data = $this->subscriptionRepository->create($plan, $trx_id, '', $request, true);
                $data['status'] = false; // pending
                $message = __('successful!!_wait_for_admin_approval');
            }
        }

        return $this->responseWithSuccess($data, $message);
    }
}
