<?php

namespace App\Classes\Modules\Exports\Services;

use App\Classes\ValueObjects\Constants\BusinessType;
use App\Classes\ValueObjects\Constants\CompanyType;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;
use App\Models\Company;
use App\Models\Transaction;
use App\Models\Wallet;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;

class ExportsTransactions implements FromQuery, WithHeadingRow, WithMapping, ShouldAutoSize
{

    use Exportable;


    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function query()
    {
        return Transaction::whereIn('type', [TransactionType::PAYMENT, TransactionType::BILL])->where('owner_type', '!=',Wallet::class);
    }

    /**
     * @param $transaction
     * @return array
     */
    public function map($transaction): array
    {
        $transactionTypes = [
            0 => 'PAYMENT_ATTEMPT',
            1 => 'PAYMENT',
            2 => 'INVOICE',
            3 => 'BILL',
            4 => 'PROFORMA',
            5 => 'TOP_UP',
            6 => 'REFUND',
            7 => 'PURCHASE_ORDER',
            8 => 'SUPPLIER_DELIVER',
            9 => 'CREDIT_NOTE',
            10 => 'WITHDRAW',
            11 => 'DEBIT_NOTE',
            12 => 'TRANSFER_FEE'
        ];

        $transactionStatus = [
            0 => 'PENDING_SUBMISSION',
            1 => 'PENDING_VERIFICATION',
            2 => 'APPROVED',
            3 => 'COMPLETED',
            4 => 'REJECTED',
            5 => 'SUSPENDED',
            6 => 'EXPIRED'
        ];


        $booking = $transaction->owner;
        if(!($booking instanceof Booking)){
            $booking = $booking->owner;
        }

        $company = $booking->company;

        if(!$company instanceof Company) dd($transaction);

        return [
            $company->reference,
            $booking ? $booking->marking : '',
            $transaction->bill_no,
            $transaction->owner_id,
            $transaction->owner_type,
            $transactionTypes[$transaction->type],
            $transaction->issuerCompany->name,
            $transaction->reciver,
            $transaction->currency->short_code,
            $transaction->amount,
            $transaction->original_currency->short_code,
            $transaction->original_amount,
            $transaction->currency_rate,
            $transaction->tax,
            $transaction->service_charge,
            $transactionStatus[$transaction->status],
            \PhpOffice\PhpSpreadsheet\Shared\Date::dateTimeToExcel($transaction->created_at),
            \PhpOffice\PhpSpreadsheet\Shared\Date::dateTimeToExcel($transaction->updated_at),
//            $marking
        ];
    }
}
