<?php

class IDebo_model extends Databases {

    private $db = DB_NAME_HEAD;
    protected $token = false;

    public function logthis($local, $tipo, $msg_err, $msg_otro) {
//        return $local . ' ' . $tipo . ' ' . $msg_err . ' ' . $msg_otro;
        if (!is_dir("Log/IDebo/")) {
            mkdir("Log/IDebo/");
        }
        $file = "" . $tipo . "_" . $local . "-" . date('Ymd H') . ".log";
        if ($fd = fopen("Log/IDebo/" . $file . "", 'a+')) {
            fwrite($fd, "FECHA:" . date('Y-m-d H:i:s') . "\n");
            fwrite($fd, "LOCAL:" . $local . "\n" . $msg_otro . "\n");
            fclose($fd);
        }
        parent::query("INSERT INTO IDEBO_LOGS (EMP, TIPO, FECHA, ERR, ARCHIVO) VALUES ($local, '$tipo', '" . date('Ymd H:i:s') . "', '$msg_err','$file')");
    }

    public function sendVersion($local, $version, $fecha) {
        $data = parent::query("SELECT EMP FROM LOCALES_VERSIONES WHERE EMP=$local AND FACT='$fecha'");
        if (!($data && count($data) > 0)) {
            $data = parent::query("INSERT INTO LOCALES_VERSIONES (EMP, FACT, VERSION) VALUES ($local, '$fecha', '$version')");
        }
        return;
    }

