<?php

namespace Modules\Operations\Controllers;

use App\Controllers\BaseController;
use App\Models\WorkOrderModel;

class OperationsDashboardController extends BaseController
{
    public function index()
    {
        $counts = (new WorkOrderModel())->countByStatus();

        $openTotal = $counts['draft'] + $counts['open'] + $counts['in_progress'] + $counts['on_hold'];

        $recent = (new WorkOrderModel())->scopeForList()
            ->orderBy('work_orders.id', 'DESC')
            ->findAll(8);

        $overdue = (new WorkOrderModel())
            ->whereIn('status', WorkOrderModel::OPEN_STATUSES)
            ->where('due_date IS NOT NULL')
            ->where('due_date <', date('Y-m-d'))
            ->countAllResults();

        return view('Modules\Operations\Views\dashboard\index', array_merge($this->baseViewData(), [
            'title'   => 'Operations Dashboard',
            'counts'  => $counts,
            'kpis'    => [
                [
                    'label'     => 'Open work orders',
                    'value'     => (string) $openTotal,
                    'icon'      => 'fa-clipboard-list',
                    'badge'     => 'Active',
                    'badgeType' => 'neutral',
                    'dept'      => 'Operations',
                ],
                [
                    'label'     => 'In progress',
                    'value'     => (string) $counts['in_progress'],
                    'icon'      => 'fa-play',
                    'badge'     => 'Live',
                    'badgeType' => 'positive',
                    'dept'      => 'Field',
                ],
                [
                    'label'     => 'Completed',
                    'value'     => (string) $counts['completed'],
                    'icon'      => 'fa-file-circle-check',
                    'badge'     => 'Closed',
                    'badgeType' => 'positive',
                    'dept'      => 'Reports',
                ],
                [
                    'label'     => 'Overdue',
                    'value'     => (string) $overdue,
                    'icon'      => 'fa-clock',
                    'badge'     => $overdue > 0 ? 'Attention' : 'Clear',
                    'badgeType' => $overdue > 0 ? 'negative' : 'neutral',
                    'dept'      => 'Due dates',
                ],
            ],
            'recent' => $recent,
        ]));
    }
}
