<?php

require_once "BASEPATH.php";

class ApiAgente extends MY_Controller
{

    private function genera_respuesta($con, $error = false, $codigo = -1, $data = null)
    {
        if ($con != null) {
            sv_mysqli_close($con);
        }
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        header("Access-Control-Allow-Credentials: true");
        header("Allow: GET, POST, OPTIONS, PUT, DELETE");
        header('Content-type: application/json');
        $this->output->set_output(
            json_encode(
                array(
                    "error" => $error,
                    "code" => $codigo,
                    "data" => $data,
                )
            )
        );
    }

    public function index()
    {
        header('Access-Control-Allow-Origin: *');
        if (isset($_GET["token"])) {
            session_destroy();
            session_id($_GET["token"]);
            session_start();
        }
        $this->load->view('apiagente/vw_apiagente');
    }

    public function getCampaigns()
    {
        require_once RUTA_APP . 'Conexion.php';
        $con = getConnection();
        $user = limpia($_POST['user']);
        $pass = limpia($_POST['pass']);
        $query = "SELECT * FROM vicidial_users WHERE BINARY user = '$user' AND BINARY pass = '$pass' AND active = 'Y' AND user_group LIKE '%" . GRUPO_AGENTES . "%' LIMIT 1";
        $result = sv_mysqli_query($con, $query);

        if ($row = sv_mysqli_fetch_array($result)) {

            $campanas = array();

            $cliente = "";
            $a = strpos($grupo, "_");
            if ($a === false) {
                $cliente = -1;
            } else {
                $cliente = "";
                for ($i = $a - 1; $i >= 0; $i--) {
                    $cliente .= $grupo[$i];
                }
                $cliente = strrev($cliente);
            }

            $and = "";
            if ($cliente != -1) {
                $and = "AND user_group = '" . $cliente . "'";
            }

            $query = "SELECT campaign_id, campaign_name FROM vicidial_campaigns WHERE active = 'Y' $and";
            $result = sv_mysqli_query($con, $query);
            $i = 0;
            while ($row = sv_mysqli_fetch_array($result)) {
                $campanas[$i]["id"] = $row["campaign_id"];
                $campanas[$i]["name"] = $row["campaign_name"];
                $i++;
            }

            $this->genera_respuesta($con, false, -1, array(
                "campaigns" => $campanas,
            ));

        } else {
            $this->genera_respuesta($con, true, 1);
        }
    }

    public function login()
    {
        if (empty($_SESSION["Usuario"])) {

            include_once RUTA_APP . 'Conexion.php';
            $con = getConnection();

            $usuario = array(); // Informacion completa del usuario
            $user = $extension = limpia($_POST['user']);
            $pass = $pass_extension = limpia($_POST['password']);

            $campana = -1;
            if (isset($_POST["campaign"])) {
                $campana = limpia($_POST["campaign"]);
            }

            // Validacion del usuario =====================================

            $query = "SELECT * FROM vicidial_users WHERE BINARY user = '$user' AND BINARY pass = '$pass' AND active = 'Y' AND user_group LIKE '%" . GRUPO_AGENTES . "%' LIMIT 1";
            $result = sv_mysqli_query($con, $query);

            if ($row = sv_mysqli_fetch_array($result)) {
                $usuario = $row;
            } else {
                $this->genera_respuesta($con, true, 1);
                return;
            }

            // Validacion del usuario =====================================

            // Validacion de la extension =================================
            $query = "SELECT extension FROM phones WHERE login IN (SELECT logins_list FROM phones_alias WHERE BINARY alias_name='$extension') AND active = 'Y' AND BINARY pass='$pass_extension' LIMIT 1";

            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $extension = $row["extension"];
            } else {
                $this->genera_respuesta($con, true, 2);
                return;
            }

            // Validacion de la extension =================================

            // Obtencion del cliente ======================================
            $grupo = $usuario["user_group"];
            $cliente = "";
            $a = strpos($grupo, "_");
            for ($i = $a - 1; $i >= 0; $i--) {
                $cliente .= $grupo[$i];
            }
            $cliente = strrev($cliente);
            // Obtencion del cliente ======================================

            // Validacion de la campaña ===================================
            $query = "SELECT campaign_id,campaign_recording,dial_method,campaign_allow_inbound FROM vicidial_campaigns WHERE active = 'Y' AND user_group = '$cliente' AND campaign_id = '$campana' LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if (sv_mysqli_num_rows($result) <= 0) {
                $this->genera_respuesta($con, true, 3);
                return;
            }
            $rowCampana = sv_mysqli_fetch_array($result);
            // Validacion de la campaña ===================================

