<?php

// generate json web token
include_once '../../_public/api_config.php';
include_once '../../_library/php-jwt-master/src/BeforeValidException.php';
include_once '../../_library/php-jwt-master/src/ExpiredException.php';
include_once '../../_library/php-jwt-master/src/SignatureInvalidException.php';
include_once '../../_library/php-jwt-master/src/JWT.php';

use \Firebase\JWT\JWT;

if (isset($_SERVER['HTTP_ORIGIN'])) {
   header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
   header('Access-Control-Allow-Credentials: true');
   header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
   if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
      header("Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS");
   if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
      header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
   exit(0);
}

$jwt = null;
foreach (getallheaders() as $name => $value) {
   if ($name == "Key") {
      $jwt = $value;
   }
}

$post_data = file_get_contents("php://input");
if (empty($post_data)) {
   $request = json_decode(json_encode($_POST));
} else {
   $request = json_decode($post_data);
}

$_POST = (array) $request;

/* try {
  $decoded_key = JWT::decode($jwt, getenv('api_key'), array('HS256'));
  if ($decoded_key->username === getenv('api_user')) {
  if ($decoded_key->password === getenv('api_password')) {
  //continue below
  } elseif ($decoded_key->password !== getenv('api_password')) {
  //echo "e1";
  header("HTTP/1.1 405 Method not NotAllowed");
  exit();
  }
  } else {
  //echo "e2";
  header("HTTP/1.1 405 Method not NotAllowed");
  exit();
  }
  } catch (Exception $e) {
  //echo "e3";
  //echo $e->getTraceAsString();
  header("HTTP/1.1 405 Method not NotAllowed");
  exit();
  } */

//print_r($_POST);

$do = $_GET["ac"];

switch ($do) {
   case "addVisit":
      addNewVisit();
      break;

   case "addPatient":
      addNewPatient();
      break;

   default:
      break;
}

function addNewVisit() {

   $result = array("success" => 0, "error" => 0, "errorMsg" => '', "ex" => "");
   $patientId = (int) $_POST['patient_id'];
   $date = $_POST['visit_date'];
   //  $_POST['detectionid'] = 73;
   $_POST['payVisit'] = 0;
   $_POST['patientid'] = $patientId;
   $_POST['visitdate'] = $date;
   $_POST['detectionid'] = $_POST['detection_id'];
   $_POST['clinic_id'] = $_POST['clinic_id'];
   $available = 1;

   if ($date == '' || is_null($date)) {
      $result['success'] = 0;
      $result['error'] = 1;
      $result['errorMsg'] = "Visit Date  Required";
      $result['ex'] = "";
      $available = 0;
   }

   if ($patientId > 0) {
      $result = checkPatientExist($patientId, $result);
      $available = $result['success'];
   } else {
      $result['success'] = 0;
      $result['error'] = 1;
      $result['errorMsg'] = "Patient Id Required";
      $result['ex'] = "";
      $available = 0;
   }

   $result['status'] = $result['success'];

   if ($available == 1) {
      $result = visitAvailability($patientId, $date, $result);
   }




   /*
     $myfile = fopen("newfiletest.txt", "w") or die("Unable to open file!");
     $txt =" ----- 5 ----\n";
     $txt .= $_POST['patient_id']."\n";
     $txt .=" ---------\n";
     $txt .= $available."\n";
     $txt .=" ---------\n";
     $txt .= $result['success']."\n";
     $txt .= $result['error']."\n";
     $txt .= $result['errorMsg']."\n";
     $txt .= $result['ex']."\n";

     fwrite($myfile, $txt);
     fclose($myfile); */

   echo json_encode($result);
}

function visitAvailability($patientId, $date, $result) {
   $exist = checkVisitExist($patientId, $date);
   if ($exist > 0) {
      $result['error'] = 1;
      $result['success'] = 0;
      $result['errorMsg'] = " patient have visit already exist at  " . $date;
      $result['ex'] = "";
      $result['status'] = 4;
   } else {
      ## check online visits limit 
      $result = visitsLimits($date, $result);
   }

   return $result;
}

