<?php
require_once 'Menu.php';
require_once 'AudioDatos.php';
require_once RUTA_APP . 'Conexion.php';
class MenuDatos
{
    public static function getLastId()
    {
        $con = getConnection();
        $query = "SELECT menu_id FROM vicidial_call_menu WHERE menu_id REGEXP '^[0-9]+$' ORDER BY CAST(menu_id AS INT) DESC LIMIT 1";
        $result = sv_mysqli_query($con, $query);
        $id = 10;
        if ($row = sv_mysqli_fetch_array($result)) {
            $id = $row["menu_id"];
        }
        sv_mysqli_close($con);
        return $id;
    }
    public static function getAllMenusByCliente($cliente)
    {
        $con = getConnection();
        $query = "SELECT menu_id, menu_name FROM vicidial_call_menu WHERE user_group = '" . $cliente->getId() . "'";
        $result = sv_mysqli_query($con, $query);
        $resp = array();
        while ($row = sv_mysqli_fetch_array($result)) {
            array_push($resp, new Menu(
                $row["menu_id"],
                $row["menu_name"]
            ));
        }
        return $resp;
    }
    public static function getAllMenus()
    {
        $con = getConnection();
        $query = "SELECT menu_id, menu_name FROM vicidial_call_menu";
        $result = sv_mysqli_query($con, $query);
        $resp = array();
        while ($row = sv_mysqli_fetch_array($result)) {
            array_push($resp, new Menu(
                $row["menu_id"],
                $row["menu_name"]
            ));
        }
        return $resp;
    }
    public static function getMenusByCliente($cliente, $pagina, $limite, $texto)
    {
        $con = getConnection();
        $query = "SELECT menu_id, menu_name, menu_prompt, menu_invalid_prompt, menu_timeout_prompt,user_group,call_time_id FROM vicidial_call_menu WHERE user_group = '" . $cliente->getId() . "' AND menu_name LIKE '%" . limpia($texto) . "%' LIMIT " . ($pagina * $limite) . "," . $limite;
        $result = sv_mysqli_query($con, $query);
        $resp = array();
        while ($row = sv_mysqli_fetch_array($result)) {
            array_push($resp, new Menu(
                $row["menu_id"],
                $row["menu_name"],
                ClienteDatos::getClienteById($row["user_group"]),
                AudioDatos::getAudioByHash($row["menu_invalid_prompt"]),
                AudioDatos::getAudioByHash($row["menu_prompt"]),
                AudioDatos::getAudioByHash($row["menu_timeout_prompt"]),
                $row["call_time_id"],
            ));
        }
        return $resp;
    }
    public static function countMenusByCliente($cliente, $texto)
    {
        $con = getConnection();
        $query = "SELECT COUNT(menu_id) AS CUENTA FROM vicidial_call_menu WHERE user_group = '" . $cliente->getId() . "' AND menu_name LIKE '%" . limpia($texto) . "%'";
        $result = sv_mysqli_query($con, $query);
        $resp = -1;
        if ($row = sv_mysqli_fetch_array($result)) {
            $resp = $row["CUENTA"];
        }
        return $resp;
    }
    public static function countMenus($texto)
    {
        $con = getConnection();
        $query = "SELECT COUNT(menu_id) AS CUENTA FROM vicidial_call_menu WHERE menu_name LIKE '%" . limpia($texto) . "%'";
        $result = sv_mysqli_query($con, $query);
        $resp = -1;
        if ($row = sv_mysqli_fetch_array($result)) {
            $resp = $row["CUENTA"];
        }
        return $resp;
    }
    public static function getMenus($pagina, $limite, $texto)
    {
        $con = getConnection();
        $query = "SELECT menu_id, menu_name, menu_prompt, menu_invalid_prompt, menu_timeout_prompt,user_group,call_time_id FROM vicidial_call_menu WHERE menu_name LIKE '%" . limpia($texto) . "%' LIMIT " . ($pagina * $limite) . "," . $limite;
        $result = sv_mysqli_query($con, $query);
        $resp = array();
        while ($row = sv_mysqli_fetch_array($result)) {
            array_push($resp, new Menu(
                $row["menu_id"],
                $row["menu_name"],
                ClienteDatos::getClienteById($row["user_group"]),
                AudioDatos::getAudioByHash($row["menu_invalid_prompt"]),
                AudioDatos::getAudioByHash($row["menu_prompt"]),
                AudioDatos::getAudioByHash($row["menu_timeout_prompt"]),
                $row["call_time_id"],
            ));
        }
        return $resp;
    }
    public static function updateMenu($menu)
    {
        $menuAnterior = self::getMenuById($menu->getId());
        if ($menuAnterior != null) {
            $con = getConnection();
            $audioTLE = $audioOpcionInvalida = $audioPrincipal = "NONE";
            if (strlen($menu->getNombre()) >= 100) {
                $menu->setNombre($menuAnterior->getNombre());
            }
            if ($menu->getAudioTLE() != null) {
                if (AudioDatos::saveAudio($menu->getAudioTLE()) != 0) {
                    $audioTLE = $menuAnterior->getAudioTLE();
                } else {
                    $audioTLE = $menu->getAudioTLE()->getHash();
                }
            }
            if ($menu->getAudioPrincipal() != null) {
                if (AudioDatos::saveAudio($menu->getAudioPrincipal()) != 0) {
                    $audioPrincipal = $menuAnterior->getAudioPrincipal();
                } else {
                    $audioPrincipal = $menu->getAudioPrincipal()->getHash();
                }
            }
            if ($menu->getAudioOpcionInvalida() != null) {
                if (AudioDatos::saveAudio($menu->getAudioOpcionInvalida()) != 0) {
                    $audioOpcionInvalida = $menuAnterior->getAudioOpcionInvalida();
                } else {
                    $audioOpcionInvalida = $menu->getAudioOpcionInvalida()->getHash();
                }
            }
            $query = "UPDATE vicidial_call_menu SET
					menu_name = '" . $menu->getNombre() . "',
					menu_prompt = '" . $audioPrincipal . "',
					menu_timeout_prompt = '" . $audioTLE . "',
					menu_invalid_prompt = '" . $audioOpcionInvalida . "',
                    call_time_id='" . $menu->getCallTimeId() . "'
					WHERE menu_id = '" . $menu->getId() . "'";
            $resp = 0;
            if (sv_mysqli_query($con, $query)) {
                $resp = 0;
                sv_mysqli_query($con, "UPDATE servers set rebuild_conf_files='Y' where generate_vicidial_conf='Y' and active_asterisk_server='Y'");
            } else {
                $resp = -1;
            }
            sv_mysqli_close($con);
            return $resp;
        } else {
            return -1;
        }
    }
    public static function deleteMenu($menu)
    {
        $menuAnterior = self::getMenuById($menu->getId());
        if ($menuAnterior != null) {
            $con = getConnection();
            $query = "DELETE FROM vicidial_call_menu WHERE menu_id = '" . $menu->getId() . "'";
            $resp = 0;
            if (sv_mysqli_query($con, $query)) {
                $resp = 0;
                sv_mysqli_query($con, "UPDATE vicidial_inbound_dids SET menu_id = 'NONE' WHERE menu_id = '" . limpia($menu->getId()) . "'");
                sv_mysqli_query($con, "UPDATE vicidial_call_menu_options SET option_route_value = 'NONE' WHERE option_route_value = '" . limpia($menu->getId()) . "' AND option_route = 'MENU'");
                sv_mysqli_query($con, "UPDATE servers set rebuild_conf_files='Y' where generate_vicidial_conf='Y' and active_asterisk_server='Y'");
            } else {
                $resp = -1;
            }
            sv_mysqli_close($con);
            return $resp;
        } else {
            return -1;
        }
    }
    public static function insertMenu($menu)
    {
        $id = self::getLastId() + 1;
        $con = getConnection();
        $audioTLE = $audioOpcionInvalida = $audioPrincipal = "NONE";
        if ($menu->getAudioTLE() != null) {
            if (AudioDatos::saveAudio($menu->getAudioTLE()) != 0) {
                $audioTLE = "NONE";
            } else {
                $audioTLE = $menu->getAudioTLE()->getHash();
            }
        }
        if ($menu->getAudioPrincipal() != null) {
            if (AudioDatos::saveAudio($menu->getAudioPrincipal()) != 0) {
                $audioPrincipal = "NONE";
            } else {
                $audioPrincipal = $menu->getAudioPrincipal()->getHash();
            }
        }
        if ($menu->getAudioOpcionInvalida() != null) {
            if (AudioDatos::saveAudio($menu->getAudioOpcionInvalida()) != 0) {
                $audioOpcionInvalida = "NONE";
            } else {
                $audioOpcionInvalida = $menu->getAudioOpcionInvalida()->getHash();
            }
        }
        $query = "INSERT INTO vicidial_call_menu (menu_id, menu_name, user_group, menu_prompt, menu_timeout_prompt, menu_invalid_prompt,call_time_id) VALUES (
				$id,
				'" . $menu->getNombre() . "',
				'" . $menu->getCliente()->getId() . "',
				'" . $audioPrincipal . "',
				'" . $audioTLE . "',
				'" . $audioOpcionInvalida . "',
				'" . $menu->getCallTimeId() . "'

			)";
        $resp = 0;
        if (sv_mysqli_query($con, $query)) {
            $resp = 0;
            sv_mysqli_query($con, "UPDATE servers set rebuild_conf_files='Y' where generate_vicidial_conf='Y' and active_asterisk_server='Y'");
        } else {
            $resp = -1;
        }
        sv_mysqli_close($con);
        return $resp;
    }

    public static function getMenuById($id)
    {
        $con = getConnection();
        $query = "SELECT menu_id, menu_name, menu_prompt, menu_invalid_prompt, menu_timeout_prompt,user_group,call_time_id FROM vicidial_call_menu WHERE menu_id = '" . limpia($id) . "'";
        $result = sv_mysqli_query($con, $query);
        $resp = null;
        if ($row = sv_mysqli_fetch_array($result)) {
            $resp = new Menu(
                $row["menu_id"],
                $row["menu_name"],
                ClienteDatos::getClienteById($row["user_group"]),
                AudioDatos::getAudioByHash($row["menu_invalid_prompt"]),
                AudioDatos::getAudioByHash($row["menu_prompt"]),
                AudioDatos::getAudioByHash($row["menu_timeout_prompt"]),
                $row["call_time_id"],
            );
        }
        return $resp;
    }

    // Agregados para el drag'n drop
    public static function getAllMenusByTypeAndClient($cliente, $tipo)
    {
        $con = getConnection();
        $query = "SELECT menu_id, menu_name FROM vicidial_call_menu WHERE user_group = '" . $cliente->getId() . "' AND menu_name LIKE '%_$tipo'";
        $result = sv_mysqli_query($con, $query);
        $resp = array();
        while ($row = sv_mysqli_fetch_array($result)) {
            array_push($resp, new Menu(
                $row["menu_id"],
                $row["menu_name"]
            ));
        }
        return $resp;
    }
    // Agregados para el drag'n drop
}
