<?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\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class SessionsSummarySheet implements FromCollection, WithHeadings, WithMapping, WithStyles, ShouldAutoSize, WithTitle
{
    public function __construct(
        private readonly Collection $sessions,
        private readonly string $periodLabel = ''
    ) {}

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

    public function collection(): Collection
    {
        return $this->sessions;
    }

    public function headings(): array
    {
        return [
            'Session #',
            'Date',
            'Operator',
            'Incharge',
            'Product',
            'Status',
            'Start Time',
            'Stop Time',
            'Total Duration',
            'Run Time',
            'Pause Duration',
            'Pauses',
            'Products Changed',
            'Total Cases',
            'Avg Filling Rate (cases/hr)',
            'OEE %',
            'Stop Reason',
        ];
    }

    public function map($session): array
    {
        $totalDur  = (int) ($session->total_duration ?? 0);
        $pauseDur  = (int) ($session->total_pause_duration ?? 0);
        $runSec    = max(0, $totalDur - $pauseDur);
        $oee       = $this->computeOee($session);
        $segCount  = $session->segments->count();
        $productsChanged = max(0, $segCount - 1);

        if ($segCount > 0) {
            $avgRate = (int) round($session->segments->avg('filling_rate'));
        } else {
            $avgRate = (int) ($session->filling_rate ?? 0);
        }

        return [
            $session->id,
            $session->start_time?->format('d/m/Y') ?? '—',
            $session->operator->name ?? '—',
            $session->incharge_name ?? '—',
            $session->product_name ?? '—',
            ucfirst($session->status),
            $session->start_time?->format('d/m/Y H:i:s') ?? '—',
            $session->stop_time?->format('d/m/Y H:i:s') ?? '—',
            $totalDur > 0 ? gmdate('H:i:s', $totalDur) : '—',
            $runSec   > 0 ? gmdate('H:i:s', $runSec)   : '—',
            $pauseDur > 0 ? gmdate('H:i:s', $pauseDur)  : '—',
            $session->pauses->count(),
            $productsChanged,
            (int) ($session->case_number ?? 0),
            $avgRate > 0 ? $avgRate : '—',
            $oee > 0 ? $oee . '%' : '—',
            $session->stop_reason ?? '—',
        ];
    }

    private function computeOee($session): float
    {
        if ($session->segments->count() > 0) {
            $totalExpected = 0;
            $totalCases    = 0;
            foreach ($session->segments as $seg) {
                $runHours       = ((int) ($seg->run_seconds ?? 0)) / 3600;
                $totalExpected += $runHours * ((int) ($seg->filling_rate ?? 0));
                $totalCases    += (int) ($seg->case_number ?? 0);
            }
            if ($totalExpected > 0 && $totalCases > 0) {
                return round(($totalCases / $totalExpected) * 100, 1);
            }
        } else {
            $runSec   = max(0, ((int) ($session->total_duration ?? 0)) - ((int) ($session->total_pause_duration ?? 0)));
            $runHours = $runSec / 3600;
            $expected = $runHours * ((int) ($session->filling_rate ?? 0));
            $cases    = (int) ($session->case_number ?? 0);
            if ($expected > 0 && $cases > 0) {
                return round(($cases / $expected) * 100, 1);
            }
        }
        return 0;
    }

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