<?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;

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

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();
}


$do = $_GET["ac"];

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

    default:
        break;
}

function addNewVisit() {
    $result = array("success" => 0, "error" => 0, "errorMsg" => '', "ex" => "");
    $patientId = (int) $_POST['patientid'];
    $date = $_POST['visitdate'];
    //  $_POST['detectionid'] = 73;
    $_POST['payVisit'] = 0;
    $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;
    }

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

    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'] = "";
    } else {
        ## add visit
        $_GET["ac"] = "addFromApi";
        $control = "visits.php";
        $response = CURL_WEB($control);

        if ($response > 0) {
            $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 checkPatientExist($patientId, $result) {
    $patient = R::findone('patients', '  id =? and done = 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 = ? ', [$patientId, $date]);
    return count($visit);
}

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;
}
