<?php

require_once("imp/_imp.php");
header("Access-Control-Allow-Origin: *");

class Controllers {

//public vars
    public $smarty;
    public $hosturl;
    public $controllname;
    public $shcontrollname;
    public $active;
    public $patientid;

    ############################################################################
    ##patients part
    ############################################################################

    public function __construct() {
        require_once("../public/aw_config.php");
//        require_once("imp/_autho.php"); //general functions
        $this->smarty = $smarty;
        $this->hosturl = $hosturl;
//here name of controll to known
        $this->controllname = 'mobileservices';
        $this->shcontrollname = 'mobileservices';
    }

    public function index() {

    }

    public function addPatient() {//add
        //check login
//        autho::checkautho($this->hosturl);
//        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //prepar wife data insert
        $wifename = filter_input(INPUT_POST, 'wifename');
        $dateofbirth = filter_input(INPUT_POST, 'dateofbirth');
        $wifeage = $this->calcage($patientdate);

        $address = filter_input(INPUT_POST, 'address');
        $mobile = filter_input(INPUT_POST, 'mobile');
        $devid = filter_input(INPUT_POST, 'devid');

        $password = filter_input(INPUT_POST, 'password');
        $hash_cost_factor = (defined('HASH_COST_FACTOR') ? HASH_COST_FACTOR : null);
        $user_password_hash = password_hash($password, PASSWORD_DEFAULT, array('cost' => $hash_cost_factor));
        // wife data that will insert
        $inserPatientData = R::dispense('patients');
        $inserPatientData->statusno = ''; //will be patient id
        $inserPatientData->wifename = $wifename;
        $inserPatientData->patient_password_hash = $user_password_hash;
        $inserPatientData->wiftypeid = 0;
        $inserPatientData->dateofbirth = $dateofbirth;
        $inserPatientData->wifeage = $wifeage;
        $inserPatientData->wifeeducation = '';
        $inserPatientData->wifejob = '';
        $inserPatientData->statuesid = 0;
        $inserPatientData->mirragefrom = 0;
        $inserPatientData->boyson = 0;
        $inserPatientData->girlson = 0;
        $inserPatientData->address = $address;
        $inserPatientData->phone = '';
        $inserPatientData->mobile = $mobile;
        $inserPatientData->wifenationalid = '';
        $inserPatientData->wifebl = 0;
        $inserPatientData->importantnote = '';
        $inserPatientData->risk = '';
        $inserPatientData->spacialnotes = '';

// Husband data that will insert
        $inserPatientData->husbandtypeid = 0;
        $inserPatientData->husdandname = '';
        $inserPatientData->husbanddateofbirth = '';
        $inserPatientData->husbandage = 0;
        $inserPatientData->husbandeducation = '';
        $inserPatientData->husbandjob = '';
        $inserPatientData->husbandnationalid = '';
        $inserPatientData->husbandbl = '';
        //
        $inserPatientData->done = 0; //has been saved permanently
        $inserPatientData->userid = 1; //$_SESSION['user_id'];
        $inserPatientData->devid = $devid; //$_SESSION['user_id'];

        R::begin();
        try {
            $inserted = R::store($inserPatientData);
            ##fatma
            //insert it in erp client
            $inserPatientData->id = $inserted;
            $treeId = $this->erpGetClientTreeId($inserPatientData->id);
            $this->erpClient($inserPatientData);
            // echo json_encode(array($inserPatientData->id, $treeId));
            $result_row = R::getRow("SELECT * FROM patients WHERE id = " . $inserted . "");
            $arr = array("success", $result_row);
            echo json_encode($arr);
        } catch (Exception $e) {
            R::rollback();
            $arr = array("false", "");
            echo json_encode($arr);
        }
    }

    public function updatePatient() {//update
////        check login
//        autho::checkautho($this->hosturl);
////check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $treeId = (int) $_POST["treeId"];
        $id = filter_input(INPUT_POST, 'patientid');
        $wifename = filter_input(INPUT_POST, 'wifename');
        $dateofbirth = filter_input(INPUT_POST, 'dateofbirth');
        $wifeage = $this->calcage($patientdate);

        $address = filter_input(INPUT_POST, 'address');
        $mobile = filter_input(INPUT_POST, 'mobile');

        $updatePatientData = R::load('patients', $id);
        $updatePatientData->wifename = $wifename;
        $updatePatientData->dateofbirth = $dateofbirth;
        $updatePatientData->wifeage = $wifeage;
        $updatePatientData->address = $address;
        $updatePatientData->mobile = $mobile;

        try {
            R::store($updatePatientData);
            if (!isset($treeId) || empty($treeId)) {
                $treeId = $this->erpGetClientTreeId($updatePatientData->id);
            }
            if ($treeId > 0) {
                $this->erpClient($updatePatientData);
            }
            $result_row = R::getRow("SELECT * FROM patients WHERE id = " . $id . "");
            $arr = array("success", $result_row);
            echo json_encode($arr);

            //echo json_encode(array($inserPatientData->id, $treeId));
        } catch (Exception $e) {
            R::rollback();
            $arr = array("false", "");
            echo json_encode($arr);

            //echo -1;
        }
    }

