<?php

namespace FacturaScripts\Plugins\Partes\Controller;

use FacturaScripts\Core\Lib\ExtendedController\ListController;

class ListOiFichajes extends ListController
{
    public function getPageData(): array
    {
        $data = parent::getPageData();
        $data["menu"] = "";
        return $data;
    }

    protected function createViews()
    {
        $this->createViewsOIncidencia();
    }

    protected function createViewsOIncidencia(string $viewName = "ListOiFichajes")
    {
        $this->addView($viewName, 'OIFichajes', 'Fichajes');

        $this->addSearchFields($viewName, ['nick']);

        // default order, most recent first
        $this->addOrderBy($viewName, ['id'], 'id', 2);
    }

    protected function loadData($viewName, $view)
    {
        parent::loadData($viewName, $view);

        if ($viewName !== 'ListOiFichajes') {
            return;
        }

        $pageHours = 0.0;
        $pageTotal = 0.0;
        foreach ($view->cursor as $fichaje) {
            $pageHours += (float) $fichaje->horas;
            $pageTotal += isset($fichaje->total) ? (float) $fichaje->total : 0.0;
        }

        $totalHours = $view->model->totalSum('horas', $view->where);
        $totalAmount = $view->model->totalSum('total', $view->where);

        $view->totalAmounts = [
            'horas' => [
                'title' => 'horas',
                'page' => $pageHours,
                'total' => $totalHours,
            ],
            'precio-hora-medio' => [
                'title' => 'precio hora medio',
                'page' => $pageHours > 0 ? $pageTotal / $pageHours : 0.0,
                'total' => $totalHours > 0 ? $totalAmount / $totalHours : 0.0,
            ],
            'total' => [
                'title' => 'total',
                'page' => $pageTotal,
                'total' => $totalAmount,
            ],
        ];
    }
}
