<?php

namespace App\Classes\Modules\Exports\Services;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
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 Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Classes\General\Eloquent\ApplyFiltersToQuery;
use App\Models\StatementTransaction;
use App\Models\Company;

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

    private $request;
    private $counter = 1;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    public function headings(): array
    {
        $header = [
            'DocNo',
            'DocDate',
            'DebtorCode',
            'Description',
            'DocNo2',
            'ProjNo',
            'DeptNo',
            'CurrencyCode',
            'ToHomeRate',
            'ToDebtorRate',
            'Note',
            'PaymentMethod',
            'ChequeNo',
            'PaymentAmt',
            'BankCharge',
            'ToBankRate',
            'BankChargeTaxType',
            'BankChargeTaxRefNo',
            'BankChargeProjNo',
            'BankChargeDeptNo',
            'PaymentBy',
            'FloatDay',
            'IsRCHQ',
            'RCHQDate',
            'KnockOffDocType',
            'KnockOffDocNo',
            'KnockOffAmt',
            '',
        ];
        return $header;
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function query()
    {
        $data = (new ApplyFiltersToQuery())->execute(StatementTransaction::query(), json_decode($this->request->input('filter'), true));
        if ($this->request->has('bankStatementTransactionId')) $data = $data->whereIn('id',json_decode($this->request->input('bankStatementTransactionId'), true));

        return $data;
    }

    /**
     * @param StatementTransaction $transaction
     *
     * @return array
     */
    public function map($transaction): array
    {
        $statementTransactionOwner = $transaction->owners()->whereIn('status', [ApprovalStatus::APPROVED])->first();
        $logArray = [
            'counter' => $this->counter,
            'system' => $statementTransactionOwner->system,
            'StatementTransactionOwner_id' => $statementTransactionOwner->id,
            'transaction_table_id' => $statementTransactionOwner->owner_id,
        ];
        $this->counter += 1;
        $logArray = json_encode($logArray);

        $filePath = storage_path('logs/exports_receipt_transactions.log');
        $errorFilePath = storage_path('logs/exports_receipt_transactions_error.log');
        $textToAppend = Carbon::now()->format('[Y-m-d H:i:s]') . ' ' . $logArray . PHP_EOL;
        file_put_contents($filePath, $textToAppend, FILE_APPEND);

        $company = Company::where('name',$transaction->transaction_description_2)->first();

        return [
            '<<New>>',
            Carbon::parse($transaction->posting_date)->format('d/m/Y'),
            ($company ? $company->debtor : null),
            $transaction->transaction_description,
            '',
            '',
            '',
            'MYR',
            1,
            1,
            '',
            'MBB',
            '',
            $transaction->amount,
            '',
            1,
            '',
            '',
            '',
            '',
            '',
            '0',
            '',
            '',
            'RI',
            $transaction->transaction_ref,
            $transaction->amount,
            '',
        ];
    }
}
