<?php

namespace App\Exports;

use App\Models\Invoice as ModelsInvoice;
use Maatwebsite\Excel\Concerns\FromView;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class ExportARItemDetail implements FromView, ShouldAutoSize, WithEvents, WithColumnFormatting
{
    /**
     * @return \Illuminate\Support\Collection
     */
    private $arinvoices;
    public $type;
    public $startDate;
    public $endDate;
    public $checkboxes = [];
    public $UDF;
    public $selectFields = [];

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                $lastColumn = $event->sheet->getHighestColumn();
                $lastRow = $event->sheet->getHighestRow();

                $range = 'C3:' . $lastColumn . $lastRow;
                $rangel = 'L3:' . $lastColumn . $lastRow;
                $rangem = 'M3:' . $lastColumn . $lastRow;
                $rangen = 'N3:' . $lastColumn . $lastRow;

                $event->sheet->getStyle($range)->applyFromArray([
                    'borders' => [
                        'allBorders' => [
                            'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                            'color' => ['argb' => '#000000'],
                        ],
                    ],
                ]);

                $event->sheet->getStyle($rangel)
                    ->getNumberFormat()
                    ->setFormatCode(NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
                $event->sheet->getStyle($rangem)
                    ->getNumberFormat()
                    ->setFormatCode(NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
                $event->sheet->getStyle($rangen)
                    ->getNumberFormat()
                    ->setFormatCode(NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
            }
        ];
    }

    public function __construct($data)
    {
        $this->type = $data['type'];
        $this->startDate = $data['startDate'];
        $this->endDate = $data['endDate'];
        $this->checkboxes = $data['checkboxes'];
        $this->arinvoices = ModelsInvoice::with('detailInvoices.item')
            ->where(function ($query) {
                $startDate = $this->startDate ?? now()->format('Y-m-d');
                $endDate = $this->endDate ?? now()->format('Y-m-d');

                if ($startDate === $endDate) {
                    $query->whereDate('created_at', '=', $startDate);
                } else {
                    $endDate = date('Y-m-d 23:59:59', strtotime($endDate));

                    $query->whereBetween('created_at', [$startDate, $endDate]);
                }

                if ($this->type === 'BJ') {
                    $query->whereNull('no_inv');
                } elseif ($this->type === 'RS') {
                    $query->whereNotNull('no_inv');
                }
                $selectedCardCodes = array_keys(array_filter($this->checkboxes));
                if (!empty($selectedCardCodes)) {
                    $query->whereIn('Luv2_invoice.cardcode', $selectedCardCodes);
                }
            })
            ->orderByDesc('created_at')
            ->get();

        $fields = DB::getSchemaBuilder()->getColumnListing('Luv2_item');

        $this->selectFields = [];

        foreach ($fields as $field) {
            if (strpos($field, 'U_') === 0) {
                $this->selectFields[] = $field;
            }
        }

        if (!empty($selectFields)) {
            $this->UDF = false;
        } else {
            $this->UDF = true;
        }

        
    }

    public function columnFormats(): array
    {
        return [
            'D' => NumberFormat::FORMAT_DATE_DDMMYYYY,
        ];
    }

    public function view(): View
    {
        return view('export.tablearitemdetail', [
            'arinvoices' => $this->arinvoices,
            'udf' => $this->UDF,
            'field' => $this->selectFields,
        ]);
    }
}
