<?php

namespace FacturaScripts\Plugins\Partes\Model;

use FacturaScripts\Core\Model\Base\ModelClass;
use FacturaScripts\Core\Model\Base\ModelTrait;
use FacturaScripts\Core\Session;
use FacturaScripts\Core\Base\DataBase\DataBaseWhere;
use FacturaScripts\Dinamic\Model\User;
use FacturaScripts\Plugins\Partes\Model\OIFichajes;

class OIOperarioTarea extends ModelClass
{
    use ModelTrait;

    /** @var string */
    public $creationdate;

    /** @var float */
    public $horas;

    /** @var float */
    public $coste_hora;

    /** @var float */
    public $total;

    /** @var int */
    public $id;

    /** @var int */
    public $idtarea;

    /** @var string */
    public $lastnick;

    /** @var string */
    public $lastupdate;

    /** @var string */
    public $nick;

    /** @var string|null */
    public $nombretarea;

    /** @var string|null */
    public $nombreparte;

    /** @var int|null */
    public $idproyecto;

    /** @var string|null */
    public $responsable;

    public function clear()
    {
        parent::clear();
        $this->creationdate = date(self::DATETIME_STYLE);
        $this->horas = 0.0;
        $this->coste_hora = 0.0;
        $this->total = 0.0;
        $this->nick = Session::get('user')->nick ?? null;
        $this->idproyecto = null;
        $this->responsable = null;
        $this->nombretarea = null;
        $this->nombreparte = null;
    }

    public static function primaryColumn(): string
    {
        return "id";
    }

    public static function tableName(): string
    {
        return "oi_operarios_tareas";
    }

    public function test(): bool
    {
        $this->lastnick = $this->toolBox()->utils()->noHtml($this->lastnick);
        $this->nick = $this->toolBox()->utils()->noHtml($this->nick);
        return parent::test();
    }

    protected function updateTotals(): void
    {
        $this->coste_hora = 0.0;
        $this->total = 0.0;
        $this->horas = 0.0;
        if (empty($this->nick) || empty($this->idtarea)) {
            return;
        }

        // Sum hours and totals from time logs associated with this task and user
        $where = [
            new DataBaseWhere('nick', $this->nick),
            new DataBaseWhere('idtarea', $this->idtarea),
        ];
        $fichajes = new OIFichajes();
        foreach ($fichajes->all($where) as $fichaje) {
            $this->horas += (float) $fichaje->horas;
            $this->total += (float) $fichaje->total;
        }

        if ($this->horas > 0) {
            $this->coste_hora = $this->total / $this->horas;
        }
    }

    protected function saveInsert(array $values = []): bool
    {
        $this->lastupdate = null;
        $this->lastnick = null;
        $this->updateTotals();
        return parent::saveInsert($values);
    }

    protected function saveUpdate(array $values = []): bool
    {
        $this->lastupdate = date(self::DATETIME_STYLE);
        $this->lastnick = Session::get('user')->nick ?? null;
        $this->updateTotals();
        return parent::saveUpdate($values);
    }



	public function saveNewOperarioSubTask($subtask)
	{
		$operario  = $subtask['operarios'];

		$idtarea = $subtask['idtarea'];

		$operarioSubTarea = new $this();
		$where = [new DataBaseWhere('idtarea', $idtarea)];
		$operarioSubTarea = $operarioSubTarea->all($where);

		// En las subtareas solo guardamos 1 operario
		if(count($operarioSubTarea) > 0){
			$operarioSubTarea = $operarioSubTarea[0];
			$operarioSubTarea->lastnick = $operario;

			if($operario == ""){
				$operarioSubTarea->delete();
				return;
			}

		}else{
			$operarioSubTarea = new $this();
			$operarioSubTarea->lastnick = "";
			if($operario == ""){
				return;
			}
		}

		$operarioSubTarea->horas = 1;
		$operarioSubTarea->idtarea = $idtarea;
		$operarioSubTarea->lastupdate = date("d-m-Y H:i:s");
		$operarioSubTarea->nick = $operario;
		$operarioSubTarea->save();
	}


        public function loadByIDTarea($idtarea)
        {
                return $this->all([
                        new DataBaseWhere('idtarea', $idtarea)
                ]);
        }

    public function url(string $type = 'auto', string $list = 'List'): string
    {
        return $type === 'list'
            ? 'ListProyecto#ListOIOperarioTarea'
            : parent::url($type, $list);
    }

}
