<?php
function getConnection()
    {
        $host = 'localhost';
        $db_name = 'rmco_site';
        $username = 'rmco_site';
        $password = '*s@W*&&2vT9g';
        $conn= new mysqli($host, $username, $password, $db_name);
        if ($conn->connect_error) {
            $conn= null;
        }
        return $conn;
    }
    
   
	
	
function tirarAcentos($string){
  $string =  preg_replace(array("/(á|à|ã|â|ä)/","/(Á|À|Ã|Â|Ä)/","/(é|è|ê|ë)/","/(É|È|Ê|Ë)/","/(í|ì|î|ï)/","/(Í|Ì|Î|Ï)/","/(ó|ò|õ|ô|ö)/","/(Ó|Ò|Õ|Ô|Ö)/","/(ú|ù|û|ü)/","/(Ú|Ù|Û|Ü)/","/(ñ)/","/(Ñ)/","/(ç)/","/(Ç)/"),explode(" ","a A e E i I o O u U n N c C"),$string);
  $char = array(' & ', 'ª ', '  (', ') ', '(', ')', ' - ', ' / ', ' /', '/ ', '/', ' | ', ' |', '| ', ' | ', '|', '_', '.', ' ');
  return (str_replace($char, '-', $string));

}


$key='c1b71d066008b7e2fd75c999e8cee777';
$chave=$_GET['key'];
$final_key=md5($chave);
$n=$_GET['n'];
$num=$_GET['num'];
$q=$_GET['n'];
$pattern = '/&nbsp;/i';
//$foto="https://www.rm.co.mz/rm.co.mz/media/k2/items/src/";

$mes = date("m");  
$ano  = date("Y");   
 
//$foto="http://localhost/radio/wp-content/uploads/";
$foto="https://www.rm.co.mz/wp-content/uploads";

if ($key == $final_key){

 $conn=getConnection();
  mysqli_set_charset($conn,"utf8");
 header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json; charset=UTF-8');
function sendResponse($resp_code,$data,$message){
    echo json_encode(array('code'=>$resp_code,'message'=>$message,'data'=>$data));
}

if($conn==null){
    sendResponse(500,$conn,'Server Connection Error');
}else{
    
    
    $page_no = $q;
	$total_records_per_page =$num ;
    	$offset = ($page_no-1) * $total_records_per_page;
	$previous_page = $page_no - 1;
	$next_page = $page_no + 1;
	$adjacents = "2";
	$result_count = mysqli_query($strcon,"SELECT COUNT(*) As total_records FROM wp_posts  ");
	$total_records = mysqli_fetch_array($result_count);
	$total_records = $total_records['total_records'];
   	 $total_no_of_pages = ceil($total_records / $total_records_per_page);
	$second_last = $total_no_of_pages - 1; // total page minus 1

	$sql = "SELECT p1.*,p1.ID as id, wm2.meta_value ,wt.*,wtr.*,wu.ID,wu.user_nicename FROM wp_posts p1 
	LEFT JOIN wp_postmeta wm1 ON ( wm1.post_id = p1.ID AND wm1.meta_value IS NOT NULL AND wm1.meta_key = '_thumbnail_id' )
	LEFT JOIN wp_postmeta wm2 ON ( wm1.meta_value = wm2.post_id AND wm2.meta_key = '_wp_attached_file' AND wm2.meta_value IS NOT NULL )
	INNER JOIN wp_term_relationships wt ON p1.ID =wt.object_id 
	INNER JOIN wp_terms wtr ON wt.term_taxonomy_id =wtr.term_id
	INNER JOIN wp_users wu ON p1.post_author = wu.ID 
	WHERE (wtr.name='Sociedade' OR wtr.name='Economia' OR wtr.name='Cultura' OR wtr.name='Mundo' OR wtr.name='Ciência &amp; Tecnologia' OR  wtr.name='Política' OR wtr.name='Breves' OR wtr.name='Recomendado' OR wtr.name='Desporto') and (p1.post_status='publish' AND p1.post_type='post') ORDER BY p1.post_date DESC Limit $offset,$total_records_per_page";
	
	
	$result = $conn->query($sql);

  if ($result->num_rows > 0) {
        $users=array();
        while($row = $result->fetch_assoc()) {
          $full= strip_tags($row["post_content"]);
        $date=date_create($row["post_date"]);
		$ano==date_format($date,"Y");
		$mes=date_format($date,"m");
		//$url=tirarAcentos($row["post_title"],);
		$url=($row["meta_value"]);
       $datafinal =date_format($date,"d-m-Y");
          // $full= preg_replace($pattern, '', $full);
            $user=array(
                "id" => $row["id"],
                "title" => $row["post_title"],
                "introtext" => strip_tags($row["post_excerpt"]),
                "fulltext" =>strip_tags($row["post_content"]),
                "categoria" => str_replace( '&amp;', '', $row["name"] ), 
                 "jornalista" => $row["user_nicename"],
                 "data" => $datafinal,
				"Image" =>$foto."/".$url,
            );
            array_push($users,$user);
        }
        sendResponse(200,$users,'Lista de noticias');
    } else {
        sendResponse(404,[],'Lista nao disponivel');
    }
    $conn->close();
}

}else{
     $myObj->Erro = "401";
$myObj->Solucao = "contacte o departamento de informatica da RM";
$myObj->Messagem = "Cade a chave??????";

$myJSON = json_encode($myObj);

echo $myJSON;
}

?>