            // Guardando informacion de la campaña en la sesion
            $_SESSION["dial_method"] = $rowCampana["dial_method"];
            $_SESSION["INBOUND"] = $rowCampana["campaign_allow_inbound"] == "Y";
            $_SESSION["campaign_recording"] = $rowCampana["campaign_recording"];

            if ($rowCampana["dial_method"] != 'INBOUND_MAN' && !$_SESSION["INBOUND"]) {
                $query = "SELECT count(hopper_id) FROM vicidial_hopper where campaign_id = '$campana' and status='READY'";
                $result = sv_mysqli_query($con, $query);
                $rowHopper = sv_mysqli_fetch_array($result);
                if ($rowHopper[0] <= 0) {
                    $this->genera_respuesta($con, true, 4);
                    return;
                }
            }

            // Configuracion adicional de la campaña
            $query2 = "SELECT windows_check,max_time_dispo,allow_beep,time_beep,time_repeat,allow_wa,idcampaign_wa FROM vicidial_tables_windows WHERE campaign_id = '$campana'";
            $result2 = sv_mysqli_query($con, $query2);
            $row4 = sv_mysqli_fetch_array($result2);

            $_SESSION["windows_check"] = $row4["windows_check"];
            $_SESSION["max_time_dispo"] = $row4["max_time_dispo"];
            $_SESSION["time_beep"] = $row4["time_beep"];
            $_SESSION["allow_beep"] = $row4["allow_beep"];
            $_SESSION["time_repeat"] = $row4["time_repeat"];

            // Configuracion si incluye WAM
            // ! Inhabilitado de momento
            // if (NEED_WA) {
            if (false) {
                $_SESSION["allow_wa"] = $row4["allow_wa"];
                $_SESSION["wa_camp"] = $row4["idcampaign_wa"];
                $query2 = "SELECT wa_user,wa_pass,allow_wa FROM dialvox_grupos_agentes WHERE Usuario = '$user'";
                $result2 = sv_mysqli_query($con, $query2);
                $row4 = sv_mysqli_fetch_array($result2);
                $_SESSION["wa_user"] = $row4["wa_user"];
                $_SESSION["wa_pass"] = $row4["wa_pass"];
                $_SESSION["WA_USER"] = $row4["allow_wa"];
            }

            // Informacion del agente
            $_SESSION["Usuario"] = $user;
            $_SESSION["Password"] = $pass;
            $_SESSION["Grupo"] = $usuario["user_group"];

            $a = strpos($_SESSION["Grupo"], "_");
            if ($a === false) {
                $_SESSION["Cliente"] = -1;
            } else {
                $_SESSION["Cliente"] = "";
                for ($i = $a - 1; $i >= 0; $i--) {
                    $_SESSION["Cliente"] .= $_SESSION["Grupo"][$i];
                }
                $_SESSION["Cliente"] = strrev($_SESSION["Cliente"]);
            }

            $_SESSION["extension"] = $extension;
            $_SESSION["pass_ext"] = $pass_extension;
            $_SESSION["Grupo"] = GRUPO_AGENTES;
            $_SESSION["Campana"] = $campana;
            $_SESSION["Nombre"] = $usuario["full_name"];

            // Configuracion si incluye WAM
            // ! Inhabilitado de momento
            // if (NEED_WA) {
            if (false) {
                $query2 = "SELECT allow_wa,user_wa,pass_wa,idclient_wa FROM vicidial_clients_limit WHERE idClient='{$_SESSION["Cliente"]}'";
                $result2 = sv_mysqli_query($con, $query2);
                if ($row4 = sv_mysqli_fetch_array($result2)) {
                    $_SESSION["allow_waCli"] = $row4["allow_wa"];
                    $_SESSION["user_wa"] = $row4["user_wa"];
                    $_SESSION["pass_wa"] = $row4["pass_wa"];
                    $_SESSION["idclient_wa"] = $row4["idclient_wa"];
                }
            }

            // Mas configuracion adicional
            // TODO: Verificar si es necesaria esta informacion
            $query2 = "SELECT allow_chat,userTelevox,passTelevox,allowTelevox,allowGlobalList,allowACD,allowInboundsReports FROM vicidial_clients_limit WHERE idClient='{$_SESSION["Cliente"]}'";
            $result2 = sv_mysqli_query($con, $query2);
            if ($row4 = sv_mysqli_fetch_array($result2)) {
                $_SESSION["userTelevox"] = $row4["userTelevox"];
                $_SESSION["passTelevox"] = $row4["passTelevox"];
                $_SESSION["allowTelevox"] = $row4["allowTelevox"];
                $_SESSION["allowGlobalList"] = $row4["allowGlobalList"];
                $_SESSION["allowACD"] = $row4["allowACD"];
                $_SESSION["allowInboundsReports"] = $row4["allowInboundsReports"];
                $_SESSION["allow_chat"] = $row4["allow_chat"];
            }