function visitsLimits($date, $result) {
   $vacation = checkVisitVacations($date);
   if ($vacation == 1) {
      $result['error'] = 1;
      $result['success'] = 0;
      $result['errorMsg'] = " Vacation Day  at  " . $date;
      $result['ex'] = "";
      $result['status'] = 4;
   } else {
      $limited = checkVisitLimits($date);
      if ($limited > 0) {
         ## add visit
         $result = addingVisit($result);
      } else {
         $result['error'] = 1;
         $result['success'] = 0;
         $result['errorMsg'] = " Daily visits limits exceeded at  " . $date;
         $result['ex'] = "";
         $result['status'] = 4;
      }
   }
   return $result;
}

function checkVisitVacations($date) {
   $vacations = r::findOne('visits_vacation', ' day_date = ?   and deleted =  0 ', [$date]);

   if (count($vacations) > 0) {
      return 1;
   } else {
      return -1;
   }
}

function checkVisitLimits($date) {
   $dayNo = getDayN0($date);

   $limit = r::findOne('visits_limit', '   branch_id = ? and  day_no = ? and deleted =  0 ', [0, $dayNo]);
   $limitNo = $limit->max_visits;

   $visits = R::findAll('visits', '   visitdate = ? and deleted != 1  ', [$date]);

   if (count($visits) >= $limitNo) {
      return -1;
   } else {
      return 1;
   }
}

function checkPatientExist($patientId, $result) {
   $patient = R::findone('patients', '  id =? and done = 1  and deleted != 1   ', [$patientId]);
   if (count($patient) > 0) {
      if ($patient->deleted == 1) {
         $result['success'] = 0;
         $result['error'] = 1;
         $result['errorMsg'] = "Patient has been deleted ";
         $result['ex'] = "";
      } else {
         $result['error'] = 0;
         $result['success'] = 1;
         $result['errorMsg'] = "";
         $result['ex'] = "";
      }
   } else {
      $result['success'] = 0;
      $result['error'] = 1;
      $result['errorMsg'] = "Patient Not Exist ";
      $result['ex'] = "";
   }
   return $result;
}

function checkVisitExist($patientId, $date) {
   $visit = R::findone('visits', '  patientid =? and visitdate = ? and deleted != 1  ', [$patientId, $date]);
   return count($visit);
}

function addingVisit($result) {
   $_GET["ac"] = "addFromApi";
   $control = "visits.php";
   $response = CURL_WEB($control);

   if ($response > 0) {
      $result['error'] = 0;
      $result['success'] = 1;
      $result['errorMsg'] = "";
      $result['ex'] = "";
      $result['status'] = 1;
   } else {
      $result['error'] = 1;
      $result['success'] = 0;
      $result['errorMsg'] = " Error !!! try again ";
      $result['ex'] = $response;
      $result['status'] = 0;
   }

   return $result;
}

function getDayN0($date) {
   $timestamp = strtotime($date);
   $day = date('w', $timestamp);

   switch ($day) {
      case 0:
         $name = 'الأحد  ';
         $no = 2;
         break;
      case 1:
         $name = ' الإثنين';
         $no = 3;
         break;
      case 2:
         $name = ' الثلاثاء';
         $no = 4;
         break;
      case 3:
         $name = 'الأربعاء ';
         $no = 5;
         break;
      case 4:
         $name = 'الخميس  ';
         $no = 6;
         break;
      case 5:
         $name = 'الجمعة ';
         $no = 7;
         break;
      case 6:
         $name = 'السبت ';
         $no = 1;
         break;
   }

   $res = array('dayNo' => $no, 'dayName' => $name);

   return $res;
}

#########################################################

