<?php

namespace App\Exports;

use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithDrawings;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;

class SolicitudesDataSheet implements FromView, ShouldAutoSize, WithStyles, WithDrawings, WithTitle
{
    protected $solicitudes;

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

    public function title(): string
    {
        return 'Reporte Detallado';
    }

    public function view(): View
    {
        return view('reportes.excel', [
            'solicitudes' => $this->solicitudes
        ]);
    }

    public function styles(Worksheet $sheet)
    {
        $lastRow = $this->solicitudes->count() + 6; // Starts at row 6
        $moduloActivo = session('modulo_activo', 'tecnologia');
        $lastCol = ($moduloActivo === 'mantenimiento') ? 'P' : 'M';

        // Estilos para el encabezado (Título de la empresa)
        $sheet->getStyle('A1')->getFont()->setBold(true)->setSize(14)->getColor()->setARGB('0C782B');
        $sheet->getStyle('A1:A3')->getFont()->setBold(true);

        // Estilos para las cabeceras de la tabla
        $headerRange = 'A5:' . $lastCol . '5';
        $sheet->getStyle($headerRange)->applyFromArray([
            'font' => [
                'bold' => true,
                'color' => ['argb' => 'FFFFFF'],
            ],
            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => ['argb' => '0C782B'], // Verde institucional de Maderas del Orinoco
            ],
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['argb' => 'FFFFFF'],
                ],
            ],
        ]);

        // Estilos para el cuerpo de la tabla
        $bodyRange = 'A6:' . $lastCol . $lastRow;
        $sheet->getStyle($bodyRange)->applyFromArray([
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['argb' => 'CBD5E1'], // slate-300
                ],
            ],
        ]);

        return [];
    }

    public function drawings()
    {
        $drawing = new Drawing();
        $drawing->setName('Logo MDO');
        $drawing->setDescription('Logo Corporativo');
        $drawing->setPath(public_path('images/logoMDO.png'));
        $drawing->setHeight(80);
        $drawing->setCoordinates('D1'); // Posicionado a la derecha del título

        return $drawing;
    }
}
