<?php

namespace App\Core;

/**
 * Single source of truth for how Scheduling KPI fields are labeled and
 * grouped for display. Used by the record detail page, the review queue,
 * and the CSV/Excel/PDF exports, so every place a KPI record is shown uses
 * the exact same field names and ordering as the entry form.
 */
class KpiFieldLabels
{
    /**
     * Ordered groups of [column => label], mirroring the sections on the
     * Weekly KPI entry form. This order is used everywhere records are
     * displayed or exported in full.
     */
    public static function groups(): array
    {
        return [
            'Submission' => [
                'submitter_name' => 'Submitted By',
                'week_ending'    => 'Week Ending',
                'status'         => 'Status',
            ],
            'Hours' => [
                'total_hours'     => 'Total Hours',
                'static_hours'    => 'Static Hours',
                'patrol_hours'    => 'Patrol Hours',
                'event_hours'     => 'Event Hours',
                'ot_hours'        => 'OT Hours',
                'ot_pct'          => 'OT %',
                'dt_hours'        => 'DT Hours',
                'dt_pct'          => 'DT %',
                'open_post_hours' => 'Open Post Hours',
                'ot_notes'        => 'OT Hours — Notes',
            ],
            'Staffing' => [
                'new_hires'              => 'New Hires',
                'terminations'           => 'Terminations',
                'open_requisition_hours' => 'Open Requisition Hours',
                'open_sites'             => 'Open Sites',
                'coverage_notes'         => 'Coverage — Notes',
                'staffing_notes'         => 'Staffing — Notes',
            ],
            'Inspections & Incidents' => [
                'guard_inspections'    => 'Guard Inspections',
                'failed_inspections'   => 'Failed Inspections',
                'incidents'            => 'Incident Reports',
                'avg_response_hours'   => 'Avg Response Hours',
                'client_complaints'    => 'Client Complaints',
                'employee_complaints'  => 'Employee Complaints',
            ],
            'Time Off & Call-Offs' => [
                'pto_requests'    => 'Time Off Requests',
                'call_off_hours'  => 'Call-Off Hours',
                'time_off_notes'  => 'Time-Off Requests — Notes',
            ],
            'Scheduling & Audits' => [
                'scheduled_hours' => 'Hours on Scheduling',
                'audit_hours'     => 'Audit Hours',
            ],
            'Backup Employees for Weekend' => [
                'backup_employees' => 'Backup Employees',
            ],
            'Training' => [
                'cesar_training'         => 'Received Training from Cesar',
                'cesar_training_details' => 'Training Details',
            ],
            'Notes' => [
                'learning_development' => 'Learning & Development',
                'employee_concerns'    => 'Employee Concerns',
                'remarks'              => 'Remarks',
            ],
            'Review & Approval' => [
                'reviewer_name'  => 'Reviewed By',
                'review_comment' => 'Review Comment',
                'return_reason'  => 'Return Reason',
                'unlock_reason'  => 'Unlock Reason',
            ],
            'History' => [
                'submitted_at' => 'Submitted At',
                'reviewed_at'  => 'Reviewed At',
                'approved_at'  => 'Approved At',
                'returned_at'  => 'Returned At',
                'locked_at'    => 'Locked At',
                'created_at'   => 'Created At',
                'updated_at'   => 'Last Updated',
            ],
        ];
    }

    /** Flat column => label map, in display order, across all groups. */
    public static function flatLabels(): array
    {
        $out = [];
        foreach (self::groups() as $fields) {
            foreach ($fields as $col => $label) {
                $out[$col] = $label;
            }
        }
        return $out;
    }

    /** Human-readable rendering of a single field's raw value. */
    public static function formatValue(string $col, $value): string
    {
        if ($value === null || $value === '') return '—';

        if ($col === 'backup_employees') {
            $backups = json_decode((string)$value, true);
            if (!is_array($backups) || empty($backups)) return '—';
            $parts = [];
            foreach ($backups as $b) {
                $name  = $b['name'] ?? '';
                $days  = $b['days'] ?? '';
                $date  = $b['date'] ?? '';
                $parts[] = trim("{$name} ({$days})" . ($date ? " – {$date}" : ''));
            }
            return implode('; ', $parts);
        }

        if ($col === 'status') {
            return ucfirst((string)$value);
        }

        if (str_ends_with($col, '_pct') && is_numeric($value)) {
            return number_format((float)$value, 2) . '%';
        }

        return (string)$value;
    }

    /**
     * Turn one raw DB row (associative array of column => value) into an
     * ordered, human-labeled row: label => formatted value. This is the
     * single transform used by the CSV, Excel, and PDF exports so all three
     * always show identical fields in identical order.
     */
    public static function toLabeledRow(array $row): array
    {
        $out = [];
        foreach (self::flatLabels() as $col => $label) {
            if (!array_key_exists($col, $row)) continue;
            $out[$label] = self::formatValue($col, $row[$col]);
        }
        return $out;
    }
}
