<?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 "databysample":
        databysample();
        break;

    case "saveresults":
        saveresults();
        break;

    case "saveresultsMulti":
        saveresultsMulti();
        break;
        
            case "orglogin":
        orglogin();
        break;

    case "orgpatientinfo":
        orgpatientinfo();
        break;

    default:
        break;
}

function databysample() {
    $result = array("success" => 0, "error" => 0, "errorMsg" => '', "res" => array());
    $sampleId = (int) $_POST['sample_id'];
    $deviceId = (int) $_POST['device_id'];
    if (!($sampleId > 0 )) {
        $result['success'] = 0;
        $result['error'] = 1;
        $result['errorMsg'] = "Sample Id Required";
    } elseif (!($deviceId > 0 )) {
        $result['success'] = 0;
        $result['error'] = 1;
        $result['errorMsg'] = "Device Id Required";
    } else {
        $result = dataBySampleId($sampleId, $deviceId, $result);
        $result['error'] = 0;
        $result['success'] = 1;
        $result['errorMsg'] = "";
    }

    //print_r($result);
    echo json_encode($result);
}

function dataBySampleId($sampleId, $deviceId, $result) {
    $anatomies = array();
    //    r::debug(true, 2);
    $invests = R::getAll(' select distinct  investigationresults.investid    ,  invests.name  as investName 
        , investigationresults.visitid  ,  invests.special_inv_type  , investigationresults.filled 
          , investigationresults.investresult
                                from investigationresults 
                                join invests                                      on   invests.id  = investigationresults.investid 
                                 join lab_devices_ranges              on   invests.id  = lab_devices_ranges.investid 
                                where investigationresults.deleted = 0 and investigationresults.sample_id = ? 
                                and  lab_devices_ranges.deleted = 0 and lab_devices_ranges.device_id = ? 
                                order by invests.sort desc , investigationresults.id asc  ', [$sampleId, $deviceId]);

    //  r::debug(false);

    $visitId = 0;
    $lipidItr = 0;
    $gfrItr = 0;
    foreach ($invests as $invest) {
        if ($visitId == 0) {
            $visitId = $invest['visitid'];
        }

        if ($invest['special_inv_type'] == 0) {
            if ($invest['filled'] != 1 || $invest['investresult'] == '' || is_null($invest['investresult'])) {
                $anatomies = normalTests($invest, $deviceId, $anatomies);
            }
        } elseif ($invest['special_inv_type'] > 0) {
            if ($invest['special_inv_type'] == 14) {
                $lipidItr++;
                if ($lipidItr == 1 && $invest['filled'] != 1) {
                    $anatomies = elementTests($invest, $deviceId, $anatomies);
                }
            } elseif ($invest['special_inv_type'] == 15) {
                $gfrItr++;
                if ($gfrItr == 1 && $invest['filled'] != 1) {
                    $anatomies = elementTests($invest, $deviceId, $anatomies);
                }
            } else {
                if ($invest['filled'] != 1) {
                    $anatomies = elementTests($invest, $deviceId, $anatomies);
                }
            }
        }
    }


    $patArray = preparePatArray($visitId);
    $data = array();
    $data['patent_id'] = $patArray['patId'];
    $data['gender'] = $patArray['sex'];
    $data['name'] = $patArray['name'];
    $data['age'] = $patArray['age'];
    $data['ageUnit'] = $patArray['ageName'];
    $data['anatomies'] = $anatomies;

    $result['res'] = $data;
    return $result;
}

function preparePatArray($visitId) {
    $visit = R::load('visits', $visitId);
    $programesetting = R::findOne('programesetting');

    $patient = R::load('patients', $visit->patientid);

    if ($programesetting->system_lang == 2) {
        $name = $patient->wifename;
        $date = $patient->dateofbirth;
        $phone = $patient->phone;
        if ($patient->gender == 1) {
            $sex = 'M';
            $gender = 1;
        } else {
            $sex = 'F';
            $gender = 0;
        }
    } else {

        if ($visit->for_husband == 1) {
            $date = $patient->husbanddateofbirth;
            $gender = 1;
            $phone = $patient->hus_mobile;

            $name = $patient->husdandname;
            $sex = 'M';
        }
###
        else if ($visit->for_husband == 2) {
            $child = R::load('patients_childs', $visit->child);
            $date = $child->birth_date;
            $phone = $patient->phone;

            if ($child->gender == 1) {
                $gender = 1;
                $title = 'الطفل  ';
                $sex = 'M  ';
            } else {
                $gender = 0;
                $title = 'الطفلة  ';
                $sex = 'F  ';
            }

            $name = $child->child_name;
        }
###
        else {
            $date = $patient->dateofbirth;
            $gender = 0;
            $phone = $patient->phone;
            $name = $patient->wifename;
            $sex = 'F';
        }
    }

    if ($date == '0000-00-00' || is_null($date) || $date == '') {
        $age = 0;
    } else {
## calculate wife age
        $dateWife = new DateTime($date);
        $today1 = new DateTime(date('Y-m-d'));
        $interval = $today1->diff($dateWife);
    }

    if ($interval->y > 0) {
        $ageAll = $interval->y . ' Years';
        $age = $interval->y;
        $ageUnit = 1;
        $ageName = 'Years';
    } elseif ($interval->m > 0) {
        $ageAll = $interval->m . ' Months';
        $age = $interval->m;
        $ageUnit = 2;
        $ageName = 'Months';
    } elseif ($interval->d >= 0) {
        $ageAll = 1 + $interval->d . ' Days';
        $age = 1 + $interval->d;
        $ageUnit = 3;
        $ageName = 'Days';
    }


    $patArray = array();
    $patArray['name'] = $name;
    $patArray['statusno'] = $patient->statusno;
    $patArray['patientId'] = $patient->wifenationalid;
    $patArray['patId'] = $patient->id;
    $patArray['ageAll'] = $ageAll;
    $patArray['sex'] = $sex;
    $patArray['patientid'] = $visit->patientid;
    $patArray['phone'] = $phone;
    $patArray['age'] = $age;
    $patArray['ageUnit'] = $ageUnit;
    $patArray['ageName'] = $ageName;
    $patArray['gender'] = $gender;
    $patArray['visitId'] = $visitId;

    return $patArray;
}

function normalTests($invest, $deviceId, $anatomies) {
    $decInvest = R::getRow(' select lab_devices_ranges.send_code , lab_devices_ranges.receive_code 
                                from lab_devices_ranges 
                                where lab_devices_ranges.deleted = 0 and lab_devices_ranges.investid = ? 
                                 and lab_devices_ranges.device_id = ? and lab_devices_ranges.send_code != "" 
                                 and lab_devices_ranges.receive_code != "" and lab_devices_ranges.send_code is not null
                                  and lab_devices_ranges.receive_code is not null  '
                    , [$invest['investid'], $deviceId]);

    $anatomy = array();
    $anatomy['id'] = $invest['investid'];
    $anatomy['name'] = $invest['investName'];
    $anatomy['send_code'] = $decInvest['send_code'];
    $anatomy['receive_code'] = $decInvest['receive_code'];

    $anatomies[] = $anatomy;
    return $anatomies;
}

function elementTests($invest, $deviceId, $anatomies) {
    $invElements = R::getAll(' select distinct lab_devices_ranges.invest_child 
                                                   ,   lab_devices_ranges.send_code , lab_devices_ranges.receive_code 
                                from lab_devices_ranges 
                                where lab_devices_ranges.deleted = 0 and lab_devices_ranges.investid = ? 
                                 and lab_devices_ranges.device_id = ?  and lab_devices_ranges.send_code != "" 
                                 and lab_devices_ranges.receive_code != "" and lab_devices_ranges.send_code is not null
                                  and lab_devices_ranges.receive_code is not null  '
                    , [$invest['investid'], $deviceId]);

    foreach ($invElements as $element) {
        $anatomy = array();
        $anatomy['id'] = $invest['investid'];
        $anatomy['name'] = $element['invest_child'];
        $anatomy['send_code'] = $element['send_code'];
        $anatomy['receive_code'] = $element['receive_code'];

        $anatomies[] = $anatomy;
    }

    return $anatomies;
}

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

function saveresults() {

    $sampleId = (int) $_POST['sample_id'];
    $deviceId = (int) $_POST['device_id'];
    $deviceName = $_POST['device_name'];
    $res = $_POST['result'];
    $receiveCode = $_POST['receiving_code'];
    $sendCode = $_POST['sending_code'];

    $result = saveResultsCommon($sampleId, $deviceId, $deviceName, $res, $receiveCode, $sendCode);

    echo json_encode($result);
}

function saveresultsMulti() {
    $finalResult = array();
    $requestResults = json_decode(file_get_contents("php://input"));
    foreach ($requestResults->requestResult as $requestResult) {
        $sampleId = (int) $requestResult->sample_id;
        $deviceId = (int) $requestResult->device_id;
        $deviceName = $requestResult->device_name;
        $res = $requestResult->result;
        $receiveCode = $requestResult->receiving_code;
        $sendCode = $requestResult->sending_code;

        $result = saveResultsCommon($sampleId, $deviceId, $deviceName, $res, $receiveCode, $sendCode);
        $finalResult[] = $result;
    }
    echo json_encode($finalResult);
}

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

function saveResultsCommon($sampleId, $deviceId, $deviceName, $res, $receiveCode, $sendCode) {
    $result = array("success" => 0, "error" => 0, "errorMsg" => '');
    $log = R::xdispense('saveresultslog');
    $log->sample_id = $sampleId;
    $log->device_id = $deviceId;
    $log->device_name = $deviceName;
    $log->result = $res;
    $log->receiving_code = $receiveCode;
    $log->sending_code = $sendCode;
    $log->create_date = date('Y-m-d H:i:s');

//    $invest = R::getRow(' select lab_devices_ranges.id  , lab_devices_ranges.invest_child 
//                                            , lab_devices_ranges.special_inv_type  , lab_devices_ranges.investid
//                                from lab_devices_ranges 
//                                join invests                     on lab_devices_ranges.investid = invests.id 
//                                join investigationresults                    on investigationresults.investid = invests.id
//                                where lab_devices_ranges.deleted = 0 and lab_devices_ranges.device_id = ? 
//                                 and lab_devices_ranges.send_code = ? and lab_devices_ranges.receive_code = ?  
//                                 order by invests.sort desc limit 1  '
//                    , [$deviceId, $sendCode, $receiveCode]);

    $invest = R::getRow(' select lab_devices_ranges.id  , lab_devices_ranges.invest_child 
                                            , lab_devices_ranges.special_inv_type  , lab_devices_ranges.investid
                                            ,investigationresults.id as invResId
                                from investigationresults 
                               join lab_devices_ranges                    on investigationresults.investid = lab_devices_ranges.investid
                                join invests                     on investigationresults.investid = invests.id 
                             
                                where lab_devices_ranges.deleted = 0 and lab_devices_ranges.device_id = ? 
                                 and lab_devices_ranges.send_code = ? and lab_devices_ranges.receive_code = ?  
                                 and investigationresults.sample_id = ? and  investigationresults.deleted = 0 
                                 order by invests.sort desc , investigationresults.id asc '
                    , [$deviceId, $sendCode, $receiveCode, $sampleId]);

    if (count($invest) > 0) {
        $log->lab_devices_ranges_id = $invest['id'];
        $return = invTypeSwitch($result, $log, $sampleId, $deviceId, $invest, $res);
        $log = $return['log'];
        $result = $return['result'];
    } else {
        $result['success'] = 0;
        $result['error'] = 1;
        $result['errorMsg'] = "Error : inv device range element not found";
    }

    R::store($log);

    return $result;
}

function invTypeSwitch($result, $log, $sampleId, $deviceId, $invest, $res) {
    switch ($invest['special_inv_type']) {
        case 1:           ## blood 
            $tableName = 'investigationresults_blood';
            $elements = array("Hgb" => "hgb", "RBC" => "rbc", "Plt" => "plt", "WBC" => "wbc"
                , "Hct" => "hct", "MCV" => "mcv_calc", "MCH" => "mch_calc", "MCHC" => "mchc_calc"
                , "RDW" => "rdw", "Mentzer Index %" => "mindex", "Other Cells" => "othercells"
                , "Segmented" => "segmented", "Band" => "band", "Pct" => "pct", "MPV" => "mpv"
                , "PDW" => "pdw", "NRBC / 100 WBC" => "nrbc", "Promyelocyte" => "promyelocyte"
                , "Myelocytes" => "myelocyte", "Juvenile" => "juvenile", "Blast" => "blast", "Hgb %" => "hgbpercent"
                , "Relative Neutrophil" => "neutrophil_r", "Relative Lymphocytes" => "lymphocytes_r"
                , "Relative Monocytes" => "monocytes_r", "Relative Eosinophils" => "eosinophils_r"
                , "Relative Basophils" => "basophils_r", "Absolute Neutrophil" => "neutrophil_abs"
                , "Absolute Lymphocytes" => "lymphocytes_abs", "Absolute Monocytes" => "monocytes_abs"
                , "Absolute Eosinophils" => "eosinophils_abs", "Absolute Basophils" => "basophils_abs"
            );
            $dbName = $elements[$invest['invest_child']];
            $return = saveElementRes($result, $log, $sampleId, $deviceId, $invest, $res, $tableName, $dbName);
            break;
        case 2:           ## urine 
            $tableName = 'investigationresults_urine';
            $elements = array("Volume" => "volume", "Color" => "color", "Odor" => "odor", "Aspect" => "aspect"
                , "Deposit" => "deposit", "Reaction" => "reaction", "Protein" => "protein", "Sugar" => "sugar", "Acetone" => "acetone"
                , "Nitrite" => "nitrite", "Specific Gravity" => "gravity", "Bilirubin" => "bilirubin", "Urobilinigen" => "urobilinigen"
                , "Leucocytes" => "leucocytes", "Blood" => "blood", "Pus Cells" => "pus", "R.B.Cs" => "pbcs"
                , "Epithelial Cells" => "epithelial", "Casts" => "casts", "Crystal" => "crystal", "Amorphous" => "amorphous"
                , "Ova" => "ova", "Trophazite" => "trophazite", "Mucus" => "mucus", "Urine Artifacts" => "artifacts"
                , "Fungi" => "fungi", "Bacteria" => "bacteria"
            );
            $dbName = $elements[$invest['invest_child']];
            $return = saveElementRes($result, $log, $sampleId, $deviceId, $invest, $res, $tableName, $dbName);
            break;
        case 3:           ## stool 
            $tableName = 'investigationresults_stool';
            $elements = array("Consistency" => "consistency", "Food Particles" => "food", "Blood" => "blood"
                , "Color" => "color", "Reaction" => "reaction", "Odor" => "odor"
                , "Mucus" => "mucus", "Proglottids" => "prog", "Flagellates" => "flagellates"
                , "Ciliate" => "ciliate", "Undigested Food" => "undigested", "Parasitology Artifacts" => "parasitology"
                , "WBCs" => "wbc", "RBCs" => "rbc", "Trophozoite" => "trophozoite"
                , "Cysts" => "cysts", "Ova" => "ova", "Larva" => "larva"
            );
            $dbName = $elements[$invest['invest_child']];
            $return = saveElementRes($result, $log, $sampleId, $deviceId, $invest, $res, $tableName, $dbName);
            break;
        case 4:           ## Culture 
            $tableName = 'investigationresults_culture';
            break;
        case 5:           ## ESR 
            $tableName = 'investigationresults_esr';
            $elements = array("hour1" => "hour1", "hour2" => "hour2");
            break;
        case 6:           ## Cross 
            $tableName = 'investigationresults_cross';
            break;
        case 7:           ## Fluid 
            break;
        case 8:           ## Clothing 
            $tableName = 'investigationresults_times';
            $elements = array("Bleeding Time" => "bleeding", "Clothing Time" => "clothing");
            break;
        case 9:           ## PT + APTT
        case 12:         ## PT  
        case 13:         ## APTT 
            $tableName = 'investigationresults_pt';
            $elements = array("PT Patient's Time" => "patient_time", "APTT Patient's Time" => "patient_time1"
                , "Concentration" => "concentration", "I.N.R" => "inr", "Ratio" => "ratio"
                , "Fibrinogen" => "fibrinogen", "FDP" => "fdp");
            break;
        case 10:         ## ABO/RH 
            $tableName = 'investigationresults_aborh';
            break;
        case 11:         ## Custom 
            $tableName = 'investigationresults_custom';
            break;
        case 14:         ## Lipid 
            $tableName = 'investigationresults_lipid';
            $elements = array("Cholesterol" => "cholesterol", "Triglycerides" => "triglycerides"
                , "HDL Cholesterol" => "hdl", "LDL Cholesterol" => "ldl", "Non-HDL Cholesterol" => "nonhdl"
                , "VLDL Cholesterol" => "vldl", "Risk ratio I" => "riskratio1", "Risk ratio II" => "riskratio2"
                , "Risk ratio III" => "riskratio3");
            $dbName = $elements[$invest['invest_child']];
            $return = saveElementRes($result, $log, $sampleId, $deviceId, $invest, $res, $tableName, $dbName);
            break;
        case 15:         ## EGFR 
            $tableName = 'investigationresults_egfr';
            $elements = array("eGFR" => "gfr", "Serum Creatinine" => "cr");
            $dbName = $elements[$invest['invest_child']];
            $return = saveElementRes($result, $log, $sampleId, $deviceId, $invest, $res, $tableName, $dbName);
            break;
        case 16:         ## Semen
            $tableName = 'investigationresults_semen';
            $elements = array("Volume" => "volume", "PH" => "ph", "Color" => "color", "Odor" => "odor"
                , "Viscosity" => "viscosity", "Liquifaction Time" => "liq_time", "Liquefection State" => "liq_state",
                "Concenteration" => "sperm_count", "Total Sperm" => "total_count", "Progressive motility" => "mobility_a"
                , "Non Progressive" => "mobility_c", "Total motility" => "mobility_b", "Immotile" => "mobility_d"
                , "Normal Sperm" => "normal_form", "Abnormal Sperm" => "ab_form", "Vitality" => "vitality"
                , "Pinheads" => "pinheads", "White Blood Cells" => "pus", "Red Blood Cells" => "rbc"
                , "Spermatogenic Cells" => "sperm_cells", "Epithelial Cells" => "epith_cells", "Others Cells" => "mobility_percent"
                , "Agglutination" => "agg", "Aggregation" => "aggregation"
                , "Coll. Location" => "coll_location", "Abestination" => "abestination", "Coll. Method" => "coll_method");
            $dbName = $elements[$invest['invest_child']];
            $return = saveElementRes($result, $log, $sampleId, $deviceId, $invest, $res, $tableName, $dbName);
            break;
        default :
            $return = saveResNormal($result, $log, $sampleId, $deviceId, $invest, $res);
            break;
    }

    return $return;
}

function saveResNormal($result, $log, $sampleId, $deviceId, $invest, $res) {
    $investRes = R::findOne('investigationresults', '  deleted = 0 and sample_id = ? and investid = ? 
                              ', [$sampleId, $invest['investid']]);
    if (count($investRes) > 0) {
        $log->investigationresults_id = $investRes->id;
        if ($investRes->verified == 1) {
            $result['success'] = 0;
            $result['error'] = 1;
            $result['errorMsg'] = "Error : inv result already verified";
        } else {
            $investRes->investresult = $res;
            $investRes->filled = 1;
            $investRes->device_id = $deviceId;
            R::store($investRes);
            $result['error'] = 0;
            $result['success'] = 1;
            $result['errorMsg'] = "";
        }
    } else {
        $result['success'] = 0;
        $result['error'] = 1;
        $result['errorMsg'] = "Error : inv result element not found";
    }

    $return = array();
    $return['log'] = $log;
    $return['result'] = $result;

    return $return;
}

function saveElementRes($result, $log, $sampleId, $deviceId, $invest, $res, $tableName, $dbName) {
    $investRes = R::load('investigationresults', $invest['invResId']);
    if (count($investRes) > 0) {
        $log->investigationresults_id = $investRes->id;
        $log->element_name = $dbName;
        $log->element_table_name = $tableName;
        if ($investRes->verified == 1) {
            $result['success'] = 0;
            $result['error'] = 1;
            $result['errorMsg'] = "Error : inv result already verified";
        } else {
            $elementRes = R::findOne($tableName, '  investigationresults_id = ?  ', [$investRes->id]);
            if (count($elementRes) > 0) {

                $elementRes->$dbName = $res;
                $investRes->filled = 1;
                $investRes->device_id = $deviceId;
                $log->element_table_id = $elementRes->id;

                if ($invest['special_inv_type'] == 14) {
                    $elementRes = lipidCalculations($elementRes);
                } else if ($invest['special_inv_type'] == 15) {
                    $elementRes = egfrCalculations($elementRes, $investRes->visitid);
                }

                R::store($elementRes);
                R::store($investRes);

                $result['error'] = 0;
                $result['success'] = 1;
                $result['errorMsg'] = "";
            } else {
                $result['success'] = 0;
                $result['error'] = 1;
                $result['errorMsg'] = "Error : inv result element not found";
            }
        }
    } else {
        $result['success'] = 0;
        $result['error'] = 1;
        $result['errorMsg'] = "Error : inv result element not found";
    }

    $return = array();
    $return['log'] = $log;
    $return['result'] = $result;

    return $return;
}

function lipidCalculations($elementRes) {
    $tg = $elementRes->triglycerides;
    $cho = $elementRes->cholesterol;
    $hdl = $elementRes->hdl;

    $vldl = $tg / 5;
    $ldl = $cho - $hdl - $vldl;
    $nonhdl = $cho - $hdl;

    if ($hdl > 0) {
        $riskratio1 = $tg / $hdl;
        $riskratio2 = $ldl / $hdl;
        $riskratio3 = $cho / $hdl;
    } else {
        $riskratio1 = '';
        $riskratio2 = '';
        $riskratio3 = '';
    }

    $elementRes->ldl = round($ldl, 2);
    $elementRes->vldl = round($vldl, 2);
    $elementRes->nonhdl = round($nonhdl, 2);
    $elementRes->riskratio1 = round($riskratio1, 2);
    $elementRes->riskratio2 = round($riskratio2, 2);
    $elementRes->riskratio3 = round($riskratio3, 2);

    return $elementRes;
}

function egfrCalculations($elementRes, $visitId) {
    $patArray = preparePatArray($visitId);
    $gender = $patArray['gender'];
    $age = $patArray['age'];
    $ageUnit = $patArray['ageUnit'];

    $cr = $elementRes->cr;
    $egfr = 175;

    if ($cr > 0) {
        if ($gender != 1) {
            $egfr = 0.742 * $egfr;
        }

        if ($age > 0 && $ageUnit == 1) {
            $egfr = ( pow($age, -0.203)) * $egfr;
        }

        $egfr = ( pow($cr, -1.154)) * $egfr;
    } else {
        $egfr = 0;
    }

    $elementRes->gfr = round($egfr, 2);

    return $elementRes;
}



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

function orglogin() {
    $result = array("success" => 0, "error" => 0, "errorMsg" => '', "res" => array());
    $userName = $_POST['user_name'];
    $password = $_POST['password'];

    if ($userName == '') {
        $result['success'] = 0;
        $result['error'] = 1;
        $result['errorMsg'] = "User Name Required";
    } elseif ($password == '') {
        $result['success'] = 0;
        $result['error'] = 1;
        $result['errorMsg'] = "Password Required";
    } else {
        $result = checkUserLogin($userName, $password, $result);
    }
    echo json_encode($result);
}

function checkUserLogin($userName, $password, $result) {
    $org = R::findOne('organizations', ' user_name = ?  ', [$userName]);
    if (!isset($org->id)) {
        $result['success'] = 0;
        $result['error'] = 1;
        $result['errorMsg'] = "User Name Does Not Exist";
    } else {
        if (password_verify($password, $org->user_password_hash)) {
            $result['success'] = 1;
            $result['error'] = 0;
            $result['errorMsg'] = " ";

            $data = array();
            $data['org_id'] = $org->id;
            $data['org_no'] = $org->org_id;
            $data['org_name'] = $org->organization_name;
            $result['res'] = $data;
        } else {
            $result['success'] = 0;
            $result['error'] = 1;
            $result['errorMsg'] = "Password Incorrect";
        }
    }

    return $result;
}


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

function orgpatientinfo() {
    $result = array("success" => 0, "error" => 0, "errorMsg" => '', "res" => array());
    $org_id = $_POST['org_id'];
    $patient_name = $_POST['patient_name'];
    $patient_no = $_POST['patient_no'];
    $date_from = $_POST['date_from'];
    $date_to = $_POST['date_to'];

    if (!($org_id > 0 )) {
        $result['success'] = 0;
        $result['error'] = 1;
        $result['errorMsg'] = "Organization Id  Required";
    } else {
        $result = checkPatientVisits($org_id, $patient_name, $patient_no, $date_from, $date_to, $result);
    }
    echo json_encode($result);
}

function checkPatientVisits($org_id, $patient_name, $patient_no, $date_from, $date_to, $result) {
    $ext = ' ';
    if ($patient_name != '' && !empty($patient_name)) {
        $ext .= ' and (patients.wifename  = "' . $patient_name . '"  || patients.husdandname  =   "' . $patient_name . '"  )  ';
    }

    if ($patient_no != '' && !empty($patient_no)) {
        $ext .= ' and organizations_patient_no.patient_no  = "' . $patient_no . '"';
    }

    if ($date_from != '' && !empty($date_from)) {
        $ext .= ' and visits.visitdate  >= "' . $date_from . '"';
    }

    if ($date_to != '' && !empty($date_to)) {
        $ext .= ' and visits.visitdate  <= "' . $date_to . '"';
    }

    // R::debug(true, 2);
    $visits = R::getAll(' select distinct  visits.id as visit_id  , visits.visitdate  , organizations_patient_no.patient_no
                                            , patients.id  as patient_id
                                from visits
                               join patients                    on patients.id = visits.patientid
                               left join organizations_patient_no       on patients.id = organizations_patient_no.patient_id 
                                                      and organizations_patient_no.organization_id  = ' . $org_id . '  

                                where visits.deleted = 0 and visits.organization_id = ? ' . $ext . '
                                 order by visits.visitdate desc ', [$org_id]);

  //  R::debug(false);
    $visits = visitsCommon($visits);
 
    
    
    $result['success'] = 1;
    $result['error'] = 0;
    $result['errorMsg'] = " ";
    $result['res'] = $visits;

    return$result;
}

function visitsCommon($visits) {
    $i = 0;
    foreach ($visits as $visit) {
        $patArray = preparePatArray($visit['visit_id']);
        $visits[$i]['patient_name'] = $patArray['name'];
        
               $delivered = R::count('investigationresults', ' deleted = 0 and delivered = 1  and   visitid = ?
                     and filled = 1  and verified = 1   ', [$visit['visit_id']]);
        $visits[$i]['delivered_count'] = $delivered;
        
        
        $i++;
    }
    return $visits;
}





