<?php

namespace App\Exports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Border;
use Maatwebsite\Excel\Concerns\WithColumnWidths;

class UsersExport implements FromCollection, WithHeadings, WithMapping, WithStyles, WithColumnWidths
{
    private $filters;

    public function __construct($filters = [])
    {
        $this->filters = $filters;
    }

    public function collection()
    {
        $query = User::with('roles');

        // Apply filters
        if (isset($this->filters['role']) && $this->filters['role']) {
            $query->whereHas('roles', function($q) {
                $q->where('name', $this->filters['role']);
            });
        }

        if (isset($this->filters['status']) && in_array($this->filters['status'], ['active', 'inactive'])) {
            $query->where('status', $this->filters['status'] === 'active');
        }

        return $query->get();
    }

    public function headings(): array
    {
        return [
            'ID',
            'Name',
            'Email',
            'Phone',
            'Roles',
            'Department',
            'Position',
            'Employee ID',
            'Status',
            'Created At',
            'Last Login',
        ];
    }

    public function map($user): array
    {
        return [
            $user->id,
            $user->name,
            $user->email,
            $user->phone ?? 'N/A',
            implode(', ', $user->role_names),
            $user->department ?? 'N/A',
            $user->position ?? 'N/A',
            $user->employee_id ?? 'N/A',
            $user->is_active ? 'Active' : 'Inactive',
            $user->created_at->format('Y-m-d H:i:s'),
            $user->last_login_at ? $user->last_login_at->format('Y-m-d H:i:s') : 'Never',
        ];
    }

    public function styles(Worksheet $sheet)
    {
        // Header style
        $sheet->getStyle('A1:K1')->applyFromArray([
            'font' => [
                'bold' => true,
                'color' => ['rgb' => 'FFFFFF']
            ],
            'fill' => [
                'fillType' => Fill::FILL_SOLID,
                'startColor' => ['rgb' => '3498db']
            ],
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['rgb' => '000000']
                ]
            ]
        ]);

        // Data rows style
        $lastRow = $sheet->getHighestRow();
        $sheet->getStyle("A2:K{$lastRow}")->applyFromArray([
            'borders' => [
                'allBorders' => [
                    'borderStyle' => Border::BORDER_THIN,
                    'color' => ['rgb' => 'dddddd']
                ]
            ]
        ]);

        // Alternate row coloring
        for ($row = 2; $row <= $lastRow; $row++) {
            if ($row % 2 == 0) {
                $sheet->getStyle("A{$row}:K{$row}")->applyFromArray([
                    'fill' => [
                        'fillType' => Fill::FILL_SOLID,
                        'startColor' => ['rgb' => 'f8f9fa']
                    ]
                ]);
            }
        }

        // Auto filter
        $sheet->setAutoFilter('A1:K1');
    }

    public function columnWidths(): array
    {
        return [
            'A' => 10, // ID
            'B' => 25, // Name
            'C' => 30, // Email
            'D' => 15, // Phone
            'E' => 20, // Roles
            'F' => 20, // Department
            'G' => 20, // Position
            'H' => 15, // Employee ID
            'I' => 10, // Status
            'J' => 20, // Created At
            'K' => 20, // Last Login
        ];
    }
}