<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\Subscription\SubscriptionOrderUpdateRequest;
use App\Http\Requests\Subscription\SubscriptionUpdateRequest;
use App\Services\OrderService;
use App\Services\SubscriptionService;

class AdminSubscriptionController extends Controller
{
    protected array $data = [];
    private $subscriptionService;

    public function __construct(SubscriptionService $subscriptionService, OrderService $orderService)
    {
        $this->data['title'] = 'Subscriptions';

        $this->subscriptionService = $subscriptionService;

        $this->orderService = $orderService;
    }

    public function index()
    {
        $this->data['allSubscriptions'] = $this->subscriptionService->all();

        // Get filter values from the request
        $searchTerm = request('search');
        $status = request('status');
        $userId = request('user_id');

        if ($searchTerm !== null || $status !== null || $userId !== null) {
            $this->data['subscriptions'] = $this->subscriptionService->filter($searchTerm, $status, $userId, $perPage=10);
        } else {
            $this->data['subscriptions'] = $this->subscriptionService->paginate($perPage=10);
        }

        return view('admin.Subscription.index', $this->data);
    }

    public function edit($id)
    {
        $subscription = $this->subscriptionService->find($id);

        $this->data['title'] = 'Subscription #' . $subscription->reference_id . ' Details';

        $this->data['order'] = $this->orderService->getBySubscription($subscription->id);

        $this->data['billingCycles'] = getConstants('billing_cycle');

        $this->data['subscription'] = $subscription;

        return view('admin.Subscription.show', $this->data);
    }

    public function update(SubscriptionUpdateRequest $request, $id)
    {
        $subscription = $this->subscriptionService->find($id);

        if (!$subscription) {
            return redirect()->back()->with('error', 'Subscription not found');
        }

        $status = (string) $request->validated()['status'];

        if ($subscription->status !== $status) {
            if (in_array($status, [
                getConstant('SUBSCRIPTION_STATUS_TRIAL'),
                getConstant('SUBSCRIPTION_STATUS_INACTIVE'),
                getConstant('SUBSCRIPTION_STATUS_PAUSED')
            ])) {
                return redirect()->back()->with('error', "You can't do this transaction");
            }

            if ($status == getConstant('SUBSCRIPTION_STATUS_ACTIVE')) {
                if ($subscription->status == getConstant('SUBSCRIPTION_STATUS_TRIAL')) {
                    return redirect()->back()->with('error', "You can't do this transaction");
                } else {
                    $this->subscriptionService->activateSubscription($subscription);
                }
            } elseif ($status == getConstant('SUBSCRIPTION_STATUS_EXPIRED')) {
                if ($subscription->status == getConstant('SUBSCRIPTION_STATUS_TRIAL')) {
                    $this->subscriptionService->moveTrialSubscriptionToExpired($subscription);
                } else {
                    $this->subscriptionService->moveSubscriptionToExpired($subscription);
                }
            } elseif ($status == getConstant('SUBSCRIPTION_STATUS_CANCELLED')) {
                if ($subscription->status == getConstant('SUBSCRIPTION_STATUS_TRIAL')) {
                    $this->subscriptionService->moveTrialSubscriptionToCancelled($subscription);
                } else {
                    $this->subscriptionService->moveSubscriptionToCancelled($subscription);
                }
            } elseif ($status == getConstant('SUBSCRIPTION_STATUS_PAST_DUE')) {
                if ($subscription->status == getConstant('SUBSCRIPTION_STATUS_TRIAL')) {
                    $this->subscriptionService->moveTrialSubscriptionToPastDue($subscription);
                } else {
                    $this->subscriptionService->moveSubscriptionToPastDue($subscription);
                }
            } elseif ($status == getConstant('SUBSCRIPTION_STATUS_SUSPENDED')) {
                if ($subscription->status == getConstant('SUBSCRIPTION_STATUS_TRIAL')) {
                    $this->subscriptionService->moveTrialSubscriptionToSuspended($subscription);
                } else {
                    $this->subscriptionService->moveSubscriptionToSuspended($subscription);
                }
            } else {
                return redirect()->back()->with('error', 'Something went wrong');
            }
        } else {
            return redirect()->back()->with('error', 'Please change the status then update');
        }

        return redirect()->back()->with('success', 'Subscription updated successfully');
    }

    public function showSubscriptionOrder($subscriptionId, $orderId)
    {
        $order = $this->subscriptionService->getOrderBySubscriptionAdmin($subscriptionId, $orderId);

        if (!$order) {
            return redirect()->back()->with('error', 'Subscription Order not found!');
        }

        $this->data['order'] = $order;
        $this->data['title'] = 'Subscription Order ' . $order->order_reference . ' Details';

        return view('admin.Subscription.subscription_order', $this->data);
    }

    public function updateSubscriptionOrder(SubscriptionOrderUpdateRequest $request, $subscriptionId, $orderId)
    {
        $order = $this->subscriptionService->getOrderBySubscriptionAdmin($subscriptionId, $orderId);
        $subscription = $this->subscriptionService->getById($subscriptionId);

        if (!$order || !$subscription) {
            return redirect()->back()->with('error', !$order ? 'Subscription Order not found!' : 'Subscription not found!');
        }

        if ($subscription->id !== $order->subscription_id) {
            return redirect()->back()->with('error', 'This order is not related to this Subscription!');
        }

        $status = (int)$request->validated()['status'];

        if ($order->status !== $status) {

            if ((int)getConstant('ORDER_STATUS_COMPLETED')) {
                $this->subscriptionService->activateSubscription($subscription);

                return redirect()->back()->with('success', 'Order completed and Subscription activated Successfully');
            } else {
                return redirect()->back()->with('success', 'This transaction is not possible now');
            }
        } else {
            return redirect()->back()->with('error', 'Please change the status then update');
        }
    }
}
