<?php

namespace App\Livewire\Page\Dashboard;

use App\Models\SubscriptionPlan;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;
use Livewire\Attributes\Locked;
use Livewire\Attributes\Renderless;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Title('Dashboard')]
class Dashboard extends Component
{
    public $subTier;
    public $subStatus;
    public $subEndsAt;
    public $subscriptions;
    #[Locked]
    public $plans;
    #[Locked]
    public $billingProvider;
    public User $user;

    public function mount()
    {
        if (Session::has('redirect')) {
            return $this->redirect(Session::get('redirect'));
        }

        $sessionKey = Session::has('subscribeToPlan') ? 'subscribeToPlan' : null;

        if ($sessionKey) {
            $this->dispatch('clickOnPlan', plan: Session::get($sessionKey));
            Session::forget($sessionKey);
        }

        $this->billingProvider = Auth::user()?->billing_provider;

        $user = Auth::user();

        $this->user = $user;

        if ($user->can('access admin panel')) {
            return redirect('/user/profile');
        }

        $this->plans = SubscriptionPlan::where('billing_provider', $this->billingProvider)->get()->keyBy('tier')->toArray();

        $subscription = $user->subscription();

        if ($user->can('access premium features')) {
            $this->getSubStatus();
            $this->getSubTier();
        }
        $this->getSubData();
    }

    public function getSubData()
    {
        if ($this->user && $this->user->subscriptions()->count()) {
            $this->subscriptions = $this->user->subscriptions;
        }
    }

    public function getSubStatus()
    {
        $subStatus = null;
        $subscriptions = $this->user->subscriptions()->latest()->first();
        if ($this->billingProvider === 'stripe') {
            $subStatus = $subscriptions->stripe_status ?? null;
        }
        $this->subStatus = $subStatus;
        $this->subEndsAt = $subscriptions->ends_at ?? null;
    }

    public function getSubTier()
    {
        $tier = null;
        $subscriptions = $this->user->subscriptions();
        if ($this->billingProvider === 'stripe') {
            $tier = SubscriptionPlan::where('plan_id', $subscriptions->latest()->first()->stripe_price)->first()->name;
        }

        $this->subTier = $tier;
    }

    public function render()
    {
        if (Auth::user()->cannot('access premium features')) {
            if ($this->billingProvider === 'stripe') {
                if (request()->query('sub') === 'true') {
                    return view('livewire.partials.loadingSpinner');
                }
            }
        }

        return view('livewire.pages.dashboard.dashboard');
    }
}
