<?php

namespace App\Exports;

use App\Helpers\Helper;
use App\Models\Base\EmployeePayroll;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Events\BeforeExport;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class EmployeePayrollsExport implements FromCollection, WithMapping, WithHeadings, WithColumnFormatting, ShouldAutoSize, WithTitle, WithStrictNullComparison, WithEvents
{
    protected $request;
    private $list_status = [];
    private $document_type_code = 'employee.payroll';

    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->list_status = [
            EmployeePayroll::DRAFT => __('base/employee_payroll.text_status_draft'),
            EmployeePayroll::OPEN => __('base/employee_payroll.text_status_open'),
            EmployeePayroll::CANCEL => __('base/employee_payroll.text_status_cancel'),
        ];
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        if (empty($this->request->filter_date_payment_from)) {
            $this->request->request->add([
                'filter_date_payment_from' => Helper::date(\Date::parse('first day of this month')->subMonth())
            ]);
        }
        if (empty($this->request->filter_date_payment_to)) {
            $this->request->request->add([
                'filter_date_payment_to' => Helper::date(\Date::parse('last day of this month'))
            ]);
        }
        $this->request->request->add(['filter_document_type_code' => $this->document_type_code]); //Filtra tipo de documento
        return EmployeePayroll::filter($this->request->all())->sortable(['date_payment' => 'desc'])->get();
    }

    /**
     * @return string
     */
    public function title(): string
    {
        return __('base/employee_payroll.document_title');
    }

    /**
     * @return array
     */
    public function headings(): array
    {
        return [
            __('base/employee_payroll.column_serie'),
            __('base/employee_payroll.column_folio'),
            __('base/employee_payroll.column_date_payment'),
            __('base/employee_payroll.column_uuid'),
            __('base/employee.column_taxid'),
            __('base/employee_payroll.column_employee'),
            __('base/employee_payroll.column_branch_office'),
            __('base/employee_payroll.column_payroll_type'),
            __('base/employee_payroll.column_currency'),
            __('base/employee_payroll.column_amount_total'),
            __('base/employee_payroll.column_status'),
        ];
    }

    /**
     * @return array
     */
    public function map($row): array
    {
        return [
            $row->serie,
            $row->folio,
            \App\Helpers\Helper::date(\Date::parse($row->date_payment)),
            $row->employeePayrollCfdi->uuid ?? '',
            $row->employee->taxid,
            $row->employee->name,
            $row->branchOffice->name,
            $row->payrollType->name,
            $row->currency->code,
            $row->amount_total,
            $this->list_status[$row->status],
        ];
    }

    /**
     * @return array
     */
    public function columnFormats(): array
    {
        return [
            'J' => NumberFormat::FORMAT_CURRENCY_USD_SIMPLE,
        ];
    }

    /**
     * @return array
     */
    public function registerEvents(): array
    {
        return [
            BeforeExport::class => function (BeforeExport $event) {
                $event->getWriter()->getDelegate()
                    ->getProperties()
                    ->setCreator(config('app.name'))
                    ->setLastModifiedBy(config('app.name'))
                    ->setTitle(__('base/employee_payroll.document_title') . '-' . config('app.name'))
                    ->setDescription(
                        __('base/employee_payroll.document_title') . '-' . config('app.name')
                    );
            },
            // Array callable, refering to a static method.
            AfterSheet::class => [self::class, 'afterSheet'],

        ];
    }

    public static function AfterSheet(AfterSheet $event)
    {

        //Default

        //Titulo
        $title_cell_range = 'A1:K1';
        $title_style = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
            ],
            'font' => [
                'name' => 'Arial',
                'size' => 10,
                'bold' => true,
                'color' => ['argb' => '0A7864'],
            ],
            'borders' => [
                'bottom' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM,
                    'color' => ['argb' => 'C5DAD6'],
                ],
            ]
        ];
        $event->getDelegate()->getStyle($title_cell_range)->applyFromArray($title_style);
        $event->getDelegate()->getStyle($title_cell_range)->getFill()
            ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
            ->getStartColor()->setARGB('EEEEEE');
        $event->getDelegate()->getRowDimension('1')->setRowHeight(22);
        //$event->getDelegate()->getColumnDimension('B')->setWidth(50);

        //Ajuste otras columnas
        $style_center = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        $style_right = [
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT,
            ],
        ];
        $event->getDelegate()->getStyle('A2:A1000')->applyFromArray($style_center);
        $event->getDelegate()->getStyle('B2:B1000')->applyFromArray($style_center);
        $event->getDelegate()->getStyle('C2:C1000')->applyFromArray($style_center);
        $event->getDelegate()->getStyle('D2:D1000')->applyFromArray($style_center);
        $event->getDelegate()->getStyle('E2:E1000')->applyFromArray($style_center);
        $event->getDelegate()->getStyle('I2:I1000')->applyFromArray($style_center);
        $event->getDelegate()->getStyle('J2:J1000')->applyFromArray($style_right);
        $event->getDelegate()->getStyle('K2:K1000')->applyFromArray($style_center);

    }
}
