<?php

namespace App\Traits;

use App\Models\CompanySubscriptions;
use App\Models\CompanyUser;
trait CheckEmployeeCountTraits
{
    public function employeeCountValidation($company_id)
    {
        $subscriptionData = $this->companySubscriptionMaximumEmployee($company_id);
        $max_employee = $subscriptionData['max_employee'];
        $is_unlimited = $subscriptionData['is_unlimited'];
        $companyEmployeesCount = $this->companyEmployeesCount($company_id);

        if ($is_unlimited == 0) {
            if ($companyEmployeesCount >= $max_employee) {
                return response()->json(['errors' => ['You have reached the maximum allowed employee for your subscription. Please upgrade to continue.']])->setStatusCode(201);
            }
        }
    }

    //Check subscription
    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)
            ->get()
            ->first();
    }

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

        return $companyWorkerData->count();
    }

    //not yet implemented, but for checking the number of current available worker
    public function checkSubscriptionAvailableSpace($numberOfWorkerTobeRecruited, $companyID)
    {

        $subscriptionData = $this->companySubscriptionMaximumEmployee($companyID);
        $max_employee = $subscriptionData['max_employee'];
        $is_unlimited = $subscriptionData['is_unlimited'];
        $companyEmployeesCount = $this->companyEmployeesCount($companyID);

        $totalWorkerCount = (int) $companyEmployeesCount + (int) $numberOfWorkerTobeRecruited;

        return [
            'numberOfWorkerTobeRecruited' => $numberOfWorkerTobeRecruited,
            'companyID' => $companyID,
            'max_employee' => $max_employee,
            'is_unlimited' => $is_unlimited,
            'companyEmployeesCount' => $companyEmployeesCount,
            'totalWorkerCount' => $totalWorkerCount,
        ];

        if ($is_unlimited == 0) {
            if ($totalWorkerCount >= $max_employee) {
                return response()->json(['errors' => ['You have reached the maximum allowed employee for your subscription. Please upgrade to continue.']])->setStatusCode(201);
            }
        }

    }

}