    public function getNHA($local, $estado) {
        $sql = "SELECT NHA,SEC,COD,DET FROM " . $this->db . ".dbo.ART_CUE WHERE EMP=$local AND NHA=$estado";
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            foreach ($data as $k => $v) {
                $data[$k]['DET'] = utf8_encode($v['DET']);
            }

            return $data;
        } else {
            return FALSE;
        }
    }

    public function updateHD($local, $articulos) {
        set_time_limit(0);
        if (count($articulos) > 0) {
            $msg = "";
            foreach ($articulos as $art) {
                parent::query("UPDATE " . $this->db . ".dbo.ART_CUE SET E_HD='', C_HD='H' WHERE EMP=$local AND SEC=" . $art['SEC'] . " AND COD=" . $art['COD']);
                $msg .= "El artículo " . $art['SEC'] . "-" . $art['COD'] . " se actualizó para que viaje\n";
            }

            $this->logthis($local, 'ART_NE', '', $msg);
        }
    }

    public function updateHDplanillaCosto($local, $articulos) {
        set_time_limit(0);
        if (count($articulos) > 0) {
            $msg = "";
            foreach ($articulos as $art) {
                parent::query("UPDATE " . $this->db . ".dbo.PLANILLA_COSTO SET E_HD='', C_HD='H' WHERE SEC=" . $art['SEC'] . " AND COD=" . $art['COD']);
                $msg .= "El artículo " . $art['SEC'] . "-" . $art['COD'] . " se actualizó en planilla costo para que viaje\n";
            }

            $this->logthis($local, 'ART_PRECIO', '', $msg);
        }
    }

    public function getPrecios($local, $fechaPdv) {
        $diffFec = abs(strtotime(date('Y-m-d H:i')) - strtotime($fechaPdv));
        $diffFec = round($diffFec / 60);
        if ($diffFec > 5) {
            $this->logthis($local, 'HORA', "Se encontró diferencia de hora en $diffFec minutos", '');
        }
        $sql = "SELECT SEC,COD,FECHA,HORA,IMI,COSTO,PRECIO_1,PRECIO_2,PRECIO_3 FROM " . $this->db . ".dbo.PLANILLA_COSTO_1 WHERE ZONAPRECIO=1 AND C_HD!='T'";
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            return $data;
        } else {
            return FALSE;
        }
    }

    public function getListasV14($listaId) {
        $sql = "SELECT * FROM " . $this->db . ".dbo.LISTA_PRECIO WHERE ID=" . $listaId . "";
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            return $data;
        } else {
            return FALSE;
        }
    }

    public function getListasV14All() {
        $sql = "SELECT * FROM " . $this->db . ".dbo.LISTA_PRECIO";
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            return $data;
        } else {
            return FALSE;
        }
    }

    public function getListasDetV14($listaId) {
        $sql = "SELECT ID,SEC,ART,PRECIO FROM " . $this->db . ".dbo.LISTA_PRECIO_DET WHERE ID=" . $listaId . "";
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            return $data;
        } else {
            return FALSE;
        }
    }

    public function getArtsByListaV14($listaId, $fechaPdv) {
        $diffFec = abs(strtotime(date('Y-m-d H:i')) - strtotime($fechaPdv));
        $diffFec = round($diffFec / 60);
        if ($diffFec > 5) {
            $this->logthis(0, 'HORA', "Se encontró diferencia de hora en $diffFec minutos", '');
        }
        $sql = "SELECT ID,SEC,ART,PRECIO,FECHA,HORA,C_HD FROM " . $this->db . ".dbo.LISTA_PRECIO_DET WHERE C_HD!='T' AND ID=" . $listaId . "";
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            return $data;
        } else {
            return FALSE;
        }
    }

    public function getBarras() {
        $sql = "SELECT SEC,ART,REPLACE(COD,' ','') AS COD FROM " . $this->db . ".dbo.CODBAR group by SEC,ART,REPLACE(COD,' ','')";
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            return $data;
        } else {
            return FALSE;
        }
    }

    public function checkStatusBarras($cuenta) {
        $sql = "Select count(SEC) as cuenta from " . $this->db . ".dbo.CODBAR";
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            $data = $data[0]['cuenta'];
            if ($data == $cuenta) {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            return FALSE;
        }
    }

    public function getSaldos($empresa, $fecha_retardo) {
        if ($fecha_retardo == '') {
            $sql = ("select CLI, COUNT(1)AS CANTIDAD,sum(ipa) as SUMA "
                    . "from " . $this->db . ".dbo.acobypag "
                    . "where EMP=" . $empresa . ""
                    . " and tco not in ('rc') group by CLI  order by CLI asc");
        } else {
            $sql = ("select CLI, COUNT(1)AS CANTIDAD, sum(ipa) as SUMA "
                    . "from " . $this->db . ".dbo.acobypag "
                    . "where EMP=" . $empresa . ""
                    . "and FEP<='$fecha_retardo'" // LE AGREGUE PARA VERIFICAR CON FECHA
                    . " and tco not in ('rc') group by CLI  order by CLI asc");
        }
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            return $data;
        } else {
            return false;
        }
    }

    public function getComprobantesGroup($emp, $cli, $retardo) {
        if ($retardo == '') {
            $sql = ("select TCO, COUNT(1) cant "
                    . "from " . $this->db . ".dbo.acobypag "
                    . "where EMP=" . $emp . ""
                    . " and CLI=$cli and tco not in ('rc') group by TCO");
        } else {
            $sql = ("select TCO, COUNT(1) cant "
                    . "from " . $this->db . ".dbo.acobypag "
                    . "where EMP=" . $emp . ""
                    . "and FEP<='$retardo'" // LE AGREGUE PARA VERIFICAR CON FECHA
                    . " and CLI=$cli and tco not in ('rc') group by TCO");
        }
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            return $data;
        } else {
            return false;
        }
    }

    function getSaldo($emp, $id_cliente) {
        $res_ale = parent::query("SELECT MCC FROM " . $this->db . ".dbo.CLIENTES WHERE COD=$id_cliente");
        $cliente_max = $res_ale[0]['MCC'];
        $fecha_actual = date("Ymd");

        $res_r = parent::query("
    (SELECT 'R' AS TIP,SUM(IPA) AS IMP FROM " . $this->db . ".dbo.ACOBYPAG WHERE CONVERT(CHAR(10),FEP,111) <= '" . $fecha_actual . "' AND
    TCO = 'RE' AND  REC = 0  AND ANU <> 'A'  AND CLI = " . $id_cliente . " )");

        $res_d = parent::query("(SELECT 'D' AS TIP,SUM(IPA) AS IMP FROM " . $this->db . ".dbo.ACOBYPAG
    WHERE CONVERT(CHAR(10),FEP,111) <= '" . $fecha_actual . "' AND  TCO IN('FT','ND','CI','DI','SA','AN') 
    AND  ANU <> 'A' AND NOT (TCO IN('FT','ND','CI','DI','SA','AN') AND FPA <> 2)   AND CLI = " . $id_cliente . " )");

        $res_a = parent::query("
    (SELECT 'A' AS TIP,SUM(SAL) AS IMP FROM " . $this->db . ".dbo.ACOBYPAG WHERE CONVERT(CHAR(10),FEP,111) <= '" . $fecha_actual . "'
    AND  TCO = 'AC'  AND  ANU <> 'A'  AND CLI = " . $id_cliente . " )");

        $res_p = parent::query("
    (SELECT 'P' AS TIP,SUM(IPA) AS IMP FROM " . $this->db . ".dbo.ACOBYPAG WHERE CONVERT(CHAR(10),FEP,111) <= '" . $fecha_actual . "'
    AND  TCO IN('RC','NC','NI')  AND  ANU <> 'A' AND NOT (TCO IN('NC','NI') AND FPA <> 2)   AND CLI = " . $id_cliente . " )
    ");
        $res_tm = 0;

        $res = (!is_nan($res_r[0]['IMP']) ? $res_r[0]['IMP'] : 0 ) + (!is_nan($res_d[0]['IMP']) ? $res_d[0]['IMP'] : 0 ) + (isset($res_tm[0]['TOTAL']) ? $res_tm[0]['TOTAL'] : 0 );
        $sum = (!is_nan($res_a[0]['IMP']) ? $res_a[0]['IMP'] : 0 ) + (!is_nan($res_p[0]['IMP']) ? $res_p[0]['IMP'] : 0 );

        $ret['cc'] = array(
            'res_R' => $res_r[0]['IMP'],
            'res_d' => $res_d[0]['IMP'],
            'res_a' => $res_a[0]['IMP'],
            'res_p' => $res_p[0]['IMP'],
            'autorizado' => $cliente_max,
            'resta' => $res,
            'suma' => $sum,
            'pend' => ( isset($res_tm[0]['PEND']) ? $res_tm[0]['PEND'] : 0 )
        );

        $clientes[0]["ARR_SALDO"] = $ret['cc'];
        $clientes[0]["SALDO"] = ($res - $sum); //$autorizado - ($resta - $suma)

        return $clientes;
    }

    public function getAdicionales($emp) {
        $sql = "select SEC,ART,ASEC,AART from " . $this->db . ".dbo.art_adicionales where EMP=" . $emp . "";
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            return $data;
        } else {
            return false;
        }
    }

    public function checkPrioridad($emp) {
        $newData = array();
        $sql = "select * from IDEBO_SETTINGS where EMP=" . $emp . "";
        $data = parent::query($sql);
        if ($data && count($data) > 0) {
            foreach ($data as $value) {
                if ($value['FUNCION_ID'] != '0') {
                    $value['FUNCION_ID'] = explode(',', $value['FUNCION_ID']);
                    $newData[] = $value;
                } else {
                    return false;
                }
            }
            if ($newData[0]['FUNCION_ID'] && count($newData[0]['FUNCION_ID']) > 0) {
                $arrayOrden = array();
                foreach ($newData[0]['FUNCION_ID'] as $value) {
                    $sql = "select funcion from IDEBO_FUNCIONES where ID=" . $value . "";
                    $data = parent::query($sql);
                    $arrayOrden[] = $data[0]['funcion'];
                }
            } else {
                return false;
            }
            return $arrayOrden;
        } else {
            return false;
        }
    }

    public function deletePrioridad($emp) {
        $sql = "delete from IDEBO_SETTINGS where EMP=" . $emp . "";
        $data = parent::query($sql);
        return $data;
    }

    public function checkFunciones() {
        $sql = "select FUNCION from IDEBO_FUNCIONES where HAB=1";
        $data = parent::query($sql);
        foreach ($data as $value) {
            $arrayOrden[] = $value['FUNCION'];
        }
        return $arrayOrden;
    }

    public function setVerazConsultas($persona,$emp) {
        $sql = "SELECT DOC FROM " . $this->db . ".dbo.VERAZ_CONSULTAS WHERE DOC=" . $persona['DOC'] . " AND EMP=".$emp;
        $data = parent::query($sql);
        $arr = $persona;
        $arr['FECHA_NACIMIENTO'] = str_replace('-', '', $persona['FECHA_NACIMIENTO']->date);
        $arr['FECHA_CONSULTA'] = str_replace('-', '', $persona['FECHA_CONSULTA']->date);
        $arr['EMP'] = $emp;
        unset($arr['C_HD']);
        unset($arr['E_HD']);
        if ($data && count($data) > 0) {
            parent::update($this->db . ".dbo.veraz_consultas", $arr, "DOC=" . $persona['DOC'] . " AND EMP=".$emp);
            $data = parent::query($sql);
            return true;
        } else {
            $arr['C_HD'] = '';
            $arr['E_HD'] = date('Ymd');
            parent::insert($this->db . ".dbo.veraz_consultas", $arr);
            return TRUE;
        }
    }

}