    public function getPatientData() {
////        check login
//        autho::checkautho($this->hosturl);
////check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $id = filter_input(INPUT_POST, 'patientid');
        $updatePatientData = R::load('patients', $id);

        echo json_encode($updatePatientData);
    }

    public function calcage($patientdate) {
        if (isset($patientdate) && !empty($patientdate)) {
            return date_diff(date_create($patientdate), date_create('today'))->y;
        } else {
            return 0;
        }
    }

    ##fatma

    public function erpClient($patient) {
        $programesetting = R::load('programesetting', 1);
        if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
            R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
            R::selectDatabase('erpDB');
            if (R::testConnection()) {
                $clientData = R::getRow('select clientid from client where obygyPatientId = ' . $patient->id);
                if (empty($clientData['clientid'])) {
                    //here use NULL for new insert
                    //better to add client using erp files it self so use  curl "it is like post requist but in php"
                    $this->curlAddClient($patient, $programesetting->erpdb);
//                $insert_sql = "REPLACE into client (clientid, clientname, clientaddress, clientphone, clientmobile, clientdebt, clientdetails, conditions, clientdate, userid,clientareaid,clientcode,dailyentryid ,rondomtxt,clientStoreIds,obygyPatientId) VALUES
//            (NULL,'" . $patient->wifename . "' , '" . $patient->address . "', '" . $patient->phone . "', '" . $patient->mobile . "', '0', '" . $patient->importantnote . "', '0', '" . date('Y-m-d') . "', '1', '0','','','','-10','" . $patient->id . "');";
                } else {
                    $treeId = (int) $_POST["treeId"];
                    if ($treeId > 0) {
                        //here use id to update
                        $this->curlUpdateClient($patient, $programesetting->erpdb, $clientData['clientid'], $treeId);
                    }
                }
            } else {
                throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
            }

            R::selectDatabase('default');
        }
    }

    //better to add client using erp files it self so use  curl "it is like post requist but in php"
    public function curlAddClient($patient, $erpDB) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'newclientName' => $patient->wifename,
            'clientaddress' => $patient->address,
            'clientphone' => $patient->phone,
            'clientmobile' => $patient->mobile,
            'newclientdebt' => 0,
            'clientdetails' => $patient->importantnote,
            'clientareaid' => 0,
            'clientcode' => '',
            'store_all' => -10,
            'obygyPatientId' => $patient->id,
        ];

        $ch = curl_init(HOST_URL_ERP . '/controllers/clientControllerAjax.php?do=addclient');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

        // execute!
        $response = curl_exec($ch);

        // close the connection, release resources used
        curl_close($ch);

        // do anything you want with your response
