<?php

function archiveRecord($patient_id, $device_id, $target_id, $target_table, $control) {
    $device = R::load('devices', $device_id);
    switch ($device->location) {
        case 4:    ## in 
            $archive = R::findOne('archive_tracking', ' patient_id = ?   
                      order by out_date desc , out_time desc ,  id desc  ', [$patient_id]);

            ##  out record was found  without in update it 
            if (count($archive) > 0 && $archive->in_device_id == 0 && $archive->out_device_id > 0) {
                $dateCol = 'in_date';
                $timeCol = 'in_time';
                $deviceCol = 'in_device_id';
                updateArchiveRecord($archive->id, $device_id, $dateCol, $timeCol, $deviceCol);
            }

            ##   add new record 
            else {
                $dateCol = 'in_date';
                $timeCol = 'in_time';
                $deviceCol = 'in_device_id';
                saveArchiveRecord($patient_id, $device_id, $target_id, $target_table, $control, $dateCol, $timeCol, $deviceCol);
            }
            break;

        case 5:  ## out  
            $dateCol = 'out_date';
            $timeCol = 'out_time';
            $deviceCol = 'out_device_id';
            saveArchiveRecord($patient_id, $device_id, $target_id, $target_table, $control, $dateCol, $timeCol, $deviceCol);
            break;
    }
}

function saveArchiveRecord($patient_id, $device_id, $target_id, $target_table, $control, $dateCol, $timeCol, $deviceCol) {

    $archive = R::findOne('archive_tracking', ' patient_id = ? and  ' . $deviceCol . ' = ?    and  ' . $dateCol . ' = ?     
                   and  ' . $timeCol . '  between    ?   and  ?       '
                    , [$patient_id, $device_id, date('Y-m-d'), date("H:i:s", strtotime("-2 minutes")), date("H:i:s")]);


    if (!(count($archive) > 0 )) {
        $obj = R::xdispense('archive_tracking');
        $obj->patient_id = $patient_id;
        $obj->target_id = $target_id;
        $obj->target_table = $target_table;

        $obj->$dateCol = date('Y-m-d');
        $obj->$timeCol = date("H:i:s");
        $obj->$deviceCol = $device_id;

        $obj->control = $control;
        $obj->user_id = $_SESSION['user_id'];
        $obj->deleted = 0;

        try {

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

function updateArchiveRecord($archive_id, $device_id, $dateCol, $timeCol, $deviceCol) {
    $obj = R::load('archive_tracking', $archive_id);
    $obj->$dateCol = date('Y-m-d');
    $obj->$timeCol = date("H:i:s");
    $obj->$deviceCol = $device_id;

    try {

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

function saveTrackingRecord($patient_id, $device_id, $target_id, $target_table, $control) {

    $record = R::findOne('device_tracking', ' patient_id = ?    and  device_id = ?   and  visit_date = ?     
                        and  visit_time  between   ?   and  ?        '
                    , [$patient_id, $device_id, date('Y-m-d'), date("H:i:s", strtotime("-2 minutes")), date("H:i:s")]);

    if (!(count($record) > 0 )) {
        $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 {

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

function visitAvailableToEdit($patient_id, $date) {
    $visit = R::findOne('visits', ' deleted = 0  and  customer_add = 1  and  visitdate = ? and  patientid = ?  ', [$date, $patient_id]);
    if ($visit->id > 0) {
        return $visit->id;
    } else {
        return 0;
    }
}

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 setVisitsViewed($patient_id) {

    $visits = R::findAll('visits', ' patientid = ?    and  visitdate = ?    ', [$patient_id, date('Y-m-d')]);

    if (count($visits) > 0) {
        $data = R::getRow("SELECT MAX(enterordered)  FROM `visits`");
        $lastEnter = $data['MAX(enterordered)'];
        foreach ($visits as $visit) {
            $lastEnter++;
            $visit->view = 1;
            $visit->visitorder = 0;
            $visit->kashf_enterance = date("H:i");
            $visit->enterordered = $lastEnter;
            R::store($visit);
        }
    }
}

function calcBalance($patId = 0) {

    $sql = ' ';
    if ($patId > 0) {
        $sql = '  where  id  = ' . $patId;
    }

    $patients = R::getAll('select id    from  patients  ' . $sql);
    foreach ($patients as $patient) {
        $patientId = $patient['id'];
        $balance = 0;

        $lastVisit = R::getAll('SELECT visits.id as visitid , visits.restdetectionvalue as rest 
                                                    FROM visits
                                                    where  visits.patientid = ?   and  visits.restdetectionvalue >0
                                                               and visits.deleted != ?   ', [$patientId, 1]);

        foreach ($lastVisit as $data) {
            $payVisits = R::getRow('SELECT COALESCE(SUM(detectionvalue_cash),0)   as paid_cash
                                                                 , COALESCE(SUM(detectionvalue_visa),0)   as paid_visa
                                                                  , COALESCE(SUM(discount),0)   as paid_discount
                                                                 , 0 as paid
                                    FROM visits   where  patientid = ?
                               and deleted != ? and detectionid = 999 and visitid = ?   ', [$patientId, 1, $data['visitid']]);


#               ## what pt paid after  creating visit
            $payVisits['paid'] = $payVisits['paid_cash'] + $payVisits['paid_visa'];

            if ($data['rest'] > ($payVisits['paid'] + $payVisits['paid_discount'])) {
                $balance = $balance + $data['rest'] - $payVisits['paid'] - $payVisits['paid_discount'];
            }
        }

        if ($balance >= 0 && $patientId > 0) {
            R::exec('update patients set balance =   ' . $balance . '    where  id  = ' . $patientId . ' ');
        }
        //    print_r(' ( ' . $patientId . '  ,    ' . $balance . ' ) - ');
    }
}

function getReferredDr($referred_dr_id, $refer_doctor_tb) {

    if ($referred_dr_id > 0) {
        switch ($refer_doctor_tb) {
            case 1:
                $refer = R::getRow('select name from awusers where user_id = ?', [$referred_dr_id]);
                $ref_dr = $refer['name'];
                break;

            default:
                $refer = R::load('refer', $referred_dr_id);
                $ref_dr = $refer->name;
                break;
        }
    } else {
        $ref_dr = 'لا يوجد';
    }
    return $ref_dr;
}

function getPatientPhone($patientId, $for_husband = 0) {
    $phone = '';
    $patient = R::load('patients', $patientId);
    if ($for_husband == 1) {
        if ($patient->id > 0 && $patient->hus_mobile != '' && $patient->hus_mobile != null) {
            $phone = $patient->hus_mobile;
        }
    } else {
        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 getMesseges($messagePlace) {
    $sms_control = R::findall('sms_control', 'deleted != 1 and status = 1  and message_place =  ?', [$messagePlace]);
    return $sms_control;
}

function getMessegeContent($sms_control, $patientId, $visit, $server_type) {
    $message = ' ';
    switch ($sms_control->message_type) {
        case 1:                                   ##  Message Only
            $message .= $sms_control->message;
            break;
        case 2:                                   ##  Message With Link  Only
            $message .= $sms_control->message;
            $shortLink = getShortUrl($sms_control->en_link, $sms_control->fixed_link);
            $fullLink = $sms_control->fixed_link . '?redirect=' . $shortLink;
            $message .= '  للمتابعة  ' . $fullLink;
            break;
        case 3:                                   ##   Message With Patient  Only
            if ($patientId > 0) {
                $patient = R::load('patients', $patientId);
                $message .= ' أ  /  ' . $patient->wifename;
            }
            $message .= '   ' . $sms_control->message;
            break;
        case 4:                                   ##   Message With Link + Patient 
            if ($patientId > 0) {
                $patient = R::load('patients', $patientId);
                $message .= ' أ  /  ' . $patient->wifename;
            }
            $message .= '   ' . $sms_control->message;
            $shortLink = getShortUrl($sms_control->en_link, $sms_control->fixed_link);
            $fullLink = $sms_control->fixed_link . '?redirect=' . $shortLink;
            $message .= '  للمتابعة  ' . $fullLink;
            break;
        case 5:                                   ##   Message With Link + Visit 
            if ($visit->id > 0) {
                $patient = R::load('patients', $visit->patientid);
                if ($visit->for_husband == 1) {
                    $patient_name = $patient->husdandname;
                } else {
                    $patient_name = $patient->wifename;
                }
                $message .= ' أ  /  ' . $patient_name . '  ';
                $message .= '  تم حجز زيارة بتاريخ   ' . $visit->visitdate;
                $shortLink = getShortUrl($sms_control->en_link . '/' . $visit->enc_id, $sms_control->fixed_link);
                $fullLink = $sms_control->fixed_link . '?redirect=' . $shortLink;
                $message .= '  للمتابعة  ' . $fullLink;
                if ($server_type == 1) {
                    prepareToSite($visit, 2, $shortLink, $sms_control->fixed_link . '' . $sms_control->en_link . '/' . $visit->enc_id, $visit->enc_id);
                }
            }
            $message .= '   ' . $sms_control->message;

            break;
    }
    return $message;
}

function sendSms($sourceId, $messagePlace) {

    switch ($messagePlace) {
        case 1:
            $patientId = $sourceId;
            $for_husband = 0;
            $deptId = 0;
            break;
        case 2:
            $visitId = $sourceId;
            $visit = R::load('visits', $visitId);
            $visit = generateUniqueID($visit);
            $patientId = $visit->patientid;
            $for_husband = $visit->for_husband;
            $deptId = $visit->for_department;
            break;
        case 3:
            $visitId = $sourceId;
            $visit = R::load('visits', $visitId);
            $visit = generateUniqueID($visit);
            $patientId = $visit->patientid;
            $for_husband = $visit->for_husband;
            $deptId = $visit->for_department;
            break;
        default:
            $patientId = 0;
            $visitId = 0;
            $for_husband = 0;
            $deptId = 0;
            break;
    }
    $phoneNo = getPatientPhone($patientId, $for_husband);
    $sms_control = getMesseges($messagePlace);
    $sms_setting = R::findOne('sms_control_setting');

    foreach ($sms_control as $mess) {
        $sendIt = allowedDept($deptId, $mess->for_depts);
        if ($sendIt == 1) {
            $message = getMessegeContent($mess, $patientId, $visit, $sms_setting->server_type);
            sendItSmsApi($phoneNo, $message);
        }
    }
}

function allowedDept($deptId, $for_depts) {
    $sendIt = 0;
    $forDepts = array();

    if ($for_depts == -1) {
        $sendIt = 1;
    } else {
        $index_roles = explode(',', $for_depts);

        foreach ($index_roles as $value) {
            $value = trim($value);
            array_push($forDepts, $value);
        }
        if (in_array($deptId, $forDepts)) {
            $sendIt = 1;
        }
    }

    return $sendIt;
}

function sendItSms($mobile, $message, $userName, $password, $sender) {
    // send to Egypt only
    $recipient = ltrim($mobile, "2");
    $recipient = ltrim($recipient, "+2");
    $recipient = ltrim($recipient, "02");
    $recipient = ltrim($recipient, "002");
    $recipient = ltrim($recipient, "0");
    $recipientWithCode = "20" . ($recipient);

    $query = [
        'environment' => 1, //1 For Live , 2 For Test,
        'username' => $userName,
        'password' => $password,
        'language' => 2, //1 For English , 2 For Arabic , 3 For Unicode
        'sender' => $sender,
        'mobile' => $recipientWithCode,
        'message' => $message
    ];
    $buildQuery = http_build_query($query);
    $requestUrl = "https://smsmisr.com/api/SMS/?" . $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', 'Content-Length:0')
    ));
    $response = curl_exec($curl);
    curl_close($curl);
    // echo $response;
}

function sendItSmsApi($mobile, $message) {
    $url = 'https://sms.naslab.gt4it.com/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 generateUniqueID($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) {
            generateUniqueID($visit);
        } else {
            $visit->enc_id = $encId;
            r::store($visit);
            return $visit;
        }
    }
}

function getShortUrl($en_url, $fixed_url) {
    $short_url = R::findOne('short_urls', 'origin_url = ? ', [$en_url]);
    if (count($short_url) > 0) {
        return $short_url->short_url;
    } else {
        $sh_url = generateShortUrl();
        $short_url = R::xdispense('short_urls');
        $short_url->origin_url = $fixed_url . '' . $en_url;
        $short_url->short_url = $sh_url;
        $short_url->create_date = date('Y-m-d H:i:s');
        r::store($short_url);
        return $sh_url;
    }
}

function generateShortUrl() {
    $sh_url = substr(md5(uniqid(rand(), true)), 0, 6);
    $short_url = R::findOne('short_urls', 'short_url = ? ', [$sh_url]);
    if (count($short_url) > 0) {
        generateShortUrl();
    } else {
        return $sh_url;
    }
}

function prepareToSite($source, $sourceType, $shortLink, $fullLink, $enc_id) {
    switch ($sourceType) {
        case 1:    // patient object
            $patient_name = $source->wifename;
            $visit_id = 0;
            $doctor_name = '';
            $visit_order = '';
            $visit_date = null;
            $visit_time = '';
            $short_url = $shortLink;
            $origin_url = $fullLink;
            break;
        case 2:    // visit  object
            $patient = R::load('patients', $source->patientid);
            if ($source->for_husband == 1) {
                $patient_name = $patient->husdandname;
            } else {
                $patient_name = $patient->wifename;
            }
            $visit_id = $source->id;
            $doctor_name = '';
            if ($source->for_doctor > 0) {
                $doctorIn = R::getRow('select name  from awusers where user_id = ?', [$source->for_doctor]);
                $doctor_name = $doctorIn['name'];
            }

            $visit_order = $source->visit_order;
            $visit_date = $source->visitdate;
            $visit_time = $source->visit_time;
            $short_url = $shortLink;
            $origin_url = $fullLink;

            break;
        default:
            $patient_name = '';
            $visit_id = 0;
            $doctor_name = '';
            $visit_date = null;
            $visit_time = '';
            $short_url = '';
            $origin_url = '';
            break;
    }


    $branch_name = '';
    if ($source->branch_id > 0) {
        $branch = R::load('branches', $source->branch_id);
        $branch_name = $branch->name;
    }

    $data = array(
        'name' => $patient_name
        , 'visit_id' => $visit_id
        , 'doctor_name' => $doctor_name
        , 'visit_order' => $visit_order
        , 'visit_date' => $visit_date
        , 'visit_time' => $visit_time
        , 'short_url' => $short_url
        , 'origin_url' => $origin_url
        , 'enc_id' => $enc_id
        , 'branch_id' => $source->branch_id
    );

    sendToSite($data);
}

function sendToSite($data) {

    $url = 'https://royal-fc.net/appv/visit_details/add';

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);

    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    $response = curl_exec($curl);
    curl_close($curl);
    $res = json_decode($response);
}

function updateToSite($data) {

    $url = 'https://royal-fc.net/appv/visit_details/update';

    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);

    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    $response = curl_exec($curl);
    curl_close($curl);
    $res = json_decode($response);
}
