<?php 
require("config.php");
require("conexao.php");

if(isset($_GET['action'])){
	
	$action = $_GET['action'];
	
    function intervalo( $entrada, $saida ) {
       $entrada = explode( ':', $entrada );
       $saida   = explode( ':', $saida );
       $minutos = ( $saida[0] - $entrada[0] ) * 60 + $saida[1] - $entrada[1];
       if( $minutos < 0 ) $minutos += 24 * 60;
       return sprintf( '%d:%d', $minutos / 60, $minutos % 60 );
    }
    
    $act_log = $con->prepare("SELECT * FROM `act_log`");
    $act_log->execute();
    while($dados = $act_log->fetch(PDO::FETCH_ASSOC)){
        $id = $dados['id'];
        $dataH = $dados['hour'];
            $datetime1 = new DateTime(date("H:i:s"));
            $datetime2 = new DateTime($dataH);
            
            
            $intervalo = $datetime1->diff($datetime2);
            if($intervalo->format('%i') >= 1){
                $qr = $con->prepare("DELETE FROM `act_log` WHERE id=:ids");
                $qr->bindValue(":ids", $id);
                $qr->execute();
            }
    }
    
	switch ($action) {
	    case 'tv':
	    //token
	    if($_GET['token'] == "1234567654343245516712738123"){
			$query = $con->prepare("SELECT * FROM `tv`");
			$query->execute();
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			echo json_encode($dados);
		}
		break;
		case 'tv_view':
		//token
		if($_GET['token'] == "1234567654343245516712738123"){
		    $id = $_GET['id'];
			$query = $con->prepare("SELECT * FROM `tv` WHERE id=:id");
			$query->bindValue(':id', $id);
			$query->execute();
			$dados = array();
			$exec = $query->fetch(PDO::FETCH_ASSOC);
			echo json_encode($exec);
		}
		break;
		case 'last':
		//token
		if($_GET['token'] == "1234567654343245516712738123"){
			$query = $con->query("SELECT * FROM `filmes` ORDER BY id DESC");
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			$test = json_encode($dados);
			echo $test;																																												}																																								
			break;
		case 'lanc':
		//token
		if($_GET['token'] == "1234567654343245516712738123"){
			$query = $con->query("SELECT * FROM `filmes` ORDER BY year DESC, id DESC ");
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			$test = json_encode($dados);
			echo $test;																																}
			break;
		case 'epview':
		//token
		if($_GET['token'] == "1234567654343245516712738123"){
			$query = $con->prepare("SELECT * FROM `episode` WHERE id = :id");
			$query->bindValue(':id', $_GET['idv']);
			$query->execute();
			
			$test = json_encode($query->fetch(PDO::FETCH_ASSOC));
			echo $test;
		}
		break;
		case 'genero':
		//token
		if($_GET['token'] == "1234567654343245516712738123"){
			$genero = $_GET['genero'];
			$query = $con->prepare("SELECT * FROM `filmes` WHERE genero LIKE :genero ORDER BY id DESC");
			$query->bindValue(":genero", "%".$genero."%");
			$query->execute();
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			$test = json_encode($dados);
			echo $test;
		}
			break;
		case 'temp':
		//token
		if($_GET['token'] == "1234567654343245516712738123"){
			$serieid = $_GET['idf'];
			$query = $con->prepare("SELECT * FROM `temporada` WHERE idf = :idf ");
			$query->bindValue(":idf", $serieid);
			$query->execute();
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			$test = json_encode($dados);
			echo $test;
		}
		break;
		case 'search':
		//token &token=asdhiua))(s)(o_dgzxyhcu7t61273nhcxuzaiyt78213yuiaxsdyasdsadt677@_)(*
		if($_GET['token'] == "1234567654343245516712738123"){
			$s = $_GET['s'];
			if($s != NULL){
			$query = $con->prepare("SELECT * FROM `filmes` WHERE titulo LIKE :s ");
			$query->bindValue(":s", "%".$s."%");
			$query->execute();
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			$test = json_encode($dados);
			echo $test;
			}
		}
			break;
		case 'epall':
		if($_GET['token'] == "1234567654343245516712738123"){
			$temp 		= $_GET['temp'];
			$idfilm 	= $_GET['idf'];
			$query = $con->prepare("SELECT * FROM `episode`  WHERE temp= :temp && idf= :idf ");
			$query->bindValue(':temp', $temp);
			$query->bindValue(':idf', $idfilm);
			$query->execute();
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			echo json_encode($dados);
		}
			break;
		case 'playlist':
		if($_GET['token'] == "1234567654343245516712738123"){
				$iduser = $_GET['iduser'];

				$query = $con->prepare("SELECT * FROM `playlist` WHERE iduser = :idu  ORDER BY id DESC");
				$query->bindValue(":idu", $iduser);
				$query->execute();
				$dados = array();
				while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
					$idv = $exec['idfilm'];
					$fetch = $con->prepare("SELECT * FROM `filmes` WHERE id = :idv ");
					$fetch->bindValue(":idv", $idv);
					$fetch->execute();
					$dados[] = $fetch->fetch(PDO::FETCH_ASSOC);
				}
				$test = json_encode($dados);
				echo $test;
			}
			break;
		case 'recent':
		if($_GET['token'] == "1234567654343245516712738123"){
			$iduser = $_GET['iduser'];

			$query = $con->prepare("SELECT * FROM `recentes` WHERE iduser = :idu  ORDER BY id DESC");
			$query->bindValue(":idu", $iduser);
			$query->execute();

			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$idv = $exec['idfilm'];
				$fetch = $con->prepare("SELECT * FROM `filmes` WHERE id = :idv ");
				$fetch->bindValue(":idv", $idv);
				$fetch->execute();
				$dados[] = $fetch->fetch(PDO::FETCH_ASSOC);
			}
			$test = json_encode($dados);
			echo $test;
		}
			break;

		case 'lastmovie':
		if($_GET['token'] == "1234567654343245516712738123"){
			$query = $con->query("SELECT * FROM `filmes`  WHERE tipo='1' ORDER BY rating DESC");
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			echo json_encode($dados);
		}
			break;
		case 'verif':
		    $iduser = $_GET['iduser'];
			$qr = $con->prepare("SELECT * FROM `user` WHERE id= :user");
			$qr->bindValue(':user', $iduser);
			$qr->execute();
			$ftcuser= $qr->fetch(PDO::FETCH_ASSOC);
			
			$dataValid = $ftcuser['datevalid'];
			$dataHj    = date('Y-m-d');
			$dataRest = strtotime($dataValid) - strtotime($dataHj);
			$rest = floor($dataRest / (60 * 60 * 24));
			if($rest < 0){
			    $query  = $con->prepare("UPDATE `user` SET `validade`=:valid WHERE id=:iduser");
			    $query->bindValue(':valid', '0');
			    $query->bindValue(':iduser', $iduser);
			    $query->execute();
			}
			
		    break;
		case 'view':
		if($_GET['token'] == "1234567654343245516712738123"){
			$idV = $_GET['idvid'];
			
			if(isset($_GET['save'])){
			$save = $_GET['save'];
			$iduser = $_GET['iduser'];

				$query = $con->prepare("SELECT * FROM `recentes` WHERE iduser= :idmb && idfilm= :idvid");
					$query->bindValue(':idmb', $iduser);
					$query->bindValue(':idvid', $idV);
					$query->execute();

					if($query->rowCount() == 0){
						$exc = $con->prepare("INSERT INTO `recentes`(`iduser`, `idfilm`) VALUES (:iduser, :idfilm)");
						$exc->bindValue(':iduser',$iduser);
						$exc->bindValue(':idfilm', $idV);
						$exc->execute();
						
					}
			}
			
			    
    			$query = $con->prepare("SELECT * FROM `filmes`  WHERE id= :id");
    			$query->bindValue(':id',$idV);
    			$query->execute();
    			$dados = array();
    			$json = json_encode($exec = $query->fetch(PDO::FETCH_ASSOC));
		
			
			echo $json;
		}
			break;
		
		case 'config':
		if($_GET['token'] == "1234567654343245516712738123"){
			$query = $con->query("SELECT * FROM `config_app`  ORDER BY id DESC");
			
			echo json_encode($query->fetch(PDO::FETCH_ASSOC));
		}
			break;

		case 'lastseries':
		if($_GET['token'] == "1234567654343245516712738123"){
			$query = $con->query("SELECT * FROM `filmes`  WHERE tipo='2' ORDER BY id DESC");
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			echo json_encode($dados);
			}
			break;
		case 'allmovies':
			$query = $con->query("SELECT * FROM `filmes`  WHERE tipo='1' ORDER BY id DESC ");
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			echo json_encode($dados);
			break;
		case 'allseries':
			$query = $con->query("SELECT * FROM `filmes`  WHERE tipo='2' ORDER BY id DESC ");
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			echo json_encode($dados);
			break;
		case 'categorietitle':
			$query = $con->query("SELECT * FROM `category` ORDER BY categoria ASC ");
			$dados = array();
			while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
				$dados[] = $exec;
			}
			echo json_encode($dados);
		break;
		case 'category':
		if($_GET['token'] == "1234567654343245516712738123"){
				$query = $con->prepare("SELECT * FROM `filmes` WHERE genero LIKE :genero");
				$query->bindValue(':genero', "%".$_GET['c']."%", PDO::PARAM_STR);
				$query->execute();
				$dados = array();
				while ($exec = $query->fetch(PDO::FETCH_ASSOC)) {
					$dados[] = $exec;
				}
				echo json_encode($dados);
			}
		break;
		case 'cadastro':
			$login 				= $_GET['login'];
			$mail 				= $_GET['mail'];
			$password 			= md5($_GET['pass']);
			$token 				= $_GET['token'];

			if($token == "1234567654343245516712738123"){
				$query = $con->prepare("SELECT * FROM `user` WHERE email= :email");
				$query->bindValue(':email', $mail);
				$query->execute();
				if($query->rowCount() == 0 or $query->rowCount() < 1){
					$cad = $con->prepare("INSERT INTO `user`(`username`, `email`, `password`, `dateCreate`, `validade`, `datevalid`) VALUES (:user, :mail, :pass, :datecreate, :valid, :datevalid )");
					$cad->bindValue(':user', $login);
					$cad->bindValue(':mail', $mail);
					$cad->bindValue(':pass', $password);
					$cad->bindValue(':valid', 0);
					$cad->bindValue(':datevalid', 0);
					$cad->bindValue(':datecreate', date('Ymd'));
					if($cad->execute()){
							$array = array('msg' => "Cadastrado com sucesso");
							$a =  json_encode($array);
							echo $a;
					}else{
						$array = array('msg' => "Erro ao Criar" );
						echo json_encode($array);
					}
				}else{
				
						$array = array('msg' => "Email já cadastrado" );
						$a = json_encode($array);
						echo $a;
				}


			}
			break;
			case 'imeicheck':
			if($_GET['token'] == "1234567654343245516712738123"){
			    $imei = $_GET['imei'];
			    $idc  = $_GET['idc'];
			    $data = date("Y/m/d");
			    
			    $d = $con->prepare("DELETE FROM `act_log` WHERE datehour != :datse");
			    $d->bindValue(":datse", $data);
			    $d->execute();
			    
			    $quer1 = $con->prepare("SELECT * FROM `act_log` WHERE idc=:idc");
			    $quer1->bindValue(':idc', $idc);
			    $quer1->execute();
			    
			    $user = $con->prepare("SELECT * FROM `user` WHERE id=:id");
			    $user->bindValue(':id', $idc);
			    $user->execute();
			    $ftc = $user->fetch(PDO::FETCH_ASSOC);
			    $maxtela = $ftc['maxtela'];
			    
			    $query = $con->prepare("SELECT * FROM `act_log` WHERE imei=:imei && idc=:idc");
			    $query->bindValue(':imei', $imei);
			    $query->bindValue(':idc', $idc);
			    $query->execute();
			    if($query->rowCount() == 1){
			        $ft = $query->fetch(PDO::FETCH_ASSOC);
			        $idqr  = $ft['id'];
			        	$qr = $con->prepare("UPDATE `act_log` SET `hour`=:hour WHERE id=:ids");
			        	$qr->bindValue(':ids', $idqr);
            			$qr->bindValue(':hour', date("H:i:s"));
            			$qr->execute();
			        $atr = array("msg"=>"Autorizado","validade"=>1);
			        echo json_encode($atr);
			    }else{
			        if($quer1->rowCount() < $maxtela){
                        		$qr = $con->prepare("INSERT INTO `act_log`(`imei`, `idc`, `datehour`, `hour`) VALUES (:imei, :idc, :dateh, :hour)");
            			        $qr->bindValue(':imei', $imei);
            			        $qr->bindValue(':idc', $idc);
            			        $qr->bindValue(':dateh', date("Y/m/d"));
            			        $qr->bindValue(':hour', date("H:i:s"));
            			        $qr->execute();

			                 $atr = array("msg"=>"Autorizado","validade"=>1);
			               echo json_encode($atr);
			            
			        }else{
			            $atr = array("msg"=>"Limite Atingido","validade"=>0);
			            echo json_encode($atr);
			        }
			        
			        
			    }
			   
			    
			    }
			    
			break;
			case 'logstatus':

				if($_GET['token'] == "1234567654343245516712738123"){
				$id = $_GET['id'];
                
				$query = $con->prepare("SELECT * FROM `user` WHERE id= :id ");
				$query->bindValue(':id', $id);
				$query->execute();
				if($query->rowCount() == 1){
					$fetch = $query->fetch(PDO::FETCH_ASSOC);
					$data_final = $fetch['datevalid'];
            		$data_inicial = date("Y-m-d");
            
            		$diferenca = strtotime($data_final) - strtotime($data_inicial);
                	$restante = floor($diferenca / 86400);
                	if($restante < 0){
                	    $qr = $con->prepare("UPDATE `user` SET `validade`=:valid WHERE id =:idc");
                	    $qr->bindValue(':valid', '0');
                	    $qr->bindValue(':idc', $id);
                	    $qr->execute();
                	$array = array(
						'msg' 		=> "Login Completo",
						'validade'		=> "0"
					 );
					
                	    
                	}else{
                	    $array = array(
						'msg' 		=> "Login Completo",
						'validade'		=> $fetch['validade']
					 );
					
                	}
                	
					$a = json_encode($array);
					echo $a;
				}
				}
			break;
			case 'log':
			if($_GET['token'] == "1234567654343245516712738123"){
				$email = $_GET['mail'];
				$pass  = md5($_GET['pass']);

				$query = $con->prepare("SELECT * FROM `user` WHERE email= :email && password= :pass");
				$query->bindValue(':pass', $pass);
				$query->bindValue(':email', $email);
				$query->execute();
				if($query->rowCount() == 1){
					$fetch = $query->fetch(PDO::FETCH_ASSOC);
					$array = array(
						'msg' 		=> "login Completo",
						'cod'		=> '1',
						'idConta'	=> $fetch['id'],
						'email'		=> $fetch['email'],
						'user'		=> $fetch['username'],
						'pass' 		=> $fetch['password']
					 );
					$a = json_encode($array);
					echo $a;
				}else{
					$array = array('msg' => "Email ou Senha incorreta", 'cod' => '0' );
						$a = json_encode($array);
						echo $a;
				}
			}
			break;
			case 'addmylist':
				if($_GET['token'] == "1234567654343245516712738123"){

					$idvid = $_GET['idvid'];
					$idmb  = $_GET['idmb'];

					$query = $con->prepare("SELECT * FROM `playlist` WHERE iduser= :idmb && idfilm= :idvid");
					$query->bindValue(':idmb', $idmb);
					$query->bindValue(':idvid', $idvid);
					$query->execute();
					if($query->rowCount() == 0){
						$exc = $con->prepare("INSERT INTO `playlist`(`iduser`, `idfilm`) VALUES (:iduser, :idfilm)");
						$exc->bindValue(':iduser',$idmb);
						$exc->bindValue(':idfilm', $idvid);
						if($exc->execute()){
							$array  = array('msg' => "Adicionado com sucesso", 'cod'=>'1' );
						}else{
							$array  = array('msg' => "Erro ao adicionar", 'cod'=>'0' );
						}
						echo json_encode($array);
					}else{
						$exc = $con->prepare("DELETE FROM `playlist` WHERE iduser= :idmb && idfilm= :idvid");
						$exc->bindValue(':idmb', $idmb);
						$exc->bindValue(':idvid', $idvid);
					
						if($exc->execute()){
							$array  = array('msg' => "Removido com sucesso", 'cod'=>'2' );
						}else{
							$array  = array('msg' => "Erro ao adicionar", 'cod'=>'0' );
						}
						echo json_encode($array);
					}
				}
			break;
			case 'listcheck':
				if($_GET['token'] == "1234567654343245516712738123"){

					$idvid = $_GET['idvid'];
					$idmb  = $_GET['idmb'];

					$query = $con->prepare("SELECT * FROM `playlist` WHERE iduser= :idmb && idfilm= :idvid");
					$query->bindValue(':idmb', $idmb);
					$query->bindValue(':idvid', $idvid);
					$query->execute();
					$array = array('result' => $query->rowCount());
					echo json_encode($array);
					
				}
			break;
		case 'errorvid':
			if($_GET['token'] == "1234567654343245516712738123"){
				$idvid = $_GET['idvid'];
					$query = $con->prepare("SELECT * FROM `errorvid` WHERE id= :idv");
					$query->bindValue(':idv', $idvid);
					$query->execute();
					if($query->rowCount() == 0){
						$ex = $con->prepare("INSERT INTO `errorvid`(`erroid`) VALUES (:idv)");
						$ex->bindValue(':idv', $idvid);
						$ex->execute();
						
					}

			}
		break;

		default:
			# code...
			break;
	}

}
?>