<?php

function saveTrackingRecord($patient_id, $device_id, $target_id, $target_table, $control) {
    $obj = R::xdispense('device_tracking');
    $obj->patient_id = $patient_id;
    $obj->device_id = $device_id;
    $obj->visit_date = date('Y-m-d');
    $obj->visit_time = date("H:i:s");
    $obj->target_id = $target_id;
    $obj->target_table = $target_table;
    $obj->control = $control;
    $obj->user_id = $_SESSION['user_id'];
    $obj->deleted = 0;

    try {

        $insert = R::store($obj);
    } catch (Exception $ex) {
        echo $ex;
    }
}

function getPatientId($patientNo) {
    $patient = R::findOne('patients', ' deleted = 0  and  statusno = ?  ', [$patientNo]);
    if ($patient->id > 0) {
        return $patient->id;
    } else {
        return 0;
    }
}

function getDeviceId($deviceNo) {
    $device = R::findOne('devices', ' deleted = 0  and  device_name = ?  ', [$deviceNo]);
    if ($device->id > 0) {
        return $device->id;
    } else {
        return 0;
    }
}

function getPatientNo($patientId) {
    $patient = R::load('patients', $patientId);
    if ($patient->id > 0) {
        return $patient->statusno;
    } else {
        return 0;
    }
}

function getPatientPhone($patientId) {
    $patient = R::load('patients', $patientId);
    $phone = '';
    if ($patient->id > 0 && $patient->phone != '' && $patient->phone != null) {
        $phone = $patient->phone;
    } else if ($patient->id > 0 && $patient->mobile != '' && $patient->mobile != null) {
        $phone = $patient->mobile;
    }
    return $phone;
}

function sendItSmsApi($patientId, $message, $hosturlApi) {

    $mobile = getPatientPhone($patientId);
    $url = $hosturlApi . '/api/send-sms';

    $data = array(
        'phone' => $mobile
        , 'message' => $message
    );

    $apiKey = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6Im1lZGljYWxfdGVzdHMiLCJwYXNzd29yZCI6Im1lZGljYWxfdGVzdHNAcGFzc3dvcmQifQ.6_o87c9NR48MsyMoer2OQzJ8PCDBVgLFJpeNo449RDA';

    // Initializes a new cURL session
    $curl = curl_init($url);
    //   print_r($curl);
    // 1. Set the CURLOPT_RETURNTRANSFER option to true
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
// 2. Set the CURLOPT_POST option to true for POST request
    curl_setopt($curl, CURLOPT_POST, true);
// 3. Set the request data 
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
// 4. Set  headers for API Auth 

    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        //'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
        'AuthorizationKey: Bearer ' . $apiKey
    ));
    $response = curl_exec($curl);
    curl_close($curl);

    //  echo $response . PHP_EOL;

    $res = json_decode($response);
    // print_r($res);
}

function sendSms($patientId, $message) {
    $phoneNo = getPatientPhone($patientId);
    // send to Egypt only
    $recipient = ltrim($phoneNo, "2");
    $recipient = ltrim($recipient, "+2");
    $recipient = ltrim($recipient, "02");
    $recipient = ltrim($recipient, "002");
    $recipient = ltrim($recipient, "0");
    $phoneNoWithCode = "20" . ($recipient);

    $data = array(
        "recipient" => $phoneNoWithCode
        , "sender_id" => "DrMhmodGoma"
        , "type" => "plain"
        , "message" => $message
    );

    $buildQuery = http_build_query($data);
    $requestUrl = "https://bulk.whysms.com/api/v3/sms/send/?" . $buildQuery;

    $curl = curl_init();

    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt_array($curl, array(
        CURLOPT_URL => $requestUrl,
        CURLOPT_HEADER => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_HTTPHEADER => array('Content-Type:application/json'
            , 'Accept: application/json'
            , 'Authorization: Bearer 40|tbtaEm4E8gdINZE8sG455GWzGmhJYIkRDDFW54pT'
            , 'Content-Length:0')
    ));

    $response = curl_exec($curl);

    // Close cURL session
    curl_close($curl);
    $res = json_decode($response);
    if ($res->success) {
        print('success');
        //    return $res->success;
    } else {
        print('error');
        //  return $res->error->message;
    }
}

function generateRecID($visit) {
    if (!empty($visit->enc_id) && $visit->enc_id != '' && $visit->enc_id != null) {
        return $visit;
    } else {
        $encId = substr(md5(uniqid(rand(), true)), 0, 6);
        $enc_visit = R::findOne('visits', 'enc_id = ? ', [$encId]);
        if (count($enc_visit) > 0) {
            generateRecID($visit);
        } else {
            $visit->enc_id = $encId;
            r::store($visit);
            return $visit;
        }
    }
}

function getRedirect($enc_id, $source_id, $to_tn) {
    $redirect = R::findOne('sms_redirect', 'source_id = ?  and  enc_id = ? and to_tn = ?  ', [$source_id, $enc_id, $to_tn]);
    if (count($redirect) > 0) {
        return $redirect->red_id;
    } else {
        $red_id = generateRedirect();
        $sms_redirect = R::xdispense('sms_redirect');
        $sms_redirect->source_id = $source_id;
        $sms_redirect->enc_id = $enc_id;
        $sms_redirect->to_tn = $to_tn;
        $sms_redirect->red_id = $red_id;
        $sms_redirect->create_date = date('Y-m-d H:i:s');
        r::store($sms_redirect);
        return $red_id;
    }
}

function generateRedirect() {
    $red_id = substr(md5(uniqid(rand(), true)), 0, 6);
    $sms_redirect = R::findOne('sms_redirect', 'red_id = ? ', [$red_id]);
    if (count($sms_redirect) > 0) {
        getRedirect();
    } else {
        return $red_id;
    }
}
