<?php

namespace App\Exports\Sheets;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class SessionsSegmentsSheet implements FromCollection, WithHeadings, WithStyles, ShouldAutoSize, WithTitle
{
    public function __construct(private readonly Collection $sessions) {}

    public function title(): string
    {
        return 'Product Segments';
    }

    public function collection(): Collection
    {
        $rows = collect();

        foreach ($this->sessions as $session) {
            foreach ($session->segments as $idx => $seg) {
                $oee = $seg->calculateOee();
                $rows->push([
                    $session->id,
                    $session->operator->name ?? '—',
                    $idx + 1,
                    $seg->product_name ?? '—',
                    (int) ($seg->filling_rate ?? 0),
                    (int) ($seg->case_number ?? 0),
                    ((int)($seg->run_seconds ?? 0)) > 0 ? gmdate('H:i:s', $seg->run_seconds) : '—',
                    $oee > 0 ? $oee . '%' : '—',
                    $seg->started_at?->format('d/m/Y H:i:s') ?? '—',
                    $seg->ended_at?->format('d/m/Y H:i:s') ?? '—',
                    $seg->is_active ? 'Active' : 'Completed',
                ]);
            }
        }

        return $rows;
    }

    public function headings(): array
    {
        return [
            'Session #',
            'Operator',
            'Segment #',
            'Product',
            'Filling Rate (cases/hr)',
            'Cases',
            'Run Duration',
            'OEE %',
            'Start Time',
            'End Time',
            'State',
        ];
    }

    public function styles(Worksheet $sheet): array
    {
        return [
            1 => [
                'font' => ['bold' => true, 'color' => ['argb' => 'FFFFFFFF']],
                'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['argb' => 'FF007870']],
            ],
        ];
    }
}