function addNewPatient() {
   $result = array("success" => 0, "error" => 0, "errorMsg" => '', "ex" => "");
   $patientName = $_POST['name'];
   $phone = $_POST['phone'];

   $available = 1;

   if ($patientName == '' || is_null($patientName)) {
      $result['success'] = 0;
      $result['error'] = 1;
      $result['errorMsg'] = "Patient Name  Required";
      $result['ex'] = "";
      $available = 0;
   } elseif ($phone == '' || is_null($phone)) {
      $result['success'] = 0;
      $result['error'] = 1;
      $result['errorMsg'] = "Phone No  Required";
      $result['ex'] = "";
      $available = 0;
   }

   if ($available == 1) {
      $result = patientAvailability($patientName, $phone, $result);
   }

   $result['status'] = $result['success'];

   echo json_encode($result);
}

function checkDuplicateName($patientName, $result) {
   $patient = R::findAll('patients', 'wifename = ?  and done = 1  and deleted != 1', [$patientName]);
   if (count($patient) > 0) {
      $result['success'] = 0;
      $result['error'] = 1;
      $result['errorMsg'] = "Patient Name Already Exist ";
      $result['ex'] = "";
   } else {
      $result['error'] = 0;
      $result['success'] = 1;
      $result['errorMsg'] = "";
      $result['ex'] = "";
   }
   return $result;
}

function checkDuplicatePhone($phone, $result) {
   $patient = R::findAll('patients', '( phone = ?  or mobile = ? ) and  done = 1  and deleted != 1', [$phone, $phone]);
   if (count($patient) > 0) {
      $result['success'] = 0;
      $result['error'] = 1;
      $result['errorMsg'] = "Patient Phone Already Exist ";
      $result['ex'] = "";
   } else {
      $result['error'] = 0;
      $result['success'] = 1;
      $result['errorMsg'] = "";
      $result['ex'] = "";
   }
   return $result;
}

function patientAvailability($patientName, $phone, $result) {
   $result = checkDuplicateName($patientName, $result);
   if ($result['success'] == 1) {
      $result = checkDuplicatePhone($phone, $result);
      if ($result['success'] == 1) {
         ## add Patient
         $_GET["ac"] = "addFromApi";
         $control = "patients.php";
         $response = CURL_WEB($control);

         if ($response > 0) {
            $result['patient_id'] = $response;
            $result['error'] = 0;
            $result['success'] = 1;
            $result['errorMsg'] = "";
            $result['ex'] = "";
         } else {
            $result['error'] = 1;
            $result['success'] = 0;
            $result['errorMsg'] = " Error !!! try again ";
            $result['ex'] = $response;
         }
      }
   }

   return $result;
}

#########################################################

function CURL_WEB($control) {
   ##preparing url
   //$projectURL = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/';
   $url = 'http://' . $_SERVER['HTTP_HOST'] . explode('controllers', $_SERVER['REQUEST_URI'])[0] . 'controllers/' . $control;
   $i = 0;

   foreach ($_GET as $key => $value) {
      if ($i == 0) {
         $url .= "?$key=$value";
      } else {
         $url .= "&$key=$value";
      }
      $i++;
   }


   $data_arr = array();

   ##appending data
   foreach ($_POST as $key => $value) {
      $data_arr[$key] = $value;
   }

   ## start sending
   $post = $data_arr;
   $ch = curl_init($url);

   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //
   //Disable CURLOPT_SSL_VERIFYHOST and CURLOPT_SSL_VERIFYPEER by
   //setting them to false.
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   //curl_setopt($ch, CURLOPT_TIMEOUT, 10); //
   // execute!
   $response = curl_exec($ch);
   if ($response === false) {
      //echo 'Error : ' . curl_error($ch);
   }

   // close the connection, release resources used
   curl_close($ch);
   // do anything you want with your response
   //var_dump($response);
   //print_r($response);
   return $response;
}
