<?php

namespace App\Classes\Modules\Exports\Services;

use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\KVPKey;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Models\Booking;
use App\Models\Transaction;
use App\Models\Wallet;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class ExportsReceivePaymentForBookingReport implements FromQuery, WithHeadings, WithHeadingRow, WithMapping, ShouldAutoSize
{
    use Exportable;

    protected $startDate;
    protected $endDate;

    public function __construct($startDate = null, $endDate = null) {
        $this->startDate = $startDate ? Carbon::parse($startDate)->startOfDay() : Carbon::now()->subMonths(1);
        $this->endDate = $endDate ? Carbon::parse($endDate)->endOfDay() : Carbon::now();
    }

    public function headings(): array
    {
        return [
            'DocNo',
            'Docdate',
            'DebtorCode',
            'Description',
            'DeptNo',
            'PaymentMethod',
            'PaymentAmt',
            'KnockOffDocType',
            'KnockOffDocNo',
            'KnockOffAmt',
        ];
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function query()
    {
        $type = TransactionType::PAYMENT;
        $query = Transaction::query();
        // $query->where('owner_type', '!=', Wallet::class);
        $query->where('type', $type);
        $query->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
        $query->whereBetween('created_at', [$this->startDate, $this->endDate]);

        return $query;
    }

    /**
     * @param Transaction $transaction
     * @return array
     */
    public function map($transaction): array
    {
        $autoCountSalesInvoiceId = null;
        $formattedDocumentDate = Carbon::parse($transaction->created_at)->format('m/d/Y');
        $owner  = $transaction->owner;
        $booking = null;
        if($owner instanceof Booking){
            $booking = $owner;
            $company = $booking->company;
        }
        else{
            $company = $owner->owner;
        }

        if($booking){
            $invoiceTransaction = $booking->transactions->where('type', TransactionType::INVOICE)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->first();
            if($invoiceTransaction){
                $invoiceTransactionKVP = $invoiceTransaction->attributesKVP()->where('key', KVPKey::AUTOCOUNT_DOCNO_INVOICE)->first();
                if($invoiceTransactionKVP){
                    $autoCountSalesInvoiceId = $invoiceTransactionKVP->value;
                }
                else {
                    $metadata = $booking->attributesKVP()->where('key', KVPKey::AUTOCOUNT_DOCNO_INVOICE)->first();
                    if($metadata){
                        $autoCountSalesInvoiceId = $metadata->value;
                    }
                }
            }
        }

        if($transaction->payment_method == PaymentMethodType::WALLET){
            if($owner instanceof Wallet){
                return[];
            }
        }

        return [
            '<<New>>',                                          //DocNo
            $formattedDocumentDate,                             //DocDate
            $company ? $company->debtor : '',                   //DebtorCode
            'Payment for ' . $autoCountSalesInvoiceId ?? '',    //Description
            'C',                                                //DeptNo
            'SALES DEPOSIT - EXC',                              //PaymentMethod
            number_format($transaction->amount, 2),             //PaymentAmt
            'RI',                                               //KnockOffDocType
            $autoCountSalesInvoiceId ?? '',                     //KnockOffDocNo
            number_format($transaction->amount, 2),             //KnockOffAmt
        ];
    }
}
