<?php
include_once("server/class/User.php");

class TareasManager {

    static function getTareas($user, $activeOnly = true) {
        $res = null;
        $restriction = sprintf("WHERE id_organizacion=%d", $user->getIdOrganizacion());
        $restriction .= ($activeOnly) ? " AND activa=1" : "";

        try {
            $q = sprintf("SELECT * FROM vista_tareas %s", $restriction);
            $dao = new dbObject();
            $res = $dao->fetchQuery($q);
            if (is_array($res) && count($res)) {
                foreach ($res as $i => $tarea) {
                    $qm = sprintf("SELECT * FROM tareas_units WHERE id_tarea = %d", $tarea['id_planificacion']);
                    $mmaq = $dao->fetchQuery($qm);
                    $maquinas = array();
                    if (is_array($mmaq) && count($mmaq)) {
                        foreach ($mmaq as $j => $maq) {
                            $maquinas[$j]['id_maquina'] = $maq['unit_id'];
                        }
                        $res[$i]['maquinas'] = $maquinas;
                    } else {
                        $res[$i]['maquinas'] = false;
                    }
                }
            }
        } catch (Exception $e) {
            
        }
        return $res;
    }

    static function saveTarea($tareaData) {
        $result = false;

        /*
          $rqData['idPlanificacion'] = (isset($data_back['json_data']['idPlanificacion']))?addslashes(($data_back['json_data']['idPlanificacion'])):null;
          $rqData['nombrePlanificacion'] = (isset($data_back['json_data']['nombrePlanificacion']))?addslashes(($data_back['json_data']['nombrePlanificacion'])):null;
          $rqData['inicioPrevisto'] = (isset($data_back['json_data']['inicioPrevisto']))?addslashes(($data_back['json_data']['inicioPrevisto'])):null;
          $rqData['finalPrevisto'] = (isset($data_back['json_data']['finalPrevisto']))?addslashes(($data_back['json_data']['finalPrevisto'])):null;
          $rqData['inicioReal'] = (isset($data_back['json_data']['inicioReal']))?addslashes(($data_back['json_data']['inicioReal'])):null;
          $rqData['finalReal'] = (isset($data_back['json_data']['finalReal']))?addslashes(($data_back['json_data']['finalReal'])):null;
          $rqData['area'] = (isset($data_back['json_data']['area']))?addslashes(($data_back['json_data']['area'])):null;
         */
        $dao = new dbObject();
        $idTarea = $tareaData['idPlanificacion'];
        try {
            if ($idTarea) {
                $q = sprintf("UPDATE tareas SET activa=1,nombre_tarea='%s', id_area=%d, inicio_prev=%d, fin_prev=%d, inicio=%d, fin=%d WHERE id_tarea = %d",
                        $tareaData['nombrePlanificacion'], $tareaData['area'], $tareaData['inicioPrevisto'], $tareaData['finalPrevisto'],
                        $tareaData['inicioReal'], $tareaData['finalReal'], $idTarea);
                $result = $dao->execute($q);
                $mQ = sprintf("DELETE FROM tareas_units WHERE id_tarea = %d", $idTarea);
                $dao->execute($mQ);
            } else {
                $q = sprintf("INSERT INTO tareas (nombre_tarea, id_area, inicio_prev, fin_prev, inicio, fin, activa) values ('%s',%d,%d,%d,%d,%d,1)",
                        $tareaData['nombrePlanificacion'], $tareaData['area'], $tareaData['inicioPrevisto'],
                        $tareaData['finalPrevisto'], $tareaData['inicioReal'], $tareaData['finalReal']);
                $result = $dao->execute($q);
                $idTarea = $dao->getAutoInc();
            }
            if (is_array($tareaData['maquinas']) && count($tareaData['maquinas'])) {
                foreach ($tareaData['maquinas'] as $tareaMaquina) {
                    $q = sprintf("INSERT INTO tareas_units (id_tarea,unit_id) VALUES (%d,'%s');", $idTarea, $tareaMaquina);
                    $dao->execute($q);
                }
            }
            return true;
        } catch (Exception $w) {
            return false;
        }

        return true;
    }

    static function delTarea($tareaData){
        $dao = new dbObject();
        $idTarea = $tareaData['id_tarea'];
        $q = sprintf("UPDATE tareas SET activa=%d WHERE id_tarea = %d", 0, $idTarea);
        $result = $dao->execute($q);
        return $result;
    }

    static function saveTareasMaquinas($id_tarea, $unit_id) {
        $q = sprintf("INSERT INTO tareas_maquinas (id_tarea, unit_id) values (%d, '%s')",
                $id_tarea, $unit_id);
        $dao = new dbObject();
        $result = $dao->execute($q);
        $key = $dao->getAutoInc();

        return $key;
    }

    static function getNewTareaId() {
        $dao = new dbObject();
        $q = "INSERT INTO tareas (activa) values (0);";
        $result = $dao->execute($q);
        $idTarea = $dao->getAutoInc();
        return $idTarea;
    }

