<?php

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

class AreasManager {

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

        try {
            $q = sprintf("SELECT * FROM areas %s ORDER BY nombre_area", $restriction);
            $dao = new dbObject();
            $res = $dao->fetchQuery($q);
        } catch (Exception $e) {
            
        }
        return $res;
    }

    static function getAreaCoords($id_area) {
        $res = null;
        $restriction = sprintf("WHERE id_area=%d", $id_area);

        try {
            $q = sprintf("SELECT * FROM area_coords %s ORDER BY coord_index", $restriction);
            $dao = new dbObject();
            $res = $dao->fetchQuery($q);
        } catch (Exception $e) {
            
        }
        return $res;
    }

    static function saveArea($areaData) {
        $result = false;
        $dao = new dbObject();
        if (!$areaData['areaId']) {
            $q = sprintf("INSERT INTO areas (id_organizacion, nombre_area, superficie, id_color) values (%d,'%s',%s,%d)",
                    $areaData['orgId'], $areaData['nombre'], $areaData['superficie'], $areaData['color']);
            $dao->execute($q);
            $key = $dao->getAutoInc();
            if ($key) {
                $result = AreasManager::saveAreaCoords($key, $dao, $areaData['coords']);
            }
        } else {
            $q = sprintf("UPDATE areas set nombre_area = '%s', superficie=%d, id_color=%d WHERE id_area = %d", $areaData['nombre'], $areaData['superficie'], $areaData['color'], $areaData['areaId']);
            if($dao->execute($q)){
               $result = AreasManager::saveAreaCoords($areaData['areaId'], $dao, $areaData['coords']); 
            }
        }
        return $result;
    }

    static function saveAreaCoords($areaId, $dao, $coords) {
        $result = true;
        $q= sprintf("DELETE FROM area_coords WHERE id_area = %d",$areaId);
        $dao->execute($q);
        if (is_array($coords) && count($coords)) {
            foreach ($coords as $index => $coord) {
                $q = sprintf("INSERT INTO area_coords(id_area, coord_index, lng, lat) VALUES (%d,%d,%s,%s)", $areaId, $index, $coord[0], $coord[1]);
                $result = $dao->execute($q);
                if (!$result)
                    break;
            }
        }
        return $result;
    }

    static function delArea($areaData){
        $dao = new dbObject();
        $idArea = $areaData['id_area'];
        $q = sprintf("UPDATE areas SET activa=%d WHERE id_area = %d", 0, $idArea);
        $result = $dao->execute($q);
        return $result;
    }

}

?>