<?php

ini_set('display_errors', 1);
ini_set('display_startup_erros', 1);
error_reporting(E_ALL); 

include_once(__DIR__."/../config.php"); 

$cs = new cs;

$id_unf  = (int) $_SESSION['info_unf']['id'];  
$request = [];

if (isset($_POST) or isset($_GET)) {
  $request = (!empty($_POST)) ? $_POST : $_GET;
}

if(isset($request['id']) && !empty($request['id']))
{
      
  $id = $cs->filterKey($request['id']); 
  
  $consulta = (!empty($id)) ? "WHERE u.id = '$id' OR u.login = '$id'": '';
  
  $query = (in_array($id_unf, [1,1010101010])) ? 
      "select u.*, x.max_connections from usuarios u LEFT JOIN xtream_iptvpro.users x ON u.iptv_id_user = x.id $consulta" : 
      "select u.*, x.max_connections from usuarios u LEFT JOIN xtream_iptvpro.users x ON u.iptv_id_user = x.id WHERE (u.id = '$id' OR u.login = '$id') AND (u.id_gerenciador = $id_unf OR u.id_pai = $id_unf)";  
  

  $row = [ 'user' => $cs->fetchQuery($cs->executeQuery($query))  ];  
      
  $profiles = $cs->fetchQuery($cs->executeQuery("SELECT * from profiles"));

  //var_dump($profiles); exit;
  foreach ($profiles as $value) {
      
    $row['profiles_group'][] = $value;   
  
  } 
   
  echo json_encode($row);
  exit;
} else if (isset($request['usuarios_ativos']) && in_array($id_unf, [1,1010101010])) {
  //var_dump($_POST); exit;
  ## Read value
  $draw            = $request['draw'];
  $row             = $request['start'];
  $rowperpage      = $request['length']; // Rows display per page
  $columnIndex     = $request['order'][0]['column']; // Column index
  $columnName      = $request['columns'][$columnIndex]['data']; // Column name
  $columnSortOrder = $request['order'][0]['dir']; // asc or desc
  $searchValue     = $request['search']['value'] ?? ''; // Search value
  $search          = $request['search'] ?? ''; // Search value
  //$min             = $request['min'];
  //$max             = $request['max'];
  //$status          = $request['status'];
  //$profile         = $request['profile'];

  //var_dump($row, $rowperpage);
  ## Search 
    
  $searchQuery = (isset($search) && !empty($search)) ? " and 
    u.username like '%".$search."%' 
    or s.stream_display_name like '%".$search."%' 
    or a.user_ip like '%".$search."%'" : ' ';

  //$searchQuery .= (isset($min) && !empty($min)) ? " and DATE(vencimento) >= '".date('Ymd', strtotime($min))."' " : ' ';    

  //$searchQuery .= (isset($max) && !empty($max)) ? " and DATE(vencimento) <= '".date('Ymd', strtotime($max))."' " : ' ';

  //$searchQuery .= (isset($status) && !empty($status)) ?  " and status = '$status' " : ' ';    

  //$searchQuery .= (isset($profile) && !empty($profile)) ? " and profile = '$profile' " : ' ';    

  //var_dump($searchQuery);
  ## Total number of records without filtering
  $query = "select count(*) as allcount from xtream_iptvpro.users u 
      INNER JOIN 
	    xtream_iptvpro.user_activity_now a  
	ON
	    u.id = a.user_id     
	    
	INNER JOIN 
	    xtream_iptvpro.streams s 
	ON 
	    a.stream_id = s.id ";

  $sel = $cs->executeQuery($query);
  $records = $cs->fetchQuery($sel);

  $totalRecords = $records[0]['allcount'];



  ## Total number of record with filtering
  $query = "select count(*) as allcount from xtream_iptvpro.users u 
    INNER JOIN 
	    xtream_iptvpro.user_activity_now a  
	ON
	    u.id = a.user_id     
	    
	INNER JOIN 
	    xtream_iptvpro.streams s 
	ON 
	    a.stream_id = s.id
	WHERE 1 $searchQuery"; 
  //var_dump(trim($searchQuery));
  $sel = $cs->executeQuery($query);
  $records = $cs->fetchQuery($sel);
  $totalRecordwithFilter = $records[0]['allcount'];

  //WHERE a.user_id = '$user_id' and 1 ".$searchQuery."
  ## Fetch records
  $empQuery = "
	select 
	    u.username, 
	    a.user_id, 
	    a.stream_id, 
	    a.user_ip, 
	    s.stream_display_name, 
	    s.stream_icon 
	from 
	    xtream_iptvpro.users u
	INNER JOIN 
	    xtream_iptvpro.user_activity_now a  
	ON
	    u.id = a.user_id     
	    
	INNER JOIN 
	    xtream_iptvpro.streams s 
	ON 
	    a.stream_id = s.id       
    
    WHERE 1 $searchQuery
	            
	GROUP BY a.activity_id
	
    order by u.".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;

 // var_dump($empQuery); exit;
  $empRecords = $cs->executeQuery($empQuery);

  $data = array();

  foreach ($cs->fetchQuery($empRecords) as $row) {
     
   // var_dump($row); exit;
    $data[] = array( 
      "user_id"             => $row['user_id'],
      "username"            => $row['username'],
      "stream_display_name" => $row['stream_display_name'],
      "stream_icon"         => $row['stream_icon'],
      "user_ip"             => $row['user_ip']
    );
  }

  ## Response
  $response = array(
    "draw"                 => intval($draw),
    "iTotalRecords"        => $totalRecords,
    "iTotalDisplayRecords" => $totalRecordwithFilter,
    "aaData"               => $data,
    "search"               => $empQuery
    //"min"                  => $min,
    //"max"                  => $max 
   );

  echo json_encode($response);   
}

if (isset($request['usuario']) && !empty($request))
{

  //var_dump($request); exit; 
  ## Read value
  $draw            = $request['draw'];
  $row             = $request['start'];
  $rowperpage      = $request['length']; // Rows display per page
  $columnIndex     = $request['order'][0]['column']; // Column index
  $columnName      = $request['columns'][$columnIndex]['data']; // Column name
  $columnSortOrder = $request['order'][0]['dir']; // asc or desc
  $searchValue     = $request['search']['value'] ?? ''; // Search value
  $search          = $request['search']; // Search value
  $min             = $request['min'];
  $max             = $request['max'];
  $status          = $request['status'];
  $profile         = $request['profile'];

  //var_dump($row, $rowperpage);
  ## Search 
  $searchQuery = " ";
   
  $searchQuery .= (isset($search) && !empty($search)) ?
    " and (display_name like '%".$search."%' or
          login like '%".$search."%' or 
          email like '%".$search."%' or 
          celular like'%".$search."%') " : ' ';

  $searchQuery .= (isset($min) && !empty($min)) ? " and DATE(vencimento) >= '".date('Ymd', strtotime($min))."' " : ' ';    

  $searchQuery .= (isset($max) && !empty($max)) ? " and DATE(vencimento) <= '".date('Ymd', strtotime($max))."' " : ' ';

  $searchQuery .= (isset($status) && !empty($status)) ?  " and status = '$status' " : ' ';    

  $searchQuery .= (isset($profile) && !empty($profile)) ? " and profile = '$profile' " : ' ';    



  $searchAdmin = " ";

  $searchAdmin .= (isset($search) && !empty($search)) ?
    " and (u.display_name like '%".$search."%' or
          u.login like '%".$search."%' or 
          u.email like '%".$search."%' or 
          u.celular like'%".$search."%') " : ' ';

  $searchAdmin .= (isset($min) && !empty($min)) ? " and DATE(u.vencimento) >= '".date('Ymd', strtotime($min))."' " : ' ';    

  $searchAdmin .= (isset($max) && !empty($max)) ? " and DATE(u.vencimento) <= '".date('Ymd', strtotime($max))."' " : ' ';

  $searchAdmin .= (isset($status) && !empty($status)) ?  " and u.status = '$status' " : ' ';    

  $searchAdmin .= (isset($profile) && !empty($profile)) ? " and u.profile = '$profile' " : ' ';    

  $searchAdmin = (trim($searchAdmin) == "") ? ''. $searchAdmin : "WHERE 1" . $searchAdmin;

  //var_dump($searchQuery);
  ## Total number of records without filtering
  $query = (in_array($id_unf, [1,1010101010])) ? "select count(*) as allcount from usuarios u $searchAdmin" : "select count(*) as allcount from v_usuario WHERE id_gerenciador = '$id_unf'";

  $sel = $cs->executeQuery($query);
  $records = $cs->fetchQuery($sel);

  $totalRecords = $records[0]['allcount'];



  ## Total number of record with filtering
  $query = (in_array($id_unf, [1,1010101010])) ? "select count(*) as allcount from usuarios u ".$searchAdmin : "select count(*) as allcount from v_usuario WHERE id_gerenciador = '$id_unf' and 1 ".$searchQuery; 
  //var_dump(trim($searchQuery));
  $sel = $cs->executeQuery($query);
  $records = $cs->fetchQuery($sel);
  $totalRecordwithFilter = $records[0]['allcount'];


  ## Fetch records
  $empQuery = (in_array($id_unf, [1,1010101010])) ? 
    "select u.*, p.profile_str as profile_str from usuarios u INNER JOIN profiles p ON u.profile = p.profile ".$searchAdmin." order by u.".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage : 
    
    "select * from v_usuario WHERE id_gerenciador = '$id_unf' and 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;

  //var_dump($empQuery, $columnName );
  $empRecords = $cs->executeQuery($empQuery);

  $data = array();

  foreach ($cs->fetchQuery($empRecords) as $row) {
     

      $data[] = array( 
          "id"           => $row['id'],
          "display_name" => $row['display_name'],
          "login"        => $row['login'],
          "email"        => $row['email'],
          "celular"      => $row['celular'],
          "vencimento"   => $row['vencimento'],
          "status"       => $row['status'],
          "profile"      => $row['profile'],
          "profile_str"  => $row['profile_str'],
     );
  }

  ## Response
  $response = array(
    "draw" => intval($draw),
    "iTotalRecords" => $totalRecords,
    "iTotalDisplayRecords" => $totalRecordwithFilter,
    "aaData" => $data,
    "search" => $searchQuery. ' - '.$searchAdmin,
    "min"    => $min,
    "max"    => $max 
   );

  echo json_encode($response);
 
} 




 //exit;    
?>