<?php
require_once "BASEPATH.php";

class CampanasHome extends MY_Controller
{
    public function dameInfoCampa()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanashome', "spanish");
                break;
            case "en":
                $this->lang->load('campanashome', "english");
                break;
            default:
                $this->lang->load('campanashome', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $campa = limpia($_POST["campana"]);
            $lista = limpia($_POST["lista"]);
            $archived = false;
            if (isset($_POST["archived"]) && limpia($_POST["archived"]) == 1) {
                $archived = true;
            }

            if ($lista == -1) {
                $lista = "list_id";
            } else {
                $lista = "'$lista'";
            }
            $sal = array();
            $con = getConnection();
            $and = "AND campaign_id IN (SELECT campaign_id FROM vicidial_campaigns WHERE user_group = '" . $_SESSION["Cliente"] . "')";
            if ($_SESSION["Cliente"] == -1) {
                $and = "";
            }

            $query = "SELECT CONCAT(IF(HOUR(CURTIME())<10,CONCAT('0',HOUR(CURTIME())),HOUR(CURTIME())),':',IF(MINUTE(CURTIME())<10,CONCAT('0',MINUTE(CURTIME())),MINUTE(CURTIME()))) AS HORA,status,status_name FROM vicidial_statuses WHERE status IN ('DROP','PDROP','XDROP','NEW','QUEUE','INCALL','NA','AB','B','N','ADC') UNION SELECT CONCAT(IF(HOUR(CURTIME())<10,CONCAT('0',HOUR(CURTIME())),HOUR(CURTIME())),':',IF(MINUTE(CURTIME())<10,CONCAT('0',MINUTE(CURTIME())),MINUTE(CURTIME()))) AS HORA,status,status_name FROM vicidial_campaign_statuses WHERE selectable = 'Y' AND campaign_id = '$campa' $and";
            $result = sv_mysqli_query($con, $query);
            //echo($campa);
            //$sal["query"] = $query;
            $cual = 0;
            $query2 = "SELECT COUNT(uniqueid) AS CONTEO,status from vicidial_log WHERE campaign_id = '$campa' AND list_id = $lista AND list_id IN (SELECT list_id FROM vicidial_lists WHERE campaign_id = '$campa' AND active = 'Y') GROUP BY vicidial_log.status";
            if ($archived) {
                $query2 .= " UNION SELECT COUNT(uniqueid) AS CONTEO,status from vicidial_log_archive WHERE campaign_id = '$campa' AND list_id = $lista AND list_id IN (SELECT list_id FROM vicidial_lists WHERE campaign_id = '$campa' AND active = 'Y') GROUP BY vicidial_log_archive.status";
            }
            $query2 = "SELECT SUM(T.CONTEO) AS CONTEO, T.status FROM ($query2) AS T GROUP BY T.status";
            //$this->output->set_output($query2);
            $result2 = sv_mysqli_query($con, $query2);
            $datosxD = array();
            $sumaOtros = 0;
            while ($row2 = sv_mysqli_fetch_array($result2)) {
                $datosxD[$row2["status"]] = $row2["CONTEO"];
                $sumaOtros += $row2["CONTEO"];
            }
            $bandera = array();
            while ($row = sv_mysqli_fetch_array($result)) {
                $sal["estados"][$cual]["nombre"] = $row["status_name"];
                $que = 0;
                if (array_key_exists($row["status"], $datosxD)) {
                    $que = $datosxD[$row["status"]];
                }
                $sumaOtros -= $que;
                $sal["estados"][$cual++]["cuantos"] = $que;
                $sal["HORA"] = $row["HORA"];
                if ($row["status"] == "NA" || $row["status"] == 'N') {
                    if (array_key_exists("NA", $bandera)) {
                        $sal["estados"][$bandera["NA"]]["cuantos"] += $que;
                        $cual--;
                    } else if (array_key_exists("N", $bandera)) {
                        $sal["estados"][$bandera["N"]]["cuantos"] += $que;
                        $cual--;
                    } else {
                        $bandera[$row["status"]] = $cual - 1;
                    }
                } else {
                    $bandera[$row["status"]] = $cual - 1;
                }
            }
            $sal["estados"][$cual]["nombre"] = "otros";
            $sal["estados"][$cual++]["cuantos"] = $sumaOtros;

            $sal["Estado"] = "ok";
            $this->output->set_output(json_encode($sal));
            //$this->output->set_output(json_encode($campa));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }

    public function infoCampaHistAcum()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('campanashome', "spanish");
                break;
            case "en":
                $this->lang->load('campanashome', "english");
                break;
            default:
                $this->lang->load('campanashome', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && $_SESSION["Grupo"] == GRUPO_ADMINS) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $archived = false;
            if (isset($_POST["archived"]) && limpia($_POST["archived"]) == 1) {
                $archived = true;
            }

            $campa = limpia($_POST["campana"]);

            $sal = [];
            $con = getConnection();

            if ($_SESSION["Cliente"] == -1) {
                $and = "";
            }

            $query = "SELECT * FROM asterisk.vicidial_campaigns;";

            $query2 = "SELECT vicidial_statuses.status as statusu, vicidial_statuses.status_name as name FROM vicidial_statuses " .
                "UNION SELECT vicidial_campaign_statuses.status as statusu, vicidial_campaign_statuses.status_name as name from vicidial_campaign_statuses " .
                " WHERE vicidial_campaign_statuses.campaign_id = '" . $campa . "'";

            $queryWolf3 = "SELECT count(*) as cuantos, DATE_FORMAT(vicidial_log.call_date, '%Y-%m-%d %H:00:00') as fechaW,call_date " .
                " FROM vicidial_log " .
                "where vicidial_log.campaign_id = '" . $campa . "' GROUP BY YEAR(vicidial_log.call_date), MONTH(vicidial_log.call_date), DAY(vicidial_log.call_date), HOUR(vicidial_log.call_date) ";
            if ($archived) {
                $queryWolf3 .= " UNION SELECT count(*) as cuantos, DATE_FORMAT(vicidial_log_archive.call_date, '%Y-%m-%d %H:00:00') as fechaW ,call_date " .
                    " FROM vicidial_log_archive " .
                    "where vicidial_log_archive.campaign_id = '" . $campa . "' GROUP BY YEAR(vicidial_log_archive.call_date), MONTH(vicidial_log_archive.call_date), DAY(vicidial_log_archive.call_date), HOUR(vicidial_log_archive.call_date) ";
            }
            $queryWolf3 = "SELECT SUM(T.cuantos) AS cuantos,T.fechaW AS fechaW FROM ($queryWolf3) AS T GROUP BY YEAR(T.call_date), MONTH(T.call_date), DAY(T.call_date), HOUR(T.call_date) order by (T.call_date) DESC";

            $resultWolf4 = sv_mysqli_query($con, $queryWolf3);

            $rowWolf = sv_mysqli_fetch_array($resultWolf4);

            $ultimaFec = $rowWolf["fechaW"];

            $contador = 0;
            $datosxD = [];
            $estatus = [];
            $acumulado = 0;

            $array1 = array();

            $originales = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ';
            $modificadas = 'aaaaaaaceeeeiiiidnoooooouuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr';

            $result = sv_mysqli_query($con, $query2);

            while ($row2 = sv_mysqli_fetch_array($result)) {

                $cadena = utf8_decode($row2["name"]);
                $cadena = strtr($cadena, utf8_decode($originales), $modificadas);
                $cadena = strtolower($cadena);
                $cadena = utf8_encode($cadena);

                //array_push($array1, $cadena);

                //$estatus[$contador]["estatus"] = $row2["name"];

                if (!empty($row2["statusu"])) {

                    $query3 = "SELECT count(*) as cuantos, DATE_FORMAT(vicidial_log.call_date, '%Y-%m-%d %H:00:00') as fechaW ,call_date" .
                        " FROM vicidial_log " .
                        "where vicidial_log.campaign_id = '" . $campa . "' and vicidial_log.status = '" . $row2["statusu"] . "'" .
                        " GROUP BY YEAR(vicidial_log.call_date), MONTH(vicidial_log.call_date), DAY(vicidial_log.call_date), HOUR(vicidial_log.call_date) ";

                    if ($archived) {
                        $query3 .= " UNION SELECT count(*) as cuantos, DATE_FORMAT(vicidial_log_archive.call_date, '%Y-%m-%d %H:00:00') as fechaW ,call_date" .
                            " FROM vicidial_log_archive " .
                            "where vicidial_log_archive.campaign_id = '" . $campa . "' and vicidial_log_archive.status = '" . $row2["statusu"] . "'" .
                            " GROUP BY YEAR(vicidial_log_archive.call_date), MONTH(vicidial_log_archive.call_date), DAY(vicidial_log_archive.call_date), HOUR(vicidial_log_archive.call_date) ";
                    }
                    $query3 = "SELECT SUM(T.cuantos) AS cuantos, T.fechaW AS fechaW FROM ($query3) AS T GROUP BY YEAR(T.call_date), MONTH(T.call_date), DAY(T.call_date), HOUR(T.call_date)  order by (T.call_date) ASC";

                    $result4 = sv_mysqli_query($con, $query3);

                    $contador2 = 0;

                    $acumulado = 0;

                    $contadorLlamadas = 0;

                    while ($row4 = sv_mysqli_fetch_array($result4)) {

                        $acumulado += $row4["cuantos"];

                        $estatus[$contador]["calls"][$contador2]["cuenta"] = $acumulado;
                        $estatus[$contador]["calls"][$contador2]["fecha"] = $row4["fechaW"];

                        $contador2++;
                        $contadorLlamadas++;

                    }

                    if ($contadorLlamadas != 0) {

                        $estatus[$contador]["calls"][$contador2]["cuenta"] = $acumulado;
                        $estatus[$contador]["calls"][$contador2]["fecha"] = $rowWolf["fechaW"];

                        $estatus[$contador]["estatus"] = $cadena;

                    }

                }

                $contador++;

            }

            $datosxD = [];
            $datosxD["estado"] = 78;

            $sal["estado"] = "ok";
            $sal["estatus"] = $estatus;
            $this->output->set_output(json_encode($sal));
            //$this->output->set_output(json_encode($campa));
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
}