            session_write_close();

            $this->genera_respuesta($con, false, -1, array(
                "token" => session_id(),
                "maxTimeQualification" => $_SESSION["max_time_dispo"],
                "requiresNextDial" => $_SESSION["dial_method"] == "INBOUND_MAN",
            ));

        } else {
            $this->genera_respuesta(null, true, 5);
        }

    }

    public function startAgent()
    {
        if (isset($_GET["token"])) {
            session_destroy();
            session_id($_GET["token"]);
            session_start();
        }
        if (!empty($_SESSION["Usuario"])) {

            include_once RUTA_APP . 'Sesiones.php';

            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;

            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=call_agent&value=CALL";
            $text = file_get_contents($url);

            if (strpos($text, "ERROR") !== false) {
                $this->genera_respuesta(null, true, 1, array(
                    "text" => str_replace("ERROR: ", "", $text),
                ));
                return;
            }

            $this->genera_respuesta(null);
        } else {
            $this->genera_respuesta(null, true, 0);
        }
    }

    public function externalDial()
    {
        if (isset($_GET["token"]) && $_GET["token"] != session_id()) {
            session_write_close();
            session_id($_GET["token"]);
            session_start();
        }

        if (!empty($_SESSION["Usuario"])) {

            include_once RUTA_APP . 'Sesiones.php';

            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;

            // Parametros recibidos
            $telefono = $_GET["phone"];
            $codigo = "";
            $debug = isset($_GET["debug"]);
            $prefijo = '';

            if (isset($_GET["codigoPais"])) {
                $codigo = $_GET["codigoPais"];
            }

            if (isset($_GET["prefijo"]) && $_GET["prefijo"] != "") {
                $prefijo = $_GET["prefijo"];
            }

            $usuario = $_SESSION["Usuario"];

            // Obtencion del estado de vicidial ===============================================
            $apiUser = USER_API;
            $apiPass = PASS_API;

            $url = URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=agent_status";

            $data = array();

            $text = file_get_contents($url);
            $keys = ["status"];
            if (strpos($text, "ERROR") !== false) {
                $this->genera_respuesta(null, true, 1);
                return;
            }

            $valores = explode("|", $text);
            for ($i = 0; $i < count($keys); $i++) {
                $data[$keys[$i]] = $valores[$i];
            }

            if (in_array($data["status"], array("READY", "CLOSER", "QUEUE"))) {

                // Poner en pausa
                $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_pause&value=PAUSE";
                $text = file_get_contents($url);
                if (strpos($text, "ERROR") !== false) {
                    $this->genera_respuesta(null, true, 1, array(
                        "text" => $debug ? $text : "El agente no se pudo poner en pausa",
                    ));
                    return;
                }

                if (isset($_GET["codigoPausa"])) {
                    $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=pause_code&value=" . $_GET["codigoPausa"];
                    $text = file_get_contents($url);
                    if (strpos($text, "ERROR") !== false) {
                        $this->genera_respuesta(null, true, 1, array(
                            "text" => $debug ? $text : "El agente no se pudo poner en pausa",
                        ));
                        return;
                    }
                }
            }

            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=external_dial&value=$telefono&phone_code=$codigo&preview=NO&search=NO&focus=NO&lead_id=";

            if ($prefijo != "") {
                $url = $url . "&dial_prefix=$prefijo";
            }

            $text = file_get_contents($url);

            if (strpos($text, "SUCCESS") === false) {
                if (strpos($text, "ERROR: agent_user is not logged in") !== false) {
                    $this->genera_respuesta(null, true, 3, array(
                        "text" => $debug ? $text : "El agente no tiene una sesion iniciada en Dialvox",
                    ));
                    return;
                }
                $this->genera_respuesta(null, true, 4, array(
                    "text" => $debug ? $text : "Ocurrio un error iniciando la llamada",
                ));
                return;
            }

            sleep(0.5);

            require_once RUTA_APP . 'Conexion.php';
            $con = getConnection();

            $lead_id = 0;
            $count = 0;
            while ($lead_id == 0) {
                sleep(1);
                $query = "SELECT lead_id, external_dial FROM vicidial_live_agents WHERE user='$usuario'";
                $res = sv_mysqli_query($con, $query);
                $row = sv_mysqli_fetch_array($res);
                $lead_id = intval($row["lead_id"]);
                $count = $count + 1;
                if ($count > 10) {
                    break;
                }
            }

            sv_mysqli_close($con);

            $date_key = date('Ymdhi');

            $this->genera_respuesta(
                null,
                false,
                -1,
                array(
                    "lead_id" => $lead_id,
                    "recording_key" => $lead_id . $date_key,
                    "recording_agent" => $usuario,
                )
            );
        } else {
            $this->genera_respuesta(null, true, 0, array(
                "text" => "Error en login",
            ));
        }
    }

    public function status()
    {
        if (isset($_GET["token"])) {
            session_destroy();
            session_id($_GET["token"]);
            session_start();
        }

        require_once RUTA_APP . 'Conexion.php';

        if (!empty($_SESSION["Usuario"])) {

            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();

            $usuario = $_SESSION["Usuario"];

            // Obtencion del estado de vicidial ===============================================
            $apiUser = USER_API;
            $apiPass = PASS_API;

            $url = URL_DIALVOX . "/" . DIRECTORIO_VICIDIAL . "/non_agent_api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=agent_status";

            $data = array();

            $text = file_get_contents($url);
            $keys = ["status", "callId", "leadId", "campaignId", "callsToday", "fullName", "userGroup", "userLevel", "pauseCode", "realTimeSubstatus", "phoneNumber", "vendorLeadCode", "sessionId"];
            if (strpos($text, "ERROR") !== false) {
                $this->genera_respuesta($con, true, 1);
                return;
            }

            $valores = explode("|", $text);
            for ($i = 0; $i < count($keys); $i++) {
                if ($keys[$i] != "sessionId" && $keys[$i] != "userGroup" && $keys[$i] != "userLevel") {
                    $data[$keys[$i]] = $valores[$i];
                }
            }
            // Obtencion del estado de vicidial ===============================================

            // Consulta para los grupos de entrada
            $campana = $_SESSION["Campana"];
            $query = "SELECT closer_campaigns FROM vicidial_campaigns WHERE campaign_id='$campana'";
            $result = sv_mysqli_query($con, $query);
            $ingroups = "";
            if ($row = sv_mysqli_fetch_array($result)) {
                $ingroups = $row["closer_campaigns"];
                $ingroups = explode(" ", $ingroups);
                $ingroups = implode("','", $ingroups);
            }
            // Consulta para los grupos de usuarios

            // Obtencion de mas informacion ===============================
            $query = "SELECT comments, TIMESTAMPDIFF(SECOND,vicidial_live_agents.last_state_change,NOW()) as dif,(SELECT campaign_name FROM vicidial_campaigns WHERE campaign_id = vicidial_live_agents.campaign_id) as nomCampa,(SELECT active FROM vicidial_campaigns WHERE campaign_id = vicidial_live_agents.campaign_id) AS campActiva,(SELECT COUNT(*) FROM vicidial_auto_calls WHERE campaign_id IN('$ingroups', '$campana') AND status='LIVE' AND call_type='IN') as llamadasSonando FROM vicidial_live_agents WHERE user = '$usuario' LIMIT 1";

            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $data["time"] = $row["dif"]; // Tiempo en ese estado
                $data["campaign"] = $row["nomCampa"]; // Nombre de la campaña
                $data["isCampaignActive"] = $row["campActiva"] == "Y"; // Envia si la campaña sigue activa
                $data["ringingCalls"] = $row["llamadasSonando"]; // Llamadas sin agente en ese  momento
                if ($row["comments"] === "INBOUND") {
                    $data["type"] = "in";
                } else {
                    $data["type"] = "out";
                }
            }
            // Obtencion de mas informacion ===============================

            // Obtencion de informacion del grupo de entrada, si hay ============================
            $query_ingroup = "SELECT campaign_id FROM vicidial_closer_log WHERE lead_id ='" . $data["leadId"] . "' ORDER BY closecallid DESC LIMIT 1";
            $query_ingroup_result = sv_mysqli_query($con, $query_ingroup);
            $data["actualIngroupId"] = "";
            $data["actualIngroupName"] = "";

            if ($row2 = sv_mysqli_fetch_array($query_ingroup_result)) {
                $data["actualIngroupId"] = $row2["campaign_id"];
                $query_ingroup = "SELECT group_name FROM vicidial_inbound_groups WHERE group_id='" . $data["actualIngroupId"] . "'";
                $query_ingroup_result = sv_mysqli_query($con, $query_ingroup);
                if ($row2 = sv_mysqli_fetch_array($query_ingroup_result)) {
                    $data["actualIngroupName"] = $row2["group_name"];
                } else {
                    $data["actualIngroupName"] = "";
                }
            }
            // Obtencion de informacion del grupo de entrada, si hay ============================

            // Arreglando status =============================================
            switch ($data["status"]) {
                case 'PAUSED':
                    switch ($data["realTimeSubstatus"]) {
                        case 'DISPO':
                            $data["status"] = 'CALIFICANDO';
                            $data["realTimeSubstatus"] = "CALIFICANDO";
                            break;
                        default:
                            $data["status"] = 'PAUSADO';
                            break;
                    }
                    break;
                case 'DIAL':
                case 'INCALL':
                    if ($data["realTimeSubstatus"] === 'DEAD') {
                        $data["status"] = 'LLAMADA CORTADA';
                    } else {
                        $data["status"] = 'EN LLAMADA';
                    }
                    break;
                case 'CLOSER':
                case 'READY':
                    $data["status"] = 'DISPONIBLE';
                    break;
                case 'QUEUE':
                    $data["status"] = 'EN COLA';
                    break;
                case 'DEAD':
                    $data["status"] = 'LLAMADA CORTADA';
                    break;
                default:
                    $data["status"] = $data["status"] . "/" . $data["realTimeSubstatus"];
                    break;
            }
            // Arreglando status =============================================

            $this->genera_respuesta($con, false, -1, $data);
        } else {
            $this->genera_respuesta(null, true, 0);
        }

    }

    public function getQualificationStatuses()
    {
        if (isset($_GET["token"])) {
            session_destroy();
            session_id($_GET["token"]);
            session_start();
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {

            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();
            $query = "SELECT status,status_name,scheduled_callback FROM vicidial_statuses WHERE selectable = 'Y' UNION SELECT status,status_name,scheduled_callback FROM vicidial_campaign_statuses WHERE selectable = 'Y' AND campaign_id = '" . $_SESSION["Campana"] . "'";
            $result = sv_mysqli_query($con, $query);
            $data = array();
            $data["statuses"] = array();
            while ($row = sv_mysqli_fetch_array($result)) {
                $data["statuses"][] = array(
                    "status" => $row["status"],
                    "name" => $row["status_name"],
                );
            }

            $this->genera_respuesta($con, false, -1, $data);
        } else {
            $this->genera_respuesta(null, true, 0);
        }
    }

    public function getPauseCodes()
    {
        if (isset($_GET["token"])) {
            session_destroy();
            session_id($_GET["token"]);
            session_start();
        }
        if (!empty($_SESSION["Usuario"])) {

            include_once RUTA_APP . 'Conexion.php';
            include_once RUTA_APP . 'Sesiones.php';
            $con = getConnection();

            $data = array();

            $campana = $_SESSION["Campana"];
            $cliente = $_SESSION["Cliente"];

            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' AND user_group = '$cliente' LIMIT 1";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {

                $query = "SELECT vpc.pause_code, vpc.pause_code_name, vpc.billable, vpc.time_limit, vpc.require_mgr_approval,dp.tiempo_limite,dp.requiere_password FROM vicidial_pause_codes AS vpc INNER JOIN dialvox_pausas AS dp ON dp.campaign_id=vpc.campaign_id AND dp.pause_code=vpc.pause_code WHERE vpc.campaign_id = '$campana' ORDER BY vpc.pause_code";
                $result = sv_mysqli_query($con, $query);

                $data["codes"] = array();
                while ($row = sv_mysqli_fetch_array($result)) {
                    array_push($data["codes"], array(
                        "code" => $row["pause_code"],
                        "name" => $row["pause_code_name"],
                        // "timeLimit" => $row["tiempo_limite"],
                        // "supervisorRequired" => $row["requiere_password"],
                    ));
                }

                $this->genera_respuesta($con, false, -1, $data);

            } else {
                $this->genera_respuesta($con, true, 1);
            }
        } else {
            $this->genera_respuesta(null, true, 0);
        }
    }

    public function logout()
    {
        if (isset($_GET["token"]) && $_GET["token"] != session_id()) {
            session_write_close();
            session_id($_GET["token"]);
            session_start();
        }
        if (!empty($_SESSION["Usuario"])) {
            $usuario = $_SESSION["Usuario"];
            $apiUser = USER_API;
            $apiPass = PASS_API;
            $url = URL_DIALVOX . "/" . DIRECTORIO_AGC . "/api.php?source=cli&user=" . $apiUser . "&pass=" . $apiPass . "&agent_user=" . $usuario . "&function=logout&value=LOGOUT";
            file_get_contents($url);
        } else {
            $this->genera_respuesta(null, true, 1);
            return;
        }
        if (!empty($_SESSION["Usuario"])) {
            session_destroy();
        }
        $this->genera_respuesta(null);
    }

}
