<?php


namespace App\Classes\Modules\Transactions\ControllersLogic;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Classes\General\Abstracts\AbstractControllerLogic;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Http\Resources\PaymentTransactionResource;
use App\Models\Booking;
use App\Models\Company;
use App\Models\Transaction;
use App\Models\Wallet;

class FetchCompanyTransactionStatementLogic extends AbstractControllerLogic
{
    /**
     * @return array
     */
    protected function notification(): array
    {
        return [
            'title' => 'Retrieved Company Transaction Statement',
            'message' => 'You have successfully retrieved company transaction statement'
        ];
    }

    /**
     * FetchCompanyAccountBalanceLogic constructor.
     */
    public function __construct()
    {
    }

    public function logic(Request $request): JsonResponse
    {
        $companyId = $request->route('id');

        $transactions = Transaction::where(function ($query) use ($companyId) {
            $query
                ->where('type', TransactionType::PAYMENT)
                ->where('owner_type', Booking::class)
                ->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])
                ->whereHas('booking', function ($query) use ($companyId) {
                    $query->where('company_id', $companyId);
                });
            })
            ->orWhere(function ($query) use ($companyId) {
                $query->whereHas('owner', function ($query) use ($companyId) {
                    $query->where('owner_id', $companyId);
                    $query->where('owner_type', Company::class);
                })
                ->where('owner_type', Wallet::class)
                ->where('type', '!=', TransactionType::PAYMENT);
            })
            ->orWhere(function ($query) use ($companyId) {
                $query
                    ->where('type', TransactionType::INVOICE)
                    ->where('owner_type', Booking::class)
                    ->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])
                    ->whereHas('booking', function ($query) use ($companyId) {
                        $query->where('company_id', $companyId);
                });
            })
            ->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])
            ->orderBy('created_at', 'desc')
            ->get();

        return $this->collectionResponse(PaymentTransactionResource::collection($transactions));
    }
}
