<?php

namespace App\Classes\Modules\Exports\Services;

use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
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 ExportsSalesDepositByWallet3DepositEntry 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',
            'DepositPaymentMethod',
            'PaymentMethod',
            'PaymentAmt',
        ];
    }

    /**
     * @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
    {
        $formattedDocumentDate = Carbon::parse($transaction->created_at)->format('m/d/Y');
        $owner  = $transaction->owner;
        $company = $owner->owner;
        return [
            '<<New>>',                              //DocNo
            $formattedDocumentDate,                 //DocDate
            $company ? $company->debtor : '',       //DebtorCode
            $transaction->bill_no,                  //Description
            'C',                                    //DeptNo
            'SALES DEPOSIT - EXC',                  //DepositPaymentMethod
            'DEPOSIT IN TRANSIT',                   //PaymentMethod
            number_format($transaction->amount, 2), //PaymentAmt
        ];
    }
}
