<?php

namespace App\Classes\Modules\Exports\Services;

use App\Models\Order;
use App\Models\PackingList;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use App\Classes\General\Eloquent\ApplyFiltersToQuery;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use DateTime;

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

    private $filters;

    public function __construct()
    {
        $this->filters = [
            "has_invoice_status_in"                 => [2],
            "packing_list_ordered_by_invoice_date"  => true,
            "with_aging_column"                     => true
        ];
    }

    public function headings(): array
    {
        return [
            'Company Name',
            'Customer Marking',
            'Order Number',
            'Invoice No',
            'Invoice Date',
            'Days',
            'Amount',
        ];
    }

    public function query()
    {
        return (new ApplyFiltersToQuery())->execute(PackingList::query(), $this->filters);
    }

    public function map($list): array
    {
        $marking = null;
        $orderNo = null;
        $name    = null;
        $invDate = 'n/a';
        $invNo   = 'n/a';
        $days    = 'n/a';

        if ($list->owner instanceof Order) {
            $inviterPivotInviteeReference = $list->owner->companyModule->inviters()->withPivot('invitee_reference')->first();

            if ($inviterPivotInviteeReference) {
                $marking = $inviterPivotInviteeReference->pivot->invitee_reference;
                $orderNo = $list->owner->reference;
            }
            $name = $list->owner->companyModule->company->name;
        }

        $transaction = $list->transactions()->whereIn('status', [ApprovalStatus::APPROVED])->first();
        if ($transaction) {

            $invoiceDate = $transaction->created_at;
            $invDate     = date_format($invoiceDate, 'd-m-Y');
            $invNo       = $transaction->bill_no;
            $amt         = number_format($transaction->amount, 2);

            $currentDate = new DateTime();
            $interval    = $currentDate->diff($invoiceDate);
            $days        = $interval->format('%a');
        }

        return [
            $name,
            $marking,
            $orderNo,
            $invNo,
            $invDate,
            $days,
            $amt,
        ];
    }

    private function dueDateColumn($colNum, $dueDateNumber, $amt)
    {
        if ($colNum == $dueDateNumber) return $amt;
        return null;
    }
}