//        var_dump($response);
    }

    public function curlUpdateClient($patient, $erpDB, $clientId, $treeId) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'id' => $clientId,
            'treeId' => $treeId,
            'newclientName' => $patient->wifename,
            'clientaddress' => $patient->address,
            'clientphone' => $patient->phone,
            'clientmobile' => $patient->mobile,
            'newclientdebt' => 0,
            'clientdetails' => $patient->importantnote,
            'clientareaid' => 0,
            'clientcode' => '',
            'store_all' => 1,
            'obygyPatientId' => $patient->id,
        ];

        $ch = curl_init(HOST_URL_ERP . '/controllers/clientControllerAjax.php?do=updateFull');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

        // execute!
        $response = curl_exec($ch);

        // close the connection, release resources used
        curl_close($ch);

        // do anything you want with your response
        var_dump($response);
    }

    public function erpGetClientTreeId($patientId) {
        $programesetting = R::load('programesetting', 1);
        if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
            R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
            R::selectDatabase('erpDB');
            if (R::testConnection()) {
                $clientData = R::getRow('select clientid,accountstree.id from client left join accountstree on accountstree.name=client.clientname where obygyPatientId = ' . $patientId);
            } else {
                //'Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup'
                return -1;
            }
            R::selectDatabase('default');
            return $clientData["id"];
        } else {
            //"NO_DB"
            return -2;
        }
    }

    ############################################################################
    ##visits part
    ############################################################################

    public function addVisit() {
//        //check login
//        autho::checkautho($this->hosturl);
//        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //prepar wife data insert
        $flag = 1;
        $patientID = filter_input(INPUT_POST, 'patientid');
        $visitDate = filter_input(INPUT_POST, 'visitdate');
        $detectionID = filter_input(INPUT_POST, 'detectionid');
        $detectionValue = filter_input(INPUT_POST, 'detectionvalue');
        $payVisit = 0; //(int) filter_input(INPUT_POST, 'payVisit');

        $new_date = date('Y/m/d', strtotime($visitDate));

        //check if there
        $patientthere = R::count('visits', 'patientid = ? and visitdate = ? and deleted = 0', [$patientID, $new_date]);
        $insertnew = 1;
        if ($patientthere > 0) {
            $insertnew = 0;
            $flag = 2; //already there is a visit
        }
        //check if visit limit of app reached
        $mobileVisitsOfThisDay = R::count('visits', 'mobileappvisit = 1 and visitdate = ?', [$new_date]);
        if ($mobileVisitsOfThisDay == 10) {//only 10 are allowed
            $insertnew = 0;
            $flag = 3; //max visits by app reached
        }

        $insertDataVisits = R::dispense('visits');
        $insertDataVisits->patientid = $patientID;
        $insertDataVisits->visitdate = $new_date;
        $insertDataVisits->detectionid = $detectionID;
        $insertDataVisits->detectionvalue = $detectionValue;
        $insertDataVisits->mobileappvisit = 1;
        $insertDataVisits->payedflag = $payVisit;
        try {
            if ($insertnew == 1) {
                $insert = R::store($insertDataVisits);
            }

            $arr = array("success", $flag,);
            echo json_encode($arr);
            //$flag = 1; //ok
            //$flag = 2; //already there is a visit
            //$flag = 3; //max visits by app reached
        } catch (Exception $ex) {
            $arr = array("failed");
            echo json_encode($arr);
        }
    }

    public function updateVisit() {
//        //check login
//        autho::checkautho($this->hosturl);
//        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);

        $vId = filter_input(INPUT_POST, 'vId');
        $patientid = filter_input(INPUT_POST, 'patientid');
        $visitDate = filter_input(INPUT_POST, 'visitdate');
        $detectionID = filter_input(INPUT_POST, 'detectionid');
        $detectionValue = filter_input(INPUT_POST, 'detectionvalue');


        $visitLoad = R::load('visits', $vId);
        $visitLoad->patientid = $patientid;
        $visitLoad->visitdate = $visitDate;
        $visitLoad->detectionid = $detectionID;
        $visitLoad->detectionvalue = $detectionValue;
        try {
            R::store($visitLoad);
            $arr = array("success");
            echo json_encode($arr);
        } catch (Exception $ex) {
            $arr = array("failed");
            echo json_encode($arr);
        }
    }

    public function delVisit() {
//        //check login
//        autho::checkautho($this->hosturl);
//        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $id = filter_input(INPUT_POST, 'id');
        $patientDelete = R::load('visits', $id);
        try {
            if ($patientDelete->payedflag == 1) {
                //patient has payed it should be del from program not app
                //echo 2;
            } else {
                $patientDelete->deleted = 1;
                R::store($patientDelete);
                //echo 1;
            }
            $arr = array("success");
            echo json_encode($arr);
        } catch (Exception $ex) {
            echo -1;
            $arr = array("failed");
            echo json_encode($arr);
        }
    }

    public function visitType() {

        $allDetections = R::getAll('select * from detections where del = 0');
        $arr = array("success", $allDetections);
        echo json_encode($allDetections);
    }

    public function queryAllVisitsByPatientAndDate() {
        $patientID = filter_input(INPUT_POST, 'patientid');
        $visitDate = filter_input(INPUT_POST, 'visitdate');

        $patientthere = R::count('visits', 'patientid = ? and visitdate = ? and deleted = 0', [$patientID, $visitDate]);
        if ($patientthere > 0) {
            $allVisits = R::getAll('select * from visits where patientid = ' . $patientID . ' and visitdate = "' . $visitDate . '" and deleted = 0');
            $arr = array("success", $allVisits);
            echo json_encode($arr);
        } else {
            $arr = array("noVisits");
            echo json_encode($arr);
        }
    }

    //if empty date it gives visits of today
    public function queryAllVisitsByDate() {
        $visitDate = filter_input(INPUT_POST, 'visitdate');
        if (empty($visitDate)) {
            $visitDate = date('Y-m-d');
        }

        $visitsCount = R::count('visits', 'visitdate = ? and deleted = 0', [ $visitDate], 'id');
        if ($visitsCount > 0) {
            $allVisits = R::getAll('select visits.*,patients.wifename from visits join patients on visits.patientid = patients.id where visitdate = "' . $visitDate . '" and visits.deleted = 0');
            $appVisitsCount = R::count('visits', 'visitdate = ? and deleted = 0 and mobileappvisit=1', [ $visitDate], 'id');
            $systemVisitsCount = $visitsCount - $appVisitsCount;
            $arr = array("success", $allVisits, $visitsCount, $appVisitsCount, $systemVisitsCount);
            echo json_encode($arr);
        } else {
            $arr = array("noVisits");
            echo json_encode($arr);
        }
    }

    public function roshetat() {

        $patientId = filter_input(INPUT_POST, 'patientid');
        $visitDate = filter_input(INPUT_POST, 'visitdate');
//        $patientId = 6;
//        $visitDate = "2018-12-25";

        $dates = R::getAll('SELECT DISTINCT date  FROM gynadrugs WHERE deleted = ? and patientid = ?   order by date desc', [ 0, $patientId]);
        $countHusband = array();
        $countWife = array();
        $allData = array();
        $i = 0;
        foreach ($dates as $date) {


            ## all prescription of certain patient
            if ($visitDate == $date['date']) {
                $PatientPresByDateWife = R::findall('gynadrugs', 'deleted = ? and patientid = ? and date = ? and forhusband = ? ', [ 0, $patientId, $date['date'], 0]);
                $PatientPresByDateHusband = R::findall('gynadrugs', 'deleted = ? and patientid = ? and date = ? and forhusband = ?', [ 0, $patientId, $date['date'], 1]);


                $j = 0;

                foreach ($PatientPresByDateWife as $pres) {

                    $dd = R::load('drugs', $pres->drugid);
                    //# drugname اسم الدواء
                    //# drugdos طريقة الاستخدام
                    $arr = array(
                        "drugname" => $dd->drugname,
                            //"drugdos" => $dd->drugdos,
                    );
                    array_push($allData, $arr);
                }

                $j = 0;

                foreach ($PatientPresByDateHusband as $pres) {
                    $dd = R::load('drugs', $pres->drugid);
                    //# drugname اسم الدواء
                    //# drugdos طريقة الاستخدام
                    $arr = array(
                        "drugname" => $dd->drugname,
                            // "drugdos" => $dd->drugdos,
                    );
                    array_push($allData, $arr);
                }

                $countHusband[$dates[$i]['date']] = count($PatientPresByDateHusband);
                $countWife[$dates[$i]['date']] = count($PatientPresByDateWife);
            }
        }

        $arr = array($allData);
        echo json_encode($allData);
    }

    ############################################################################
    ##login part
    ############################################################################

    public function patientLogin() {
        $mobile = filter_input(INPUT_POST, 'mobile');
        $password = filter_input(INPUT_POST, 'password');
//        $mobile = $_GET['mobile'];
//        $password = $_GET['password'];

        $result_row = R::getRow("SELECT * FROM patients WHERE mobile = '" . $mobile . "'");
        if (!password_verify($password, $result_row["patient_password_hash"])) {
            //fail
            //echo 0;
            $arr = array("false", "", "treeId" => "");
        } else {
            //sucess
            $treeId = $this->erpGetClientTreeId($result_row["id"]);
            $arr = array("success", $result_row, $treeId);
        }
        echo json_encode($arr);
    }

    ############################################################################
    ##showprescription part
    ############################################################################

    public function showprescription() {       ## show prescriptions of patient
//        //check login
//        autho::checkautho($this->hosturl);
//        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        $ProgramesettingData = R::findone('programesetting');
//        $this->smarty->assign('ProgramesettingData', $ProgramesettingData);

        $patientId = filter_input(INPUT_POST, "patientId");
        $type = filter_input(INPUT_POST, "type");  ## show or edit
        $preFor = filter_input(INPUT_POST, "preFor");
        ## show all prescription of patient
        if ($type == "show") {
            $dates = R::getAll('SELECT DISTINCT date  FROM gynadrugs WHERE deleted = ? and patientid = ?  order by date desc', [ 0, $patientId]);
            $countHusband = array();
            $countWife = array();
            $i = 0;
            foreach ($dates as $date) {
                ## all prescription of certain patient


                $PatientPresByDateWife = R::findall('gynadrugs', 'deleted = ? and patientid = ? and date = ? and forhusband = ? ', [ 0, $patientId, $date['date'], 0]);
                $PatientPresByDateHusband = R::findall('gynadrugs', 'deleted = ? and patientid = ? and date = ? and forhusband = ?', [ 0, $patientId, $date['date'], 1]);


                $j = 0;

                foreach ($PatientPresByDateWife as $pres) {
                    $dd = R::load('drugs', $pres->drugid);
                    if ($j == 0) {
                        $dates[$i]["drugdos"] = "";
                        $dates[$i]["drugdos"] = $dd->drugname;
                    } else {
                        $dates[$i]["drugdos"] = $dates[$i]["drugdos"] . ' , ' . $dd->drugname;
                    }

                    $j++;
                }

                $j = 0;

                foreach ($PatientPresByDateHusband as $pres) {
                    $dd = R::load('drugs', $pres->drugid);
                    if ($j == 0) {
                        $dates[$i]["drugtype"] = "";
                        $dates[$i]["drugtype"] = $dd->drugname;
                    } else {
                        $dates[$i]["drugtype"] = $dates[$i]["drugtype"] . ' , ' . $dd->drugname;
                    }

                    $j++;
                }

                $dates[$i]['date'] = date("Y/m/d", strtotime($dates[$i]['date']));
                $countHusband[$dates[$i]['date']] = count($PatientPresByDateHusband);
                $countWife[$dates[$i]['date']] = count($PatientPresByDateWife);


                $i++;
            }
            echo json_encode(array('ProgramesettingData' => $ProgramesettingData, 'countHusband' => $countHusband, 'countWife' => $countWife, 'dates' => $dates));
//            $this->smarty->assign('countHusband', $countHusband);
//            $this->smarty->assign('countWife', $countWife);
//            $this->smarty->assign('dates', $dates);
//
//            $this->smarty->display('gyna/showPrescriptions.html');
        }

        ## show  prescription of patient with determined date to edit it
        else if ($type == "edit") {
            $date = filter_input(INPUT_POST, "preDate");
            $date = date("Y-m-d", strtotime($date));
            $this->getprescription($patientId, $date, $preFor);
            echo json_encode(array('ProgramesettingData' => $ProgramesettingData, "type" => "drugedit"));
//            $this->smarty->assign('type', "drugedit");
//            $this->smarty->display('gyna/newrowdrugedit.html');
        }
    }

    ############################################################################
    ## Start chatting  part
    ############################################################################

    public function selectChatting() {
        $event_id = $_GET['event_id'];
        //$limit = $_GET['limit'];
        //# creating folder for each user if not exist .
        print_r('xxxxxxxxx');

        if (!file_exists('http://localhost/obgy_new/upload/user_1')) {
            mkdir('http://localhost/obgy_new/upload/user_1', 0777, true);
        }
        $serverLink = 'http://localhost/obgy_new/';

        //$patient_id = filter_input(INPUT_POST, 'patient_id');
        $patient_id = 1;

        $sQuery = "
                SELECT chat.* ,
                patients.wifename as wifename
                FROM chat
                join patients on patients.id = chat.patient_id
                where chat.patient_id = " . $patient_id . "
                order by chat.sys_time ASC
            ";
        $eventsData = R::getAll($sQuery);

        $arr = array();
        foreach ($eventsData as $val) {
            $img = $filepdf = $fileword = $voice = '';
            if ($val['img'] != '') {
                $img = $val['img'];
            }
            if ($val['filepdf'] != '') {
                $filepdf = $val['filepdf'];
            }
            if ($val['fileword'] != '') {
                $fileword = $val['fileword'];
            }
            if ($val['voice'] != '') {
                $voice = $val['voice'];
            }
            $arr[] = array(
                'chat_id' => $val['id'],
                'user_id' => $val['user_id'],
                'senderName' => $val['senderName'],
                'txt' => $val['txt'],
                'img' => $img,
                'filepdf' => $filepdf,
                'filepdfName' => $val['filepdf'],
                'fileword' => $fileword,
                'filewordName' => $val['fileword'],
                'voice' => $voice,
                'location' => $val['location'],
                'video' => $val['video'],
                'contacts' => $val['contacts'],
                'sys_time' => $val['sys_time'],
                'picture' => $val['picture'],
            );
        }

        echo json_encode($arr);
    }

    ############################################################################
    ## End chatting  part
    ############################################################################
    #
    // at the end of class call

    public function __destruct() {
//close connection
        R::close();
    }

}
