<?php

namespace App\Controllers;

use App\Models\ActivityLogModel;
use App\Models\HousekeepingTaskModel;
use App\Models\MaintenanceWorkOrderModel;
use App\Models\PosOrderModel;
use App\Models\ShiftModel;
use App\Models\UserModel;
use Config\Lookups;

/**
 * Staff performance metrics — every figure here is a GROUP BY over data
 * this app is already writing for its own operational reasons
 * (housekeeping_tasks/maintenance_work_orders timestamps, activity_log
 * entries, pos_orders.opened_by, shifts.actual_hours). No new tracking,
 * no invented "performance score" — see the build plan's Phase 4 note.
 * Manager-only (same tier as Reports).
 */
class StaffPerformanceController extends BaseController
{
    public function index()
    {
        $from = $this->request->getGet('from') ?: date('Y-m-d', strtotime('-30 days'));
        $to   = $this->request->getGet('to') ?: date('Y-m-d');

        $staff = (new UserModel())->where('is_active', 1)->orderBy('full_name')->findAll();

        $housekeeping = (new HousekeepingTaskModel())->performanceByAssignee($from, $to);
        $maintenance  = (new MaintenanceWorkOrderModel())->resolvedCountByAssignee($from, $to);
        $bookings     = (new ActivityLogModel())->countByModuleAndPrefix('bookings', 'Booked room', $from, $to);
        $checkins     = (new ActivityLogModel())->countByModuleAndPrefix('checkin', 'Checked in', $from, $to);
        $fnbOrders    = (new PosOrderModel())->countByOpener($from, $to);
        $overtime     = (new ShiftModel())->overtimeByUser($from, $to);

        $rows = [];

        foreach ($staff as $s) {
            $rows[] = [
                'user'              => $s,
                'housekeepingCount' => $housekeeping[$s->id]['count'] ?? 0,
                'housekeepingAvgMinutes' => $housekeeping[$s->id]['avgMinutes'] ?? 0.0,
                'maintenanceResolved' => $maintenance[$s->id] ?? 0,
                'bookingsCreated'   => $bookings[$s->id] ?? 0,
                'checkinsProcessed' => $checkins[$s->id] ?? 0,
                'fnbOrders'         => $fnbOrders[$s->id] ?? 0,
                'overtimeHours'     => $overtime[$s->id] ?? 0.0,
            ];
        }

        // Staff with zero activity across every metric add noise, not
        // signal, to a date-ranged report — quietly drop them rather
        // than showing a wall of all-zero rows.
        $rows = array_values(array_filter($rows, static fn ($r) => $r['housekeepingCount'] || $r['maintenanceResolved'] || $r['bookingsCreated'] || $r['checkinsProcessed'] || $r['fnbOrders'] || $r['overtimeHours']));

        return view('reports/staff_performance', [
            'pageTitle' => 'Staff Performance',
            'from'      => $from,
            'to'        => $to,
            'rows'      => $rows,
            'lookups'   => new Lookups(),
        ]);
    }
}