    static function saveResource($resourceData){
        $dao=new dbObject();
        $q=sprintf("INSERT INTO recursos_de_tareas (id_tarea, id_recurso, cantidad_estimada, cantidad_efectiva) VALUES (%d,%d,'%s','%s') ON DUPLICATE KEY UPDATE cantidad_estimada='%s', cantidad_efectiva='%s';",$resourceData['id_planificacion'],$resourceData['idRecRen'], $resourceData['estimado'],$resourceData['real'], $resourceData['estimado'],$resourceData['real']);
        $res = $dao->execute($q);
        return $res;
    }

    static function delResource($resourceData){
        $dao = new dbObject();
        $idRecurso = $resourceData['id'];
        $q = sprintf("UPDATE recursos SET activo=%d WHERE id_recurso = %d", 0, $idRecurso);
        $result = $dao->execute($q);
        return $result;
    }

    static function saveResult($resourceData){      
        $dao=new dbObject();
        $q=sprintf("INSERT INTO rendimientos_de_tareas (id_tarea, id_rendimiento, cantidad_estimada, cantidad_efectiva) VALUES (%d,%d,'%s','%s') ON DUPLICATE KEY UPDATE cantidad_estimada='%s', cantidad_efectiva='%s';",$resourceData['id_planificacion'],$resourceData['idRecRen'], $resourceData['estimado'],$resourceData['real'], $resourceData['estimado'],$resourceData['real']);
        $res = $dao->execute($q);
        return $res;
    }

    static function delResult($resultData){
        $dao = new dbObject();
        $idResult = $resultData['id'];
        $q = sprintf("UPDATE rendimientos SET activo=%d WHERE id_rendimiento = %d", 0, $idResult);
        $result = $dao->execute($q);
        return $result;
    }

    static function getRecursosDeTarea($id_tarea){
        $q = sprintf("SELECT * FROM recursos_de_tareas frt 
        INNER JOIN recursos fr 
        ON (frt.id_recurso = fr.id_recurso) WHERE frt.id_tarea='%s'", $id_tarea);
        $dao = new dbObject();
        $res = $dao->fetchQuery($q);
        return $res;
    }

    static function getRecursosList($user, $activeOnly = true){
        $res = null;
        $restriction = sprintf("WHERE (id_organizacion=%d OR id_organizacion IS NULL)", $user->getIdOrganizacion());
        $restriction .= ($activeOnly) ? " AND activo=1" : "";

        $q = "SELECT * FROM recursos ".$restriction;
        $dao = new dbObject();
        $res = $dao->fetchQuery($q);
        return $res;
    }


    static function getRendimientosDeTarea($id_tarea){
        $q = sprintf("SELECT * FROM rendimientos_de_tareas frt 
        INNER JOIN rendimientos fr 
        ON (frt.id_rendimiento = fr.id_rendimiento) WHERE frt.id_tarea='%s'", $id_tarea);
        $dao = new dbObject();
        $res = $dao->fetchQuery($q);
        return $res;
    }

    static function getRendimientosList($user, $activeOnly = true){
        $res = null;
        $restriction = sprintf("WHERE (id_organizacion=%d OR id_organizacion IS NULL)", $user->getIdOrganizacion());
        $restriction .= ($activeOnly) ? " AND activo=1" : "";

        $q = "SELECT * FROM rendimientos ".$restriction;
        $dao = new dbObject();
        $res = $dao->fetchQuery($q);
        return $res;
    }

    static function saveGlobalResource($resourceData, $user){
        $resourceId = $resourceData['id'];
        if ($resourceId) {
            $dao = new dbObject();
            $q = sprintf("UPDATE recursos SET nombre_recurso='%s', unidad='%s', costo_usd='%s' WHERE id_recurso = %d",
                        $resourceData['nombre'], $resourceData['unidad'], $resourceData['costo'], $resourceId);

            $result = $dao->execute($q);
                
        }else{
            $dao=new dbObject();
            $q=sprintf("INSERT INTO recursos (nombre_recurso, unidad, activo, id_organizacion, costo_usd) VALUES ('%s','%s', %d, %d,'%s')", $resourceData['nombre'],$resourceData['unidad'], 1, $user->getIdOrganizacion(), $resourceData['costo']);
            $res = $dao->execute($q);
            return $res;
        }

        return $result;

    }

    static function saveGlobalResult($resourceData, $user){
        $resourceId = $resourceData['id'];
        if ($resourceId) {
            $dao = new dbObject();
            $q = sprintf("UPDATE rendimientos SET nombre_rendimiento='%s', unidad='%s', costo_usd='%s' WHERE id_rendimiento = %d",
                        $resourceData['nombre'], $resourceData['unidad'], $resourceData['costo'], $resourceId);

            $result = $dao->execute($q);
                
        }else{
            $dao=new dbObject();
            $q=sprintf("INSERT INTO rendimientos (nombre_rendimiento, unidad, activo, id_organizacion, costo_usd) VALUES ('%s','%s', %d, %d,'%s')", $resourceData['nombre'],$resourceData['unidad'], 1, $user->getIdOrganizacion(), $resourceData['costo']);
            $res = $dao->execute($q);
            return $res;
        }

        return $result;

    }


    
}

?>