<?php

// function detect is abn active 


$servername = "localhost";
$username = "mhdata_wp_xeicz";
$password = "yQnZb25*xW&R1y8u";
$db = "mhdata_wp_ifw0v";


// Create connection
$conn = new mysqli($servername, $username, $password,$db);

$conn->set_charset("utf8");


function isActiveToken($the_json){

 global $conn;
// isActiveToken

$wp_c_g_token = $the_json['wp_c_g_token'];

$host = $the_json['host'];

$host=str_replace("http://","","$host"); 
$host=str_replace("https://","","$host"); 
$host=str_replace("/","","$host"); 
$host=str_replace("www.","","$host"); 

 $sql_tokens = "select count(*) as c from tokens where (active=1 OR active_always=1) and blocked=0 and (token='$wp_c_g_token' and REPLACE(host_name, 'https://', '')='$host')";
 
// echo $sql_tokens;die();

 $result = mysqli_query($conn,$sql_tokens);
 
 $count_tokens = mysqli_fetch_object($result);
 

$count_tokens = $count_tokens->c;

return $count_tokens ;
}

function setHistToken($wp_c_g_token,$insData,$to_use_api=0){
 global $conn;
 
 // hist tokens
 $sql = sprintf(
    'INSERT INTO  hist_tokens (%s) VALUES ("%s")',
    implode(',',array_keys($insData)),
    implode('","',array_values($insData))
);


 $result = mysqli_query($conn,$sql);
 
 
 // count_query  
$sql_count_query="SELECT count(*) as c  FROM hist_tokens where token='$wp_c_g_token'";
$count_query = mysqli_query($conn,$sql_count_query);
$count_query = mysqli_fetch_object($count_query);
$count_query = $count_query->c;

$m=date("m"); $y=date("Y");

 // c_q_this_month  
$sql_c_q_this_month="SELECT count(*) as c  FROM hist_tokens where token='$wp_c_g_token' and month(date)='$m' and year(date)='$y'";
$c_q_this_month= mysqli_query($conn,$sql_c_q_this_month);
$c_q_this_month = mysqli_fetch_object($c_q_this_month);
$c_q_this_month = $c_q_this_month->c;

     
// update tokens
$sql_update = "update tokens set to_use_api='$to_use_api' ,c_q_this_month='$c_q_this_month',last_update='".date('Y-m-d H:i:s')."',count_query='".$count_query."' where token='".$wp_c_g_token."'";
$result_update = mysqli_query($conn,$sql_update);
}


function returnError($text)
{

  $DataToExport = [];
  $DataToExport['error'] = 1;
  $DataToExport['message'] = "Erreur :  $text";
  header('Content-Type: application/json; charset=utf-8');

  echo json_encode($DataToExport);

  return;
}



?>