<?php

require_once "BASEPATH.php";

class ReciclajeLeads extends MY_Controller
{
    public function getStatusesSelect()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reciclajeleads', "spanish");
                break;
            case "en":
                $this->lang->load('reciclajeleads', "english");
                break;
            default:
                $this->lang->load('reciclajeleads', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"])) {
            header('Content-type: application/json');
            include_once RUTA_APP . 'Sesiones.php';
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            if ($_SESSION["Grupo"] == GRUPO_AGENTES) {
                $campana = $_SESSION["Campana"];
            } else {
                $campana = limpia($_POST["campana"]);
            }
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' ";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $query = "SELECT status, status_name FROM vicidial_statuses UNION SELECT status, status_name FROM vicidial_campaign_statuses WHERE campaign_id='$campana'";
                $result = sv_mysqli_query($con, $query);
                $donde = 0;
                $sal["Registros"] = array();
                while ($row = sv_mysqli_fetch_array($result)) {
                    $sal["Registros"][$donde]["estado"] = $row["status"];
                    $sal["Registros"][$donde]["nombre"] = $row["status_name"];
                    $donde++;
                }
                $sal["Estado"] = "ok";
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosVerEstados");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }

    public function getStatuses()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reciclajeleads', "spanish");
                break;
            case "en":
                $this->lang->load('reciclajeleads', "english");
                break;
            default:
                $this->lang->load('reciclajeleads', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            $pagina = 0;
            if (isset($_POST["pagina"]) && intval($_POST["pagina"]) >= 1) {
                $pagina = intval(limpia($_POST["pagina"]) - 1);
            }
            $registros = 10;
            $skip = $pagina * $registros;
            $campana = limpia($_POST["campana"]);
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $stmt = "SELECT list_id from vicidial_lists where campaign_id='$campana'";
                $result2 = sv_mysqli_query($con, $stmt);
                $listas = "";
                while ($row2 = sv_mysqli_fetch_array($result2)) {
                    $listas .= "'" . $row2["list_id"] . "',";
                }
                if (strlen($listas) > 0) {
                    $listas = substr($listas, 0, -1);
                } else {
                    $listas = "''";
                }
                $query = "SELECT recycle_id, status, active,attempt_maximum  FROM vicidial_lead_recycle WHERE campaign_id = '$campana' ORDER BY recycle_id LIMIT $skip,$registros";
                $result = sv_mysqli_query($con, $query);
                $donde = 0;
                $sal["Registros"] = array();
                $sal["Estado"] = "ok";
                while ($row = sv_mysqli_fetch_array($result)) {
                    $RECYCLE_count = "'Y','Y1','Y2','Y3','Y4','Y5','Y6','Y7','Y8','Y9','Y10'";
                    if ($row["attempt_maximum"] == 1) {$RECYCLE_count = "'Y1','Y2','Y3','Y4','Y5','Y6','Y7','Y8','Y9','Y10'";}
                    if ($row["attempt_maximum"] == 2) {$RECYCLE_count = "'Y2','Y3','Y4','Y5','Y6','Y7','Y8','Y9','Y10'";}
                    if ($row["attempt_maximum"] == 3) {$RECYCLE_count = "'Y3','Y4','Y5','Y6','Y7','Y8','Y9','Y10'";}
                    if ($row["attempt_maximum"] == 4) {$RECYCLE_count = "'Y4','Y5','Y6','Y7','Y8','Y9','Y10'";}
                    if ($row["attempt_maximum"] == 5) {$RECYCLE_count = "'Y5','Y6','Y7','Y8','Y9','Y10'";}
                    if ($row["attempt_maximum"] == 6) {$RECYCLE_count = "'Y6','Y7','Y8','Y9','Y10'";}
                    if ($row["attempt_maximum"] == 7) {$RECYCLE_count = "'Y7','Y8','Y9','Y10'";}
                    if ($row["attempt_maximum"] == 8) {$RECYCLE_count = "'Y8','Y9','Y10'";}
                    if ($row["attempt_maximum"] == 9) {$RECYCLE_count = "'Y9','Y10'";}
                    if ($row["attempt_maximum"] > 9) {$RECYCLE_count = "'Y10'";}

                    $otra = "SELECT COUNT(*) AS maximo FROM vicidial_list WHERE status='" . $row["status"] . "' AND list_id IN($listas) AND called_since_last_reset IN ($RECYCLE_count)";
                    $result2 = sv_mysqli_query($con, $otra);
                    if ($row2 = sv_mysqli_fetch_array($result2)) {
                        $sal["Registros"][$donde]["maximo"] = $row2["maximo"];
                    } else {
                        $sal["Registros"][$donde]["maximo"] = 0;
                    }
                    $sal["Registros"][$donde]["recycle_id"] = $row["recycle_id"];
                    $sal["Registros"][$donde]["status"] = $row["status"];
                    $sal["Registros"][$donde]["active"] = $row["active"];

                    $donde++;
                }
                $result = sv_mysqli_query($con, "SELECT COUNT(recycle_id)  FROM vicidial_lead_recycle WHERE campaign_id = '$campana'");
                $row = sv_mysqli_fetch_array($result);
                $sal["Cuenta"] = $row[0];
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosVerEstados");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function getStatDetails()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reciclajeleads', "spanish");
                break;
            case "en":
                $this->lang->load('reciclajeleads', "english");
                break;
            default:
                $this->lang->load('reciclajeleads', "spanish");
                break;
        }
        include_once RUTA_APP . 'Conexion.php';
        if (!empty($_SESSION["Usuario"]) && ($_SESSION["Grupo"] == GRUPO_ADMINS || $_SESSION["Grupo"] == GRUPO_SUPERVISORES)) {
            include_once RUTA_APP . 'Sesiones.php';
            header('Content-type: application/json');
            $usuario = $_SESSION["Usuario"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            $estado = limpia($_POST["estado"]);
            $campana = limpia($_POST["campana"]);
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $stmt = "SELECT recycle_id,status,attempt_delay,attempt_maximum from vicidial_lead_recycle where campaign_id='$campana' and recycle_id='$estado'";
                $result2 = sv_mysqli_query($con, $stmt);
                if ($row = sv_mysqli_fetch_array($result2)) {
                    $sal["Reciclaje"] = array();
                    $sal["Reciclaje"]["attempt_delay"] = $row["attempt_delay"];
                    $sal["Reciclaje"]["attempt_maximum"] = $row["attempt_maximum"];
                    $sal["Reciclaje"]["recycle_id"] = $row["recycle_id"];
                    $sal["Reciclaje"]["status"] = $row["status"];
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_estadoInexistente");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosVerEstados");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function addStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reciclajeleads', "spanish");
                break;
            case "en":
                $this->lang->load('reciclajeleads', "english");
                break;
            default:
                $this->lang->load('reciclajeleads', "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"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            $campana = limpia($_POST["campana"]);
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $estado = limpia($_POST["estado"]);
                $query = "SELECT status FROM vicidial_lead_recycle WHERE campaign_id = '$campana' AND status = '$estado' LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_estadoExistente");
                } else {
                    $attemp_delay = limpia($_POST["attemp_delay"]);
                    $attempt_maximum = limpia($_POST["attempt_maximum"]);
                    $stmtE = "INSERT INTO vicidial_lead_recycle (status,attempt_delay,attempt_maximum,active,campaign_id) VALUES ('$estado','$attemp_delay','$attempt_maximum','Y','$campana') ";
                    sv_mysqli_query($con, $stmtE);
                    $sal["Estado"] = "ok";
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosAgregar");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function deleteStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reciclajeleads', "spanish");
                break;
            case "en":
                $this->lang->load('reciclajeleads', "english");
                break;
            default:
                $this->lang->load('reciclajeleads', "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"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            $campana = limpia($_POST["campana"]);
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $estado = limpia($_POST["estado"]);
                $query = "SELECT status FROM vicidial_lead_recycle WHERE campaign_id = '$campana' AND recycle_id = '$estado' LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    $stmt = "DELETE FROM vicidial_lead_recycle WHERE campaign_id = '$campana' AND recycle_id = '$estado' LIMIT 1";
                    $result = sv_mysqli_query($con, $stmt);
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_estadoInexistente");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEliminar");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function editStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reciclajeleads', "spanish");
                break;
            case "en":
                $this->lang->load('reciclajeleads', "english");
                break;
            default:
                $this->lang->load('reciclajeleads', "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"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            $campana = limpia($_POST["campana"]);
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $estado = limpia($_POST["estado"]);
                $query = "SELECT status FROM vicidial_lead_recycle WHERE campaign_id = '$campana' AND recycle_id = '$estado' LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    $attemp_delay = limpia($_POST["attemp_delay"]);
                    $attempt_maximum = limpia($_POST["attempt_maximum"]);
                    $stmtE = "UPDATE vicidial_lead_recycle SET attempt_delay='$attemp_delay',attempt_maximum='$attempt_maximum' WHERE recycle_id='$estado' AND campaign_id='$campana'";
                    sv_mysqli_query($con, $stmtE);
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_estadoInexistente");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEditar");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }
    public function changeStatus()
    {
        $idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
        switch ($idioma) {
            case "es":
                $this->lang->load('reciclajeleads', "spanish");
                break;
            case "en":
                $this->lang->load('reciclajeleads', "english");
                break;
            default:
                $this->lang->load('reciclajeleads', "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"];
            $sal = array();
            $con = getConnection();
            $donde = "";
            $cliente = $_SESSION["Cliente"];
            $campana = limpia($_POST["campana"]);
            if ($cliente != -1) {
                $donde = "AND user_group = '$cliente'";
            }
            $query = "SELECT campaign_id FROM vicidial_campaigns WHERE campaign_id = '$campana' $donde";
            $result = sv_mysqli_query($con, $query);
            if ($row = sv_mysqli_fetch_array($result)) {
                $estado = limpia($_POST["estado"]);
                $query = "SELECT status,active FROM vicidial_lead_recycle WHERE campaign_id = '$campana' AND recycle_id = '$estado' LIMIT 1";
                $result = sv_mysqli_query($con, $query);
                if ($row = sv_mysqli_fetch_array($result)) {
                    $active = 'Y';
                    if ($row["active"] == 'Y') {
                        $active = 'N';
                    }
                    $stmtE = "UPDATE vicidial_lead_recycle SET active='$active' WHERE recycle_id='$estado' AND campaign_id='$campana'";
                    sv_mysqli_query($con, $stmtE);
                    $sal["Estado"] = "ok";
                } else {
                    $sal["Estado"] = "error";
                    $sal["Descripcion"] = $this->lang->line("desc_estadoInexistente");
                }
            } else {
                $sal["Estado"] = "error";
                $sal["Descripcion"] = $this->lang->line("desc_permisosEditar");
            }
            $this->output->set_output(json_encode($sal));
            sv_mysqli_close($con);
        } else {
            $sal = array();
            $sal["Estado"] = "error";
            $sal["Descripcion"] = $this->lang->line("desc_permisosAccion");
            $this->output->set_output(json_encode($sal));
        }
    }

    public function index()
    {
        $this->load->view('reciclajeLeads/head');
        $this->load->view('reciclajeLeads/vw_reciclajeLeads');
        $this->load->view('reciclajeLeads/foot');
    }
}
