<?php

namespace App\Classes\Modules\Exports\Services;

use App\Models\Company;
use App\Models\Transaction;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Illuminate\Http\Request;
use Carbon\Carbon;

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

    private $request;

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

    public function headings(): array
    {
        return [
            'Ref No',
            'Creted Date',
            'Amount',
            'Rate',
            'Supplier'
        ];
    }

    /**
     * @return \Illuminate\Support\Collection|mixed
     */
    public function query()
    {
        $supplierIds = array_map(function($value){
            return ['id' => $value];
        }, json_decode($this->request->input('supplierIds')));

        $dateFrom =Carbon::parse($this->request->input('startDate'))->format('Y-m-d');
        $dateTo =Carbon::parse($this->request->input('endDate'))->format('Y-m-d');

        return Transaction::where('type', 3)->whereIn('issuer', $supplierIds)->whereBetween('created_at', [$dateFrom, $dateTo]);
    }

    /**
     * @param $transaction
     * @return array
     */
    public function map($transaction): array
    {
        $supplierName = Company::where('id', $transaction->issuer)->get()->first()->name;
        $refNo = $transaction->owner->owner == null ?  $transaction->owner->marking : $transaction->owner->owner->marking;
        
        $createdAt = $transaction->created_at->format('d-m-Y');
        $amount = $transaction->amount;
        $rate = $transaction->currency_rate;

        return [
            $refNo,
            $createdAt,
            $amount,
            $rate,
            $supplierName
        ];
    }
}