<?php

namespace App\Modules\Company\Account;

use App\Models\Company; 
use App\Models\CompanySubscriptions; 
use App\Models\Worker;
use App\Traits\UserTraits;
use App\Traits\CompanyCheckActiveTransactionsTrait;

use Carbon\Carbon; 

class FreezeAccountModule
{
    use UserTraits;
    use CompanyCheckActiveTransactionsTrait;

    /**
     * Freeze Account
     * 
     * @return array
     */
    public function freezeAccount() : array
    {
        $currentUser            = $this->getCurrentUser();
        $companyId              = $currentUser->company_id;

        $company                =  Company::findOrFail($companyId);
        $activeTransactions     =  $this->checkIfHasActiveTransaction($companyId); 

        //! CHECK IF HAS ACTIVE TRANSACTIONS
        if(count($activeTransactions) >= 1)
        {
            return [
                'success'            => false,
                'activeTransactions' => $activeTransactions
            ];
        }

        //? SHOULD PAUSE SUBSCRIPTION HERE
        $company->is_freezed    = true; 
        $company->date_freezed  = Carbon::now();      
        $company->save(); 

        return [
            'success'            => true,
            'activeTransactions' => $activeTransactions
        ];
    }
    
    /**
     * Unfreeze Account 
     * 
     * @param array $data
     * 
     * @return array
     */
    public function unFreezeAccount($data) : array
    {
        try 
        {
            $user = Worker::where('email_address', '=',  $data['email'])->first();
    
            $companyData = Worker::select(
                'company_users.company_id',
                'company_users.role_id'
            )
            ->leftJoin('company_users', 'company_users.worker_id', '=', 'workers.id')
            ->leftJoin('companies', 'companies.id', '=', 'company_users.company_id')
            ->where('workers.id', $user->id)
            ->first();
    
            $company = Company::find($companyData->company_id); 

            //! CHECK IF USER IS AUTHORIZED (COMPANY OWNER / ADMIN)
            $isAuthorized = $companyData->role_id == 1 ? true : false; 
            
            if ($isAuthorized) 
            {
                //! SHOULD MODIFY SUBSCRIPTION HERE
                $this->resumeSubscription($company->id, $company->date_freezed);

                $company->is_freezed   = false;
                $company->date_freezed = null;
                $company->save();
            }

            return [
                'success'      => true,
                'isAuthorized' => $isAuthorized
            ];
        } 
        catch (\Throwable $th) 
        {
            return [
                'success'      => false,
                'isAuthorized' => false,
            ]; 
        }

    }
    
    /**
     * CheckIfAccountIsFrozen
     * 
     * @param array $data
     * 
     * @return array
     */
    public function checkIfAccountIsFrozen($data) : array 
    {   
        $user = Worker::where('email_address', '=',  $data['email'])->first();

        $companyData = Worker::select(
            'company_users.company_id',
            'company_users.role_id'
        )
        ->leftJoin('company_users', 'company_users.worker_id', '=', 'workers.id')
        ->leftJoin('companies', 'companies.id', '=', 'company_users.company_id')
        ->where('workers.id', $user->id)
        ->first();

        $company = Company::find($companyData->company_id); 

        if($company == null)
        {
            return [
                'isFrozen'    => false,
                'isAuthorized' => false,
            ]; 
        }

        if (!$company->is_freezed)
        {
            return [
                'isFrozen'    => false,
                'isAuthorized' => false,
            ]; 
        } 

        //! CHECK IF USER IS AUTHORIZED (COMPANY OWNER / ADMIN)
        $isAuthorized = $companyData->role_id == 1 ? true : false; 

        return [
            'isFrozen'    => true,
            'isAuthorized' => $isAuthorized,
        ]; 
    }

    /**
     * Check if Has Active Transactions
     * 
     * @param  int $companyId 
     * 
     * @return array
     */
    public function checkIfHasActiveTransaction($companyId) : array
    {
        $transactions = [];

        if ($this->checkIfHasActiveLoanApprovedRequest($companyId))
        {
            array_push($transactions, "Active Loan Approved Transactions"); 
        }

        if ($this->checkIfHasActiveLoanPendingRequest($companyId))
        {
            array_push($transactions, "Active Loan Pending Transactions"); 
        }

        if ($this->checkIfHasActiveBorrowApprovedRequest($companyId))
        {
            array_push($transactions, "Active Borrow Approved Transactions"); 
        }

        if ($this->checkIfHasActiveBorrowPendingRequest($companyId))
        {
            array_push($transactions, "Active Borrow Pending Transactions"); 
        }

        if ($this->checkIfHasActiveJobSeekerApplicant($companyId))
        {
            array_push($transactions, "Active Jobseeker Applications");  
        }

        if ($this->checkIfHasActiveWorkerRequest($companyId))
        {
            array_push($transactions, "Active Worker Request Transaction");
        }

        if ($this->checkIfHasAmountDue($companyId))
        {
            array_push($transactions, "Account still has amount due to be paid.");
        }

        if ($this->checkIfSubscriptionHasExpired($companyId))
        {
            array_push($transactions, "Account Subscription has Expired. Please renew your account first");
        }

        return $transactions; 
    }

    /**
     * Resume Subscription
     * 
     * @param  int $companyId
     * @param  int $dateFroze
     *  
     * @return void 
     */
    private function resumeSubscription($companyId, $dateFroze) : void  
    {
        $subscription                       = CompanySubscriptions::where('company_id', $companyId)->firstOrFail();

        $dateFrozen                         = Carbon::createFromDate($dateFroze); 
        $currentMonthPaid                   = Carbon::createFromDate($subscription->current_month_paid);
        $currentDateSubscriptionEnd         = Carbon::createFromDate($subscription->duration); 

        $dateUnFroze                        = Carbon::now(); 
        $dayFrozeTimeFrameDifference        = $dateFrozen->diffInDays($dateUnFroze);

        //! FOR CURRENT MONTH PAID 
        $newCurrentMonthPaid                = $currentMonthPaid->addDays($dayFrozeTimeFrameDifference); 

        //! FOR NEW SUBSCRIPTION DURATION
        $addDaysToSubscriptionDuration      = $dayFrozeTimeFrameDifference; 
        $newDateSubscriptionEnd             = $currentDateSubscriptionEnd->addDays($addDaysToSubscriptionDuration);

        $subscription->current_month_paid   = $newCurrentMonthPaid; 
        $subscription->duration             = $newDateSubscriptionEnd;

        $subscription->save(); 
    }
}   