<?php
    require_once 'Audio.php';
    require_once RUTA_APP.'Conexion.php';
    class AudioDatos{
        public static function deleteAudio($audio){            
            if(self::getAudioById($audio->getId()) != NULL){
                $con = getConnection();
                $query = "UPDATE dialvox_audio SET visible = FALSE WHERE id = '".$audio->getId()."'";
                sv_mysqli_query($con,$query);
                return 0;
            }else{
                return -1;
            }
        }
        public static function getAudioById($id){
            $con = getConnection();
            $query = "SELECT Nombre,Audio,FechaCarga,Hash,MimeType,id,Cliente FROM dialvox_audio WHERE id = '".limpia($id)."' AND Visible = TRUE LIMIT 1";
            $resp = NULL;
			$result = sv_mysqli_query($con,$query);
            if($row = sv_mysqli_fetch_array($result)){
                    $resp = new Audio(
                        ClienteDatos::getClienteById($row["Cliente"]),
                        $row["Nombre"],
                        $row["FechaCarga"],
                        $row["id"],
                        $row["Hash"],
                        $row["MimeType"],
						$row["Audio"]
                    );
            }
            sv_mysqli_close($con);
			return $resp;
        }
        public static function getAllAudiosByCliente($cliente){
            $con = getConnection();
            $query = "SELECT Nombre,id,Hash FROM dialvox_audio WHERE Cliente = '".limpia($cliente->getId())."' AND Visible = TRUE ORDER BY id DESC";		
            $resp = array();
			$result = sv_mysqli_query($con,$query);
            while($row = sv_mysqli_fetch_array($result)){
                    array_push($resp, new Audio(
                        null, // Cliente
                        $row["Nombre"],
                        null, // ????
                        $row["id"],
                        $row["Hash"],
                        null // ???
                    ));
            }
            sv_mysqli_close($con);
			return $resp;
        }
		public static function countAudiosByCliente($cliente,$texto){
			$con = getConnection();
            $query = "SELECT COUNT(id) AS Cuenta FROM dialvox_audio WHERE Cliente = '".limpia($cliente->getId())."' AND Visible = TRUE AND Nombre LIKE '%".limpia($texto)."%' LIMIT 1";
			$result = sv_mysqli_query($con,$query);
            $resp = 0;
            if($row = sv_mysqli_fetch_array($result)){
				$resp = $row["Cuenta"];
            }
            sv_mysqli_close($con);
			return $resp;
		}
		public static function countAudios($texto){
			$con = getConnection();
            $query = "SELECT COUNT(id) AS Cuenta FROM dialvox_audio WHERE Visible = TRUE AND Nombre LIKE '%".limpia($texto)."%' LIMIT 1";
			$result = sv_mysqli_query($con,$query);
            $resp = 0;
            if($row = sv_mysqli_fetch_array($result)){
				$resp = $row["Cuenta"];
            }
            sv_mysqli_close($con);
			return $resp;
		}
        public static function getAudiosByCliente($cliente, $pagina, $limite,$texto){
			$con = getConnection();
            $query = "SELECT Nombre,FechaCarga,Hash,MimeType,id,Cliente FROM dialvox_audio WHERE Cliente = '".limpia($cliente->getId())."' AND Visible = TRUE AND Nombre LIKE '%".limpia($texto)."%' ORDER BY id DESC LIMIT ".($pagina*$limite).",".$limite;			
            $resp = array();
			$result = sv_mysqli_query($con,$query);
            while($row = sv_mysqli_fetch_array($result)){
                    array_push($resp,new Audio(
                        ClienteDatos::getClienteById($row["Cliente"]),
                        $row["Nombre"],
                        $row["FechaCarga"],
                        $row["id"],
                        $row["Hash"],
                        $row["MimeType"]
                    ));
            }
            sv_mysqli_close($con);
			return $resp;
        }
        public static function getAudios($pagina, $limite,$texto){
		$con = getConnection();
            $query = "SELECT Nombre,FechaCarga,Hash,MimeType,id,Cliente FROM dialvox_audio WHERE Visible = TRUE AND Nombre LIKE '%".limpia($texto)."%' ORDER BY id DESC LIMIT ".($pagina*$limite).",".$limite;			
            $resp = array();
			$result = sv_mysqli_query($con,$query);
            while($row = sv_mysqli_fetch_array($result)){
                    array_push($resp,new Audio(
                        ClienteDatos::getClienteById($row["Cliente"]),
                        $row["Nombre"],
                        $row["FechaCarga"],
                        $row["id"],
                        $row["Hash"],
                        $row["MimeType"]
                    ));
            }
            sv_mysqli_close($con);
			return $resp;
        }
        public static function getAllAudios(){

        }
        public static function insertAudio($audio){
			if(self::getAudioByHash($audio->getHash()) == NULL){
				$con = getConnection();
				$query = "INSERT INTO dialvox_audio (Nombre, FechaCarga,Audio,Hash,Visible,Cliente,MimeType) VALUES (
				'".limpia($audio->getNombre())."',
				NOW(),
				'".limpia($audio->getBinario())."',
				'".limpia($audio->getHash())."',
				TRUE,
				'".limpia($audio->getCliente()->getId())."',
				'".limpia($audio->getMimeType())."'
				)";
				$ret = 0;
				if(sv_mysqli_query($con,$query)){
					$ret = 0;
				}else{
					$ret = -1;
				}
				sv_mysqli_close($con);
				return $ret;
			}else{
				return -1;
			}
        }
		public static function getAudioByHash($hash){
            $con = getConnection();
            $query = "SELECT * FROM dialvox_audio WHERE Hash = '".limpia($hash)."' AND Visible = TRUE LIMIT 1";
            $resp = NULL;
			$result = sv_mysqli_query($con,$query);
            if($row = sv_mysqli_fetch_array($result)){
                    $resp = new Audio(
                        ClienteDatos::getClienteById($row["Cliente"]),
                        $row["Nombre"],
                        $row["FechaCarga"],
                        $row["id"],
                        $row["Hash"],
                        $row["MimeType"],
						$row["Audio"]
                    );
            }
            sv_mysqli_close($con);
			return $resp;
        }
		public static function saveAudio($audio){
			$preFile = '/var/lib/asterisk/sounds/pre_'.$audio->getHash();
			$postFile = '/var/lib/asterisk/sounds/'.$audio->getHash().".wav";
			if(file_exists($preFile))unlink($preFile);
			if(file_exists($postFile))unlink($postFile);			
			//$destino = fopen('/var/lib/asterisk/sounds/pre_'.$audio->getHash(), 'w');
			$fp = fopen($preFile, 'w');
			fwrite($fp, $audio->getBinario());
			fclose($fp);			
			//$comando = "ffmpeg -i ".$preFile." -acodec pcm_u8 -ar 16000 -sample_fmt s16 -ac 1 -framerate 2 ".$postFile;
			$comando = "ffmpeg -i ".$preFile." -acodec pcm_s16le -ar 8000 -sample_fmt s16 -ac 1 -framerate 2 ".$postFile;
			$xd = shell_exec($comando);
			if($xd != null)return -1;
			return 0;										
		}
    }
?>
