<?php

namespace App\Http\Resources\V2;

use App\Classes\Modules\Companies\Services\FetchesCompanyServices;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\BankAccountType;
use App\Classes\ValueObjects\Constants\BusinessType;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Classes\ValueObjects\Constants\RoleTypes;
use App\Classes\ValueObjects\Constants\SegmentConstants;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Currency;
use App\Models\SegmentConstant;
use Carbon\Carbon;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Auth;
use App\Http\Resources as V1;


class CompanyV2Resource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $lastPayment = $this->transactions()->where('transactions.type', TransactionType::PAYMENT)->whereIn('transactions.status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->orderBy('id', 'DESC')->first();
        $totalPayments =  $this->transactions()->where('transactions.type', TransactionType::PAYMENT)->whereIn('transactions.status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->sum('amount');

        $segment = SegmentConstant::where('reference', SegmentConstants::SUPPLIER_CURRENCIES)->where('detail->id', $this->id)->first();
        $serviceCharge = SegmentConstant::where('reference', SegmentConstants::SERVICE_CHARGE)->where('detail->id', $this->id)->first();

        $userResource = null;

        $userInfoEmail = $this->userInfo && isset($this->userInfo->email) ? $this->userInfo->email : null;
        $userInfoType = $this->userInfo && isset($this->userInfo->type) ? $this->userInfo->type : null;

        // if(!$userInfoEmail && Auth::user()){
        //     $userInfoEmail = Auth::user()->email;
        // }
        // if(!$userInfoType && Auth::user()){
        //     $userInfoType = Auth::user()->type;
        // }

        if(!is_null($userInfoEmail) && !is_null($userInfoType)){
            $userResource = new V1\UserResource($userInfoType === RoleTypes::USER ? $this->employees()->where('email', '=',  $userInfoEmail)->first() : $this->employees()->orderBy('id', 'DESC')->first());
        }

        return [
            'id' => $this->id,
            'name' => $this->name,
            'reference' => $this->reference,
            'debtor' => $this->debtor,
            'type' => (int) $this->type,
            'business_type' => (int) $this->business_type,
            'status' => (int) $this->status,
            'contact' => new V1\ContactResource ($this->when($this->has('contacts'), $this->contacts->first())),
            'address' => new V1\AddressResource($this->when($this->has('addresses'), $this->addresses->where('billing', true)->first())),
            'employee' =>  $userResource,
            'identification' => new V1\DocumentResource($this->documents->whereIn('document_type', DocumentType::IDENTIFICATION_DOCUMENTS)->sortByDesc('created_at')->first()),
            'bookings' => $this->whenLoaded('bookings', $this->bookings()->orderBy('id', 'DESC')->get(), []),
            'confirmed_bookings' => $this->bookings()->whereHas('transactions', function ($query){
                $query->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
            })->count(),
            'total_payments' => (float) $totalPayments,
            'average_spending_per_day' => (float) $totalPayments / ($this->created_at->diff(Carbon::now())->days === 0 ? 1 : $this->created_at->diff(Carbon::now())->days),
            'average_spending_per_booking' => (float) $totalPayments > 0 ? $totalPayments / $this->bookings()->whereHas('transactions', function ($query){
                $query->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
                })->count() : $totalPayments,
            'last_payment' => $lastPayment ? $lastPayment->created_at->diffForHumans() : 'No Payments',
            'personal_banks' => V1\BankResource::collection($this->banks->where('type', BankAccountType::PERSONAL)),
            'recipient_banks' => [
                'accounts' => V1\BankResource::collection($this->banks->where('type', BankAccountType::EXTERNAL)->whereIn('creator_type', [null])),
                'default' => new V1\BankResource($this->banks->where('type', BankAccountType::EXTERNAL)->where('default', true)->first())
            ],
            'segments' => V1\SegmentResource::collection($this->segments),
            'seasonalSegment' => $this->whenLoaded('seasonalSegments', V1\SeasonalSegmentResource::collection($this->seasonalSegments)),
            'services' => (new FetchesCompanyServices())->getServices($this->servicesConfigurations()),
            'wallet' => $this->whenLoaded('wallets', new V1\WalletResource($this->wallets()->with('transactions')->first()), new V1\WalletResource($this->wallets()->first())),
            'created_at' => $this->created_at->format('d-m-Y'),
            $this->mergeWhen($this->business_type === BusinessType::CURRENCY_VENDOR, [
                'currencies' => $segment ? V1\CurrencyResource::collection(Currency::whereIn('id', $segment->detail->currencies)->get()) : [],
                'service_charge' => $serviceCharge
            ])

        ];
    }
}
