<?php

namespace App\Modules\Company\Subscription;

use App\Models\CompanySubscriptionPayments;
use App\Models\CompanySubscriptionRates;
use App\Models\CompanySubscriptions;
use App\Models\CompanyUser;
use App\Models\Company;
use App\Modules\Company\Subscription\Discount\Coupon;
use App\Traits\UserTraits;

use Illuminate\Support\Facades\DB;

class Subscription
{
    use UserTraits;

    public $companySubscription;
    public $companyID;
    public $userData;
    public $coupon;

    public function __construct()
    {
        $this->coupon              = new Coupon;
        $this->companyID           = $this->getCurrentUser()->company_id;
        $this->companySubscription = CompanySubscriptions::where('company_id', $this->companyID)->first();
    }

    public function fetchCompanySubscsriptionDetails()
    {
        $company_subscription = $this->checkSubscription($this->companyID);

        //! If no subscription, null for specifying to go to subscription page 
        if (!$company_subscription) 
        {
            return null;
        }

        $subscriptionData      = $this->companySubscriptionMaximumEmployee($this->companyID);
        $companyEmployeesCount = $this->getCompanyEmployeesCount($this->companyID);

        $max_employee = $subscriptionData->max_employee;
        $is_unlimited = $subscriptionData->is_unlimited;

        if ($is_unlimited) 
        {
            $remaining_employee = 'unlimited';
        } 
        else 
        {
            $remaining_employee = $max_employee - $companyEmployeesCount;
        }

        return [
            'company_subscription'   => $company_subscription,
            'remaining_employee'     => $remaining_employee,
            'current_employee_count' => $companyEmployeesCount,
        ];
    }

    public function checkSubscription($companyID)
    {
        return CompanySubscriptions::select(
            'company_subscriptions.*',
            'company_subscription_rates.max_employee',
            'company_subscription_rates.is_unlimited',
            )
            ->join('company_subscription_rates', 'company_subscriptions.subscription_rate_id', '=', 'company_subscription_rates.id')
            ->where('company_subscriptions.company_id', $companyID)
            ->first();
    }

    public function companySubscriptionMaximumEmployee($company_id)
    {
        return CompanySubscriptions::select(
            'company_subscription_rates.max_employee',
            'company_subscription_rates.is_unlimited',
            )
            ->join('company_subscription_rates', 'company_subscriptions.subscription_rate_id', '=', 'company_subscription_rates.id')
            ->where('company_subscriptions.company_id', $company_id)
            ->first();
    }

    public function getCompanyEmployeesCount($company_id)
    {
        $companyWorkerData = CompanyUser::select()
            ->where('company_id', $company_id)
            ->where('role_id', 5)
            ->get();

        return $companyWorkerData->count();
    }


    public function getAllSubscsriptionRates($max = 0)
    {
        return CompanySubscriptionRates::when(
                ($max > 0), 
                function ($query) use ($max) 
                {
                    return $query->where('max_employee', '>', $max)
                        ->orWhere('is_unlimited', 1);
                }
            )
            ->where('is_disabled', false)
            ->get();
    }

    public function getSubscriptionRateDetails($id)
    {
        return CompanySubscriptionRates::find($id);
    }

    public function setCompanySubscriptionToExpired()
    {
        if ($this->checkStatus($this->companyID) == 'expired') 
        {
            return [
                'status' => 'success',
            ];
        };

        DB::beginTransaction();

        $company_transaction = $this->setBlocked($this->companyID);

        if ($company_transaction) 
        {
            DB::commit();
        
            return [
                'status' => 'success',
            ];
        } 
        else 
        {
            DB::rollBack();
        
            return [
                'status' => 'failed',
            ];
        }
    }

    public function checkStatus($id)
    {
        $status = CompanySubscriptions::select('is_blocked')->where('company_id', $id)->get()->first();

        if ($status->is_blocked == 'true') 
        {
            return 'blocked';
        } 
        else 
        {
            //? update to blocked
            return 'update'; 
        }
    }

    public function setBlocked($id)
    {
        return CompanySubscriptions::where('company_id', $id)->update(['is_blocked' => 'true']);
    }

    public function getrenewBillingData($payload)
    {
        if (!$payload->selectedSubscriptionID) 
        {
            return response()->json(['error' => 'Selected subscription is empty.']);
        }

        return [
            'companySubscription'         => $this->companySubscription,
            'companyDetails'              => Company::where('id', $this->companyID)->first(),
            'selectedSubscriptionDetails' => $this->showSubscriptionRateDetails($payload->selectedSubscriptionID),
            'enabledSubscriptionRates'    => $this->getAllSubscsriptionRates(),
        ];
    }

    public function showSubscriptionRateDetails($rateID)
    {
        return CompanySubscriptionRates::where('id', $rateID)->first();
    }

    public function getPayNowBillingDetails()
    {
        $companyID = $this->companyID;

        $companySubscription = CompanySubscriptions::where('company_id', $companyID)->first();
        
        if(!$companySubscription)
        {
            return response()->json(['error' => "Company subscription doesn't exist."]);
        }

        $companyDiscount = Company::select('discount')->where('id', $companyID)->first();

        return [
            'latestPayment'                 => CompanySubscriptionPayments::where('company_id', $companyID)->latest()->first(),
            'subscribedSubscriptionDetails' => CompanySubscriptionRates::where('id', $companySubscription->subscription_rate_id)->first(),
            'companySubscriptionDetails'    => $companySubscription,
            'hasCompanyDiscount'            => $companyDiscount->discount > 0 ? $companyDiscount->discount : false,
            'companyDetails'                => Company::where('id', $companyID)->first(),
            'activeCoupon'                  => $this->coupon->getActiveCoupon($companyID)
        ];
    }

    public function showUpgradedSubscriptionRate()
    {
        $currentSubscription = $this->showSubscriptionRateDetails($this->companySubscription->subscription_rate_id);
        $maxEmployee         = $currentSubscription->max_employee;

        return CompanySubscriptionRates::when(
            ($maxEmployee), function ($query) use ($maxEmployee) 
                {
                    return $query->where('max_employee', '>', $maxEmployee)
                        ->orWhere('is_unlimited', 1);
                }
            )
            ->where('is_disabled', false)
            ->get();
    }

    public function getUpgradeBillingDetails($payload)
    {
        return [
            'companySubscription'         => $this->companySubscription,
            'companyDetails'              => Company::where('id', $this->companyID)->first(),
            'selectedSubscriptionDetails' => $this->showSubscriptionRateDetails($payload->selectedRateID),
        ];
    }
}
