<?php

##  $source= 1    lab dept    ,   $source= 5  Operation Data   ,   $source= 6  patient labs report
##############################  pdf  file preparing

function investsForPdf($dataArray, $htmlHead, $htmlFoot, $invResId, $gender, $age, $ageUnit, $smarty, $source, $reDeliver) {

    $in = R::load('investigationresults', $invResId);
    $obj = R::load('invests', $in->investid);

    $cat = R::load('investcats', $obj->investcatid);
    $in->invname = $obj->name;
    $in->special_inv_type = $obj->special_inv_type;
    $in->invests = $obj;

    //$fileName = 'test.pdf';
    $fileName = md5(uniqid(mt_rand(), true)) . '.pdf';
    $dataArray['test_name'] = $obj->name;
    $dataArray['invResId'] = $invResId;
    $dataArray['is_pathology'] = $cat->pathology;

    // create some HTML content
    switch ($obj->special_inv_type) {
## urine
        case 2:
            $urine_count = R::count('investigationresults_urine', 'investigationresults_id = ?', [$in->id]);
            if ($urine_count < 1) {
                $urine = R::xdispense('investigationresults_urine');
                $urine->investigationresults_id = $in->id;
                r::store($urine);
            }
            $urine = printUrine($in, $gender, $age, $ageUnit, $smarty);
            $htmlBody = urineHtml($urine, $cat->name, $obj->name);
            break;

## stool
        case 3:
            $stool_count = R::count('investigationresults_stool', 'investigationresults_id = ?', [$in->id]);
            if ($stool_count < 1) {
                $stool = R::xdispense('investigationresults_stool');
                $stool->investigationresults_id = $in->id;
                r::store($stool);
            }
            $stool = printStool($in, $gender, $age, $ageUnit, $smarty);
            $htmlBody = stoolHtml($stool, $cat->name, $obj->name);
            break;

## blood picture
        case 1:
            $blood_count = R::count('investigationresults_blood', 'investigationresults_id = ?', [$in->id]);
            if ($blood_count < 1) {
                $blood = R::xdispense('investigationresults_blood');
                $blood->investigationresults_id = $in->id;
                r::store($blood);
            }
            $blood = printBlood($in, $gender, $age, $ageUnit, $smarty);
            $htmlBody = bloodHtml($blood, $cat->name, $obj->name);
            break;

## Culture
        case 4:

            $culture_count = R::count('investigationresults_culture', 'investigationresults_id = ?', [$in->id]);
            if ($culture_count < 1) {
                $culture = R::xdispense('investigationresults_culture');
                $culture->investigationresults_id = $in->id;
                r::store($culture);
            }
            $culture = printCulture($in, $smarty);
            $htmlBody = cultureHtml($culture, $cat->name, $obj->name);
            break;

## ESR
        case 5:
            $esr_count = R::count('investigationresults_esr', 'investigationresults_id = ?', [$in->id]);
            if ($esr_count < 1) {
                $esr = R::xdispense('investigationresults_esr');
                $esr->investigationresults_id = $in->id;
                r::store($esr);
            }

            $esr = loadEsrRanges($in, $gender, $age, $ageUnit, $smarty);
            $htmlBody = esrHtml($esr, $cat->name, $obj->name);
            break;

## Cross Matching
        case 6:
            $cross_count = R::count('investigationresults_cross', 'investigationresults_id = ?', [$in->id]);
            if ($cross_count < 1) {
                $cross = R::xdispense('investigationresults_cross');
                $cross->investigationresults_id = $in->id;
                r::store($cross);
            }

            $cross = printCross($in, $smarty);
            $htmlBody = crossHtml($cross, $cat->name, $obj->name);
            break;

## Fluid
        case 7:

            $notUrine++;
            break;

## Custom
        case 11:
            $customElements = customInvDetails($in, $gender, $age, $ageUnit, $smarty, 1);
            $htmlBody = customHtml($customElements, $cat->name, $obj->name, $in->comment);
            break;

## Clothing time
        case 8:
            $clothing_count = R::count('investigationresults_times', 'investigationresults_id = ?', [$in->id]);
            if ($clothing_count < 1) {
                $clothing = R::xdispense('investigationresults_times');
                $clothing->investigationresults_id = $in->id;
                r::store($clothing);
            }
            $clothing = loadClothingDetails($in, $gender, $age, $ageUnit, $smarty, 1);
            $htmlBody = clothingHtml($clothing, $cat->name, $obj->name);
            break;

## PT + APTT
        case 9:
## PT
        case 12:
##  APTT
        case 13:
            $pt_count = R::count('investigationresults_pt', 'investigationresults_id = ?', [$in->id]);
            if ($pt_count < 1) {
                $pt = R::xdispense('investigationresults_pt');
                $pt->investigationresults_id = $in->id;
                r::store($pt);
            }

            $pt = loadPtDetails($in, $gender, $age, $ageUnit, $smarty, 1);
            $htmlBody = ptHtml($pt, $cat->name, $obj->name, $obj->special_inv_type);
            break;

## ABO/RH
        case 10:
            $aborh_count = R::count('investigationresults_aborh', 'investigationresults_id = ?', [$in->id]);
            if ($aborh_count < 1) {
                $aborh = R::xdispense('investigationresults_aborh');
                $aborh->investigationresults_id = $in->id;
                r::store($aborh);
            }
            $aborh = printAborh($in, $smarty);
            $htmlBody = aborhHtml($aborh, $cat->name, $obj->name);
            break;

        default :
            $in = printCommon($in, $smarty);
            $htmlBody = normalHtml($in, $cat->name, $obj->name);

            break;
    }

    $res = generateInvestPdf($dataArray, $htmlBody, $htmlHead, $htmlFoot, $fileName, $reDeliver);
    return $res;
}

function generateInvestPdf($dataArray, $htmlBody, $htmlHead, $htmlFoot, $fileName, $reDeliver) {
    ob_start();

    $programesetting = R::findOne('programesetting');

    require_once("../../_library/plugins/tcpdf/tcpdf.php");
// create new PDF document
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

// set default monospaced font
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

// set margins
    $pdf->SetMargins(5, $programesetting->above2, 5);
    $pdf->SetHeaderMargin(0);
    $pdf->SetFooterMargin(0);

    $pdf->SetPrintHeader(false);
    $pdf->SetPrintFooter(false);

// set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

// set some language-dependent strings (optional)
    if (@file_exists(dirname(__FILE__) . '/lang/eng.php')) {
        require_once(dirname(__FILE__) . '/lang/eng.php');
        $pdf->setLanguageArray($l);
    }

// ---------------------------------------------------------
    define('K_PATH_FONTS', dirname(__FILE__) . '/../../_library/plugins/tcpdf/');
// set font
    $pdf->SetFont('dejavusans', '', 10);
// add a page
    $pdf->AddPage();

    $html = $htmlHead . ' ' . $htmlBody . ' ' . $htmlFoot;

// output the HTML content
    $pdf->writeHTML($html, true, false, true, false, '');

// reset pointer to the last page
    $pdf->lastPage();

    if (!file_exists('../../upload/inv_pdf/' . $dataArray['statusno'])) {
        //    print_r(555);
        mkdir('../../upload/inv_pdf/' . $dataArray['statusno'], 0777, true);
    }

//    $fileName = '5555.pdf';
//Close and output PDF document
    $pdf->Output(__DIR__ . '/../../upload/inv_pdf/' . $dataArray['statusno'] . '/' . $fileName, 'F');

    $invRes = R::load('investigationresults', $dataArray['invResId']);
    $invRes->pdf = $fileName;
    r::store($invRes);

    $res = sendPdf($fileName, $dataArray, $reDeliver);

    return $res;
//============================================================+
// END OF FILE
//============================================================+
}

function sendPdf($fileName, $dataArray, $reDeliver) {

    // echo  '../../upload/inv_pdf/' . $dataArray['statusno'] . '/' . $fileName;
    //    echo ' - ' . file_exists('../../upload/inv_pdf/30886/1f6e8ae4ea2e1385e777c3be395ed67e.pdf') ;
    //   echo file_exists('../../upload/inv_pdf/' . $dataArray['statusno'] . '/' . $fileName). ' - ' ;
    //  echo $dataArray['phone'] ;

    if ($reDeliver == 1) {
        $url = 'http://lab.royal-fc.net/api/patient-test/update';
        $data = array(
            'royal_patient_id' => $dataArray['royal_patient_id']
            , 'test_name' => $dataArray['test_name']
            , 'test_pdf' => new CURLFile('../../upload/inv_pdf/' . $dataArray['statusno'] . '/' . $fileName, 'application/pdf')
            , 'plus_file' => ''
            , 'visit_id' => $dataArray['visit_id']
            , 'invest_id' => $dataArray['invResId']
            , 'is_pathology' => $dataArray['is_pathology']
            , 'phone' => $dataArray['phone']
        );
    } else {
        $url = 'http://lab.royal-fc.net/api/patient-test';
        $data = array(
            'name' => $dataArray['name']
            , 'royal_patient_id' => $dataArray['royal_patient_id']
            , 'age' => $dataArray['age']
            , 'sex' => $dataArray['sex']
            , 'test_name' => $dataArray['test_name']
            , 'referred_by' => $dataArray['referred_by']
            , 'phone' => $dataArray['phone']
            , 'requested_date' => $dataArray['requested_date']
            , 'printed_date' => $dataArray['printed_date']
            , 'test_pdf' => new CURLFile('../../upload/inv_pdf/' . $dataArray['statusno'] . '/' . $fileName, 'application/pdf')
            , 'plus_file' => ''
            , 'visit_id' => $dataArray['visit_id']
            , 'invest_id' => $dataArray['invResId']
            , 'is_pathology' => $dataArray['is_pathology']
        );
    }

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

    // Initializes a new cURL session
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    // 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
    ));

    // Execute cURL request with all previous settings
    $response = curl_exec($curl);

//    if (curl_errno($curl)) {z
//        $error_msg = curl_error($curl);
//    }
    // Close cURL session
    curl_close($curl);

    //  echo $response . PHP_EOL;

    $res = json_decode($response);
//    print_r($res);
//    print_r($res->success);
    // print_r($res->error);

    if ($res->success) {
        return $res->success;
    } else {
        return $res->error->message;
    }
}

##########  common  section   ##########

function testHead($catName, $invname, $nameExist = 1) {
    $htmlBody = '

<table   class="noborder wds98">
    <tr style="line-height: 20px; ">
        <td class="wds75">
            <span class="underline bold catName">' . $catName . '  Report </span>
        </td>

        <td class="wds25">
            <span  class="underline bold catName">Reference Range</span>
        </td>
    </tr>
</table> ';

    if ($nameExist == 1) {
        $htmlBody .= '
<table style="width: 98%;">
    <tr style="line-height: 20px; ">
        <td  style="width: 100%;">
                    <span style=" text-decoration: underline ;font-weight: bold;    margin-left: 15px;">
                       ' . $invname . '
                    </span>
        </td>
    </tr>
 </table> ';
    }

    return $htmlBody;
}

function testSubHead($subTitleName) {
    $htmlBody = '<table style="width: 98%;">
    <tr style="line-height: 20px; ">
        <td  style="width: 100%;">
            <ul>
                <li style="list-style: disc;">
                    <span style=" text-decoration: underline ;font-weight: bold;">
                        ' . $subTitleName . '  :
                    </span>
                </li>
            </ul>
        </td>
    </tr> </table> ';

    return $htmlBody;
}

function commentsPrint($comment) {
    $htmlBody = '';

    if ($comment != Null && $comment != '') {
        $htmlBody .= '<table style="width: 98%;">
    <tr style="line-height: 20px; ">
        <td  style="width: 100%;">
            <ul>
                <li style="list-style: disc;">
                    <span style=" text-decoration: underline ;font-weight: bold;">
                        Comment :
                    </span>
                    <span> &nbsp;  &nbsp;  &nbsp;
                         ' . $comment . '
                    </span>
                </li>
            </ul>
        </td>
    </tr> </table> ';
    }

    return $htmlBody;
}

##############################  esr  Pdf Prepare ######################################

function normalHtml($test, $catName, $invname) {


    $htmlBody = '';

    $htmlBody .= testHead($catName, $invname, 0);

    $htmlBody .= normalCommon($test);

    $htmlBody .= commentsPrint($test->comment);
    #########################################################

    return $htmlBody;
}

function normalCommon($test) {
    $htmlBody = '';

    $htmlBody .= '
            <table style="width: 98%;">
                   <tr  style="line-height: 25px; ">
                        <td style="width: 30%; text-align:left;">
                       <ul><li style="list-style: disc;  font-weight: bold ;"> ' . $test->invname . '  </li>  </ul> </td>';

###################### TD
    $htmlBody .= ' <td style="width: 3%; "> :   ';
    $htmlBody .= ' </td>';
###################### TD
    $htmlBody .= '      <td style="width: 25%; "> ';

    if ($test->low == 1 || $test->high == 1) {
        $htmlBody .= '    <span style="background-color: #E5E5E5;" > ';
    } else {
        $htmlBody .= '   <span> ';
    }

//    $htmlBody .= $test->investresult;
    $htmlBody .= sympolErrorResolve($test->investresult);

    $htmlBody .= '   </span> ';

    $htmlBody .= ' </td>';
###################### TD
    $htmlBody .= ' <td style="width: 11%; ">  ';
    $htmlBody .= $test->range->invest_units;
    $htmlBody .= ' </td>';
###################### TD
    $htmlBody .= ' <td style="width: 6%; ">  ';

    if ($test->low == 1) {
        $htmlBody .= ' L ';
    } elseif ($test->high == 1) {
        $htmlBody .= ' H ';
    }

    $htmlBody .= ' </td>';

###################### TD
    $htmlBody .= ' <td style="width: 25%; ">  ';

    if ($test->range->range_txt != Null || $test->range->range_txt != '') {
//        $htmlBody .= $test->range->range_txt;
        $htmlBody .= sympolErrorResolve($test->range->range_txt);
    }

    $htmlBody .= ' </td>';
######################
    $htmlBody .= ' </tr>
        </table>';

    return $htmlBody;
}

##############################  ABO/RH  Pdf Prepare ######################################

function aborhHtml($aborh, $catName, $invname) {


    $htmlBody = '';

    $htmlBody .= testHead($catName, $invname);

    $htmlBody .= esrCommon($aborh, 'abo', 'ABO System');
    $htmlBody .= esrCommon($aborh, 'rh', 'Blood Rh');

    $htmlBody .= commentsPrint($aborh['comment']);
    #########################################################

    return $htmlBody;
}

##############################  PT  Pdf Prepare ######################################

function ptHtml($pt, $catName, $invname, $special_inv_type) {


    $htmlBody = '';

    $htmlBody .= testHead($catName, $invname);

    if ($special_inv_type == 9 || $special_inv_type == 12) {
        $htmlBody .= testSubHead('PT ( Prothrombin Time ) ');
        $htmlBody .= ptCommon($pt, 'patient_time', 'Patient Time ');
        $htmlBody .= ptCommon($pt, 'concentration', 'Concentration ');
        $htmlBody .= ptCommon($pt, 'inr', 'I.N.R ');
    }

    if ($special_inv_type == 9 || $special_inv_type == 13) {
        $htmlBody .= testSubHead('APTT ');
        $htmlBody .= ptCommon($pt, 'patient_time1', 'Patient Time ');
        $htmlBody .= ptCommon($pt, 'fibrinogen', 'Fibrinogen ');
        $htmlBody .= ptCommon($pt, 'fdp', 'FDP ');
    }



    $htmlBody .= commentsPrint($pt['comment']);
    #########################################################

    return $htmlBody;
}

function ptCommon($test, $element, $elementName, $element2 = '', $element2Sep = '&nbsp; ') {
    $htmlBody = '';
    if ($test->$element != Null && $test->$element != '') {
        $htmlBody .= '
            <table style="width: 98%;">
                   <tr  style="line-height: 40px; ">
                        <td style="width: 30%; text-align:left;">
                        &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp;' . $elementName . '  </td>';

###################### TD
        $htmlBody .= ' <td style="width: 3%; "> :   ';
        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= '      <td style="width: 25%; "> ';

        $element_low = $element . '_low';
        $element_high = $element . '_high';
        $element_invest_units = $element . '_invest_units';
        $element_range_txt = $element . '_range_txt';

        if ($test->$element_low == 1 || $test->$element_high == 1) {
            $htmlBody .= '    <span style="background-color: #E5E5E5;" > ';
        } else {
            $htmlBody .= '   <span> ';
        }

//        $htmlBody .= $test->$element;
//
//        if ($element2 != '') {
//            $htmlBody .= $element2Sep . ' ' . $test->$element2;
//        }


        $htmlBody .= sympolErrorResolve($test->$element);

        if ($element2 != '') {
            $htmlBody .= $element2Sep . ' ' . sympolErrorResolve($test->$element2);
        }



        $htmlBody .= '   </span> ';

        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= ' <td style="width: 11%; ">  ';
        $htmlBody .= $test->$element_invest_units;
        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= ' <td style="width: 6%; ">  ';

        if ($test->$element_low == 1) {
            $htmlBody .= ' L ';
        } elseif ($test->$element_high == 1) {
            $htmlBody .= ' H ';
        }

        $htmlBody .= ' </td>';

###################### TD
        $htmlBody .= ' <td style="width: 25%; ">  ';

        if ($test->$element_range_txt != Null || $test->$element_range_txt != '') {
            $htmlBody .= sympolErrorResolve($test->$element_range_txt);
        }

        $htmlBody .= ' </td>';
######################
        $htmlBody .= ' </tr>
        </table>';
    }

    return $htmlBody;
}

##############################  clothing  Pdf Prepare ######################################

function clothingHtml($clothing, $catName, $invname) {


    $htmlBody = '';

    $htmlBody .= testHead($catName, $invname);

    $htmlBody .= clothingCommon($clothing, 'bleeding', 'Bleeding Time ( BT ) ', 'bleeding_sec', ' : ');
    $htmlBody .= clothingCommon($clothing, 'clothing', 'Clothing Time ( CT )  ', 'clothing_sec', ' : ');

    $htmlBody .= commentsPrint($clothing['comment']);
    #########################################################

    return $htmlBody;
}

function clothingCommon($test, $element, $elementName, $element2 = '', $element2Sep = '&nbsp; ') {
    $htmlBody = '';
    if ($test->$element != Null && $test->$element != '') {
        $htmlBody .= '
            <table style="width: 98%;">
                   <tr  style="line-height: 40px; ">
                        <td style="width: 30%; text-align:left;">
                       <ul><li style="list-style: disc;  font-weight: bold ;"> ' . $elementName . '  </li>  </ul> </td>';

###################### TD
        $htmlBody .= ' <td style="width: 3%; "> :   ';
        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= '      <td style="width: 25%; "> ';

        $element_low = $element . '_low';
        $element_high = $element . '_high';
        $element_invest_units = $element . '_invest_units';
        $element_range_txt = $element . '_range_txt';

        if ($test->$element_low == 1 || $test->$element_high == 1) {
            $htmlBody .= '    <span style="background-color: #E5E5E5;" > ';
        } else {
            $htmlBody .= '   <span> ';
        }

        $htmlBody .= sympolErrorResolve($test->$element);

        if ($element2 != '') {
            $htmlBody .= $element2Sep . ' ' . $test->$element2;
        }



        $htmlBody .= '   </span> ';

        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= ' <td style="width: 11%; ">  ';
        $htmlBody .= $test->$element_invest_units;
        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= ' <td style="width: 6%; ">  ';

        if ($test->$element_low == 1) {
            $htmlBody .= ' L ';
        } elseif ($test->$element_high == 1) {
            $htmlBody .= ' H ';
        }

        $htmlBody .= ' </td>';

###################### TD
        $htmlBody .= ' <td style="width: 25%; ">  ';

        if ($test->$element_range_txt != Null || $test->$element_range_txt != '') {
            $htmlBody .= sympolErrorResolve($test->$element_range_txt);
        }

        $htmlBody .= ' </td>';
######################
        $htmlBody .= ' </tr>
        </table>';
    }

    return $htmlBody;
}

##############################  cross  Pdf Prepare ######################################

function crossHtml($cross, $catName, $invname) {


    $htmlBody = '';

    $htmlBody .= testHead($catName, $invname);

    $htmlBody .= esrCommon($cross, 'abo', 'The Patient ', 'rh');
    $htmlBody .= crossCommon($cross);

    $htmlBody .= commentsPrint($cross['comment']);
    #########################################################

    return $htmlBody;
}

function crossCommon($cross) {
    $htmlBody = '';

    $htmlBody .= '
            <table style="width: 98%;">
                   <tr  style="line-height: 25px; ">
                        <td style="width: 50%; text-align:left;">
                       <ul><li style="list-style: disc;font-weight: bold;">The Donors :   </li>  </ul> </td>';

###################### TD
    $htmlBody .= '
                        <td style="width: 50%; text-align:left;">
                       <ul><li style="list-style: disc;font-weight: bold;"> Viral Screen :   </li>  </ul> </td>';

######################
    $htmlBody .= ' </tr>
        </table>';

    if ($cross['donnersItr'] > 0) {

        $htmlBody .= '
            <table style="width: 100%;">
                   <tr  style="line-height: 25px; background-color: #E5E5E5;">';
        ###################### TD
        $htmlBody .= ' <td style="width: 27%;font-weight: bold; ">  &nbsp; Donor Name  ';
        $htmlBody .= ' </td>';
        ###################### TD
        $htmlBody .= ' <td style="width: 14%;font-weight: bold; ">  &nbsp;  Result  ';
        $htmlBody .= ' </td>';
        ###################### TD
        $htmlBody .= ' <td style="width: 14%; font-weight: bold;">  ';
        $htmlBody .= ' </td>';
        ###################### TD
        $htmlBody .= ' <td style="width: 15%;font-weight: bold; "> &nbsp;  &nbsp; HCV   ';
        $htmlBody .= ' </td>';
        ###################### TD
        $htmlBody .= ' <td style="width: 15%;font-weight: bold; "> &nbsp;  &nbsp;  HBsAg  ';
        $htmlBody .= ' </td>';
        ###################### TD
        $htmlBody .= ' <td style="width: 14%;font-weight: bold; "> &nbsp;  &nbsp; HV  ';
        $htmlBody .= ' </td>';

        $htmlBody .= ' </tr>';

        foreach ($cross['donners'] as $donner) {
            if ($donner['name'] != Null && $donner['name'] != '') {

                $htmlBody .= ' <tr style="line-height: 25px; ">';
                ###################### TD
                $htmlBody .= ' <td style="width: 27%; ">';
                $htmlBody .= sympolErrorResolve($donner['name']) . ' </td>';
                ###################### TD
                $htmlBody .= ' <td style="width: 14%; ">  :   ';
                $htmlBody .= $donner['abo_value'] . '  ' . $donner['rh_value'] . ' </td>';
                ###################### TD
                $htmlBody .= ' <td style="width: 14%; ">  ';
                $htmlBody .= $donner['compatibility_value'] . ' </td>';
                ###################### TD
                $htmlBody .= ' <td style="width: 15%; ">    ';
                $htmlBody .= $donner['hcv_value'] . ' </td>';
                ###################### TD
                $htmlBody .= ' <td style="width: 15%; ">    ';
                $htmlBody .= $donner['hbsag_value'] . ' </td>';
                ###################### TD
                $htmlBody .= ' <td style="width: 14%; ">  ';
                $htmlBody .= $donner['hv_value'] . ' </td>';
                $htmlBody .= ' </tr>';
            }
######################
        }
        $htmlBody .= ' </table>';
    }

    return $htmlBody;
}

##############################  custom  Pdf Prepare ######################################

function customHtml($elements, $catName, $invname, $comment) {
    $htmlBody = '';

    $htmlBody .= testHead($catName, $invname, 0);

    foreach ($elements as $element) {
        $htmlBody .= customCommon($element);
    }

    $htmlBody .= commentsPrint($comment);
    #########################################################

    return $htmlBody;
}

function customCommon($element) {
    $htmlBody = '';

    $htmlBody .= '
            <table style="width: 98%;">
                   <tr  style="line-height: 25px; ">
                        <td style="width: 33%; text-align:left;">
                       <ul><li style="list-style: disc;font-weight: bold;"> ' . sympolErrorResolve($element->show_name) . '  </li>  </ul> </td>';

###################### TD
    $htmlBody .= ' <td style="width: 3%; "> :   ';
    $htmlBody .= ' </td>';
###################### TD
    $htmlBody .= '      <td style="width: 25%; "> ';

    if ($element->content->element_text_low == 1 || $element->content->element_text_high == 1) {
        $htmlBody .= '    <span style="background-color: #E5E5E5;" > ';
    } else {
        $htmlBody .= '   <span> ';
    }

    $htmlBody .= $element->content->element_select_text . ' &nbsp;  &nbsp;    ' . $element->content->element_text;

    $htmlBody .= '   </span> ';

    $htmlBody .= ' </td>';
###################### TD
    $htmlBody .= ' <td style="width: 10%; ">  ';
    $htmlBody .= $element->content->element_text_unit;
    $htmlBody .= ' </td>';
###################### TD
    $htmlBody .= ' <td style="width: 5%; ">  ';

    if ($element->content->element_text_low == 1) {
        $htmlBody .= ' L ';
    } elseif ($element->content->element_text_high == 1) {
        $htmlBody .= ' H ';
    }

    $htmlBody .= ' </td>';

###################### TD
    $htmlBody .= ' <td>  ';

    if ($element->content->element_text_range_txt != Null || $element->content->element_text_range_txt != '') {
        $htmlBody .= sympolErrorResolve($element->content->element_text_range_txt);
    }

    $htmlBody .= ' </td>';
######################
    $htmlBody .= ' </tr>
        </table>';

    return $htmlBody;
}

##############################  esr  Pdf Prepare ######################################

function esrHtml($esr, $catName, $invname) {


    $htmlBody = '';

    $htmlBody .= testHead($catName, $invname);

    $htmlBody .= esrCommon($esr, 'hour1', 'First Hour');
    $htmlBody .= esrCommon($esr, 'hour2', 'Second Hour');

    $htmlBody .= commentsPrint($esr['comment']);
    #########################################################

    return $htmlBody;
}

function esrCommon($test, $element, $elementName, $element2 = '', $element2Sep = '&nbsp; ') {
    $htmlBody = '';
    if ($test[$element] != Null && $test[$element] != '') {
        $htmlBody .= '
            <table style="width: 98%;">
                   <tr  style="line-height: 25px; ">
                        <td style="width: 30%; text-align:left;">
                       <ul><li style="list-style: disc;  font-weight: bold ;"> ' . $elementName . '  </li>  </ul> </td>';

###################### TD
        $htmlBody .= ' <td style="width: 3%; "> :   ';
        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= '      <td style="width: 25%; "> ';

        if ($test[$element . '_low'] == 1 || $test[$element . '_high'] == 1) {
            $htmlBody .= '    <span style="background-color: #E5E5E5;" > ';
        } else {
            $htmlBody .= '   <span> ';
        }

        $htmlBody .= sympolErrorResolve($test[$element . '_value']);

        if ($element2 != '') {
            $htmlBody .= $element2Sep . ' ' . sympolErrorResolve($test[$element2 . '_value']);
        }



        $htmlBody .= '   </span> ';

        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= ' <td style="width: 11%; ">  ';
        $htmlBody .= $test[$element . '_invest_units'];
        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= ' <td style="width: 6%; ">  ';

        if ($test[$element . '_low'] == 1) {
            $htmlBody .= ' L ';
        } elseif ($test[$element . '_high'] == 1) {
            $htmlBody .= ' H ';
        }

        $htmlBody .= ' </td>';

###################### TD
        $htmlBody .= ' <td style="width: 25%; ">  ';

        if ($test[$element . '_range_txt'] != Null || $test[$element . '_range_txt'] != '') {
            $htmlBody .= sympolErrorResolve($test[$element . '_range_txt']);
        }

        $htmlBody .= ' </td>';
######################
        $htmlBody .= ' </tr>
        </table>';
    }

    return $htmlBody;
}

##############################  Urine Pdf Prepare ######################################

function urineHtml($urine, $catName, $invname) {

    $htmlBody = '';

    $dashArray = array("pus", "pbcs");
    $spaceArray = array("casts", "crystal", "amorphous", "bacteria");

    $htmlBody .= testHead($catName, $invname);

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

    $htmlBody .= testSubHead('Physical Examination');
    $htmlBody .= urinePhysical($urine, $dashArray, $spaceArray);

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

    $htmlBody .= testSubHead('Chemical Examination');
    $htmlBody .= urineChemical($urine, $dashArray, $spaceArray);

    #########################################################
    $htmlBody .= testSubHead('Microscopic Examination');
    $htmlBody .= urineMicroscopic($urine, $dashArray, $spaceArray);

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

    $htmlBody .= commentsPrint($urine['comment']);
#########################################################

    return $htmlBody;
}

function urinePhysical($urine, $dashArray, $spaceArray) {
    $htmlBody = '';

    $elements = array("Volume" => "volume", "Color" => "color", "Odor" => "odor"
        , "Aspect" => "aspect", "Deposit" => "deposit");

    $htmlBody .= urineElementsDraw($elements, $urine, $dashArray, $spaceArray);

    return $htmlBody;
}

function urineChemical($urine, $dashArray, $spaceArray) {
    $htmlBody = '';

    $elements = array("Reaction" => "reaction", "Protein" => "protein", "Sugar" => "sugar", "Acetone" => "acetone"
        , "Nitrite" => "nitrite", "Specific Gravity" => "gravity", "Bilirubin" => "bilirubin", "Urobilinigen" => "urobilinigen"
        , "Leucocytes" => "leucocytes", "Blood" => "blood");

    $htmlBody .= urineElementsDraw($elements, $urine, $dashArray, $spaceArray);

    return $htmlBody;
}

function urineMicroscopic($urine, $dashArray, $spaceArray) {
    $htmlBody = '';

    $elements = array("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"
    );

    $htmlBody .= urineElementsDraw($elements, $urine, $dashArray, $spaceArray);

    return $htmlBody;
}

function urineElementsDraw($elements, $test, $dashArray, $spaceArray) {
    $htmlBody = '';

    foreach ($elements as $showName => $dbName) {
        $htmlBody .= urineCommon($test, $dbName, $showName, $dashArray, $spaceArray);
    }

    return $htmlBody;
}

## $dashArray =  elements that has another value will print separated by -
### example  => pus - pus2
########
## $spaceArray =  elements that has another value will print separated by  free space
### example  => pus    pus2

function urineCommon($test, $element, $elementName, $dashArray, $spaceArray) {
    $htmlBody = '';
    if ($test[$element] != Null && $test[$element] != '') {
        $htmlBody .= '
            <table style="width: 98%;">
                   <tr  style="line-height: 20px; ">
                        <td style="width: 30%; text-align:left;">
                        &nbsp;  &nbsp;  &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp;
                        ' . $elementName . '     </td>';

###################### TD
        $htmlBody .= ' <td style="width: 3%; "> :   ';
        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= '      <td style="width: 23%; "> ';

        if ($test[$element . '_low'] == 1 || $test[$element . '_high'] == 1) {
            $htmlBody .= '    <span style="background-color: #E5E5E5;" > ';
        } else {
            $htmlBody .= '   <span> ';
        }

        if (in_array($element, $dashArray)) {
            $htmlBody .= sympolErrorResolve($test[$element]) . ' - ' . sympolErrorResolve($test[$element . '2']);
        }
        ###
        else if (in_array($element, $spaceArray)) {
            $htmlBody .= $test[$element];
            if ($test[$element . '2'] != Null && $test[$element . '2'] != '') {
                $htmlBody .= ' ' . sympolErrorResolve($test[$element . '2']);
            }
            if ($urine[$element . '3'] != Null && $urine[$element . '3'] != '') {
                $htmlBody .= ' ' . sympolErrorResolve($test[$element . '3']);
            }
        }
        ###
        else {
            $htmlBody .= sympolErrorResolve($test[$element]);
        }



        $htmlBody .= '   </span> ';

        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= ' <td style="width: 12%; ">  ';
        $htmlBody .= $test[$element . '_invest_units'];
        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= ' <td style="width: 6%; ">  ';

        if ($test[$element . '_low'] == 1) {
            $htmlBody .= ' L ';
        } elseif ($test[$element . '_high'] == 1) {
            $htmlBody .= ' H ';
        }

        $htmlBody .= ' </td>';

###################### TD
        $htmlBody .= ' <td style="width: 25%; ">  ';

        if ($test[$element . '_range_txt'] != Null || $test[$element . '_range_txt'] != '') {
            $htmlBody .= sympolErrorResolve($test[$element . '_range_txt']);
        }

        $htmlBody .= ' </td>';
######################
        $htmlBody .= ' </tr>
        </table>';
    }

    return $htmlBody;
}

##############################  Stool Pdf Prepare ######################################

function stoolHtml($stool, $catName, $invname) {
    $htmlBody = '';

    $dashArray = array("wbc", "rbc");
    $spaceArray = array("trophozoite", "cysts", "ova", "larva", "prog", "flagellates", "undigested", "parasitology");

    $htmlBody .= testHead($catName, $invname);

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

    $htmlBody .= testSubHead('Physical Examination');
    $htmlBody .= stoolPhysical($stool, $dashArray, $spaceArray);

    #########################################################
    $htmlBody .= testSubHead('Microscopic Examination');
    $htmlBody .= stoolMicroscopic($stool, $dashArray, $spaceArray);

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

    $htmlBody .= commentsPrint($stool['comment']);
#########################################################
    return $htmlBody;
}

function stoolPhysical($stool, $dashArray, $spaceArray) {
    $htmlBody = '';

    $elements = array("Color" => "color", "Reaction" => "reaction", "Odor" => "odor"
        , "Mucus" => "mucus", "Consistency" => "consistency", "Food Particles" => "food", "Blood" => "blood");

    $htmlBody .= urineElementsDraw($elements, $stool, $dashArray, $spaceArray);

    return $htmlBody;
}

function stoolMicroscopic($stool, $dashArray, $spaceArray) {
    $htmlBody = '';

    $elements = array("WBCs" => "wbc", "RBCs" => "rbc", "Trophozoite" => "trophozoite"
        , "Cysts" => "cysts", "Ova" => "ova", "Larva" => "larva", "Proglottids" => "prog", "Flagellates" => "flagellates"
        , "Ciliate" => "ciliate", "Undigested Food" => "undigested", "Parasitology Artifacts" => "parasitology"
    );

    $htmlBody .= urineElementsDraw($elements, $stool, $dashArray, $spaceArray);

    return $htmlBody;
}

##############################  culture  Pdf Prepare ######################################

function cultureHtml($culture, $catName, $invname) {
    $htmlBody = '';

    $htmlBody .= testHead($catName, $invname);

    $htmlBody .= testSubHead('Culture');

    $elements = array("Sample" => "sample_value", "Organism A" => "organism_a_value"
        , "Organism B" => "organism_b_value", "Organism C" => "organism_c_value"
        , "Culture Condition" => "condition_value", "Colony Count " => "colony_count_value");

    $htmlBody .= cultureElementsDraw($elements, $culture);

    $htmlBody .= testSubHead('Sensitivity');

    $htmlBody .= cultureElementsDraw2($culture);

    $htmlBody .= commentsPrint($culture['comment']);
    #########################################################

    return $htmlBody;
}

function cultureElementsDraw($elements, $blood) {
    $htmlBody = '';

    foreach ($elements as $showName => $dbName) {
        $htmlBody .= cultureCommon($blood, $dbName, $showName);
    }

    return $htmlBody;
}

function cultureCommon($test, $element, $elementName) {
    $htmlBody = '';
    if ($test[$element] != Null && $test[$element] != '') {
        $htmlBody .= '
            <table style="width: 98%;">
                   <tr  style="line-height: 25px; ">
                        <td style="width: 30%; text-align:left;">
                         &nbsp;  &nbsp;  &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp;   ' . $elementName . '   </td>';

###################### TD
        $htmlBody .= ' <td style="width: 3%; "> :  </td>';
###################### TD
        $htmlBody .= '      <td style="width: 42%; "> ';

        $htmlBody .= '   <span> ';
        $htmlBody .= sympolErrorResolve($test[$element]);
        $htmlBody .= '   </span> ';

        $htmlBody .= ' </td>';

###################### TD
        $htmlBody .= ' <td style="width: 25%; ">  </td>';
######################
        $htmlBody .= ' </tr>
        </table>';
    }

    return $htmlBody;
}

function cultureElementsDraw2($culture) {
    $htmlBody = '';
    if (count($culture['investigationresults_culture_hs']) > 0 || count($culture['investigationresults_culture_ls']) > 0 ||
            count($culture['investigationresults_culture_ms']) > 0 || count($culture['investigationresults_culture_rs']) > 0) {
        $htmlBody .= '
            <table style="width: 98%;">  <tr  style="line-height: 25px; "> ';

        $htmlBody .= '   <td style="width: 50%;"> </td>';
        $htmlBody .= '   <td style="width: 25%;  font-weight: bold ;"> Sensitive </td>';
        $htmlBody .= '   <td style="width: 25%;  font-weight: bold ;"> Commercial Name </td>';

        $htmlBody .= ' </tr></table>';

        $elements = array("investigationresults_culture_hs" => "Highly"
            , "investigationresults_culture_ms" => "Moderate"
            , "investigationresults_culture_ls" => "Low"
            , "investigationresults_culture_rs" => "Resistant");

        foreach ($elements as $element => $rateText) {
            if (count($culture[$element]) > 0) {
                $sensitivityCat = $rateText . ' ' . $culture['sensitivity_cat_value'];
                $htmlBody .= cultureCommon2($culture[$element], $sensitivityCat);
            }
        }
    }

    return $htmlBody;
}

function cultureCommon2($sensitivityArray, $sensitivityCat) {
    $htmlBody = '';

    $htmlBody .= '
            <table style="width: 98%;">  <tr  style="line-height: 25px; "> ';

    $htmlBody .= '   <td style="width: 53%;font-weight: bold ;">   &nbsp;  &nbsp;  &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp;    ' . $sensitivityCat . '  For  </td>';
    $htmlBody .= '   <td style="width: 25%;  font-weight: bold ;">  </td>';
    $htmlBody .= '   <td style="width: 22%;  font-weight: bold ;">   </td>';

    $htmlBody .= ' </tr></table>';

    $i = 1;
    foreach ($sensitivityArray as $sensitive) {

        $htmlBody .= '
            <table style="width: 98%;">  <tr  style="line-height: 25px; "> ';

        $htmlBody .= '   <td style="width: 53%;">  &nbsp;  &nbsp;  &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                  &nbsp; &nbsp;   ' . $i . '  -   ' . $sensitive['scientific_name'] . '  </td>';
        $htmlBody .= '   <td style="width: 25%;">  ' . $sensitive['sensitivity'] . ' </td>';
        $htmlBody .= '   <td style="width: 22%;">   </td>';

        $htmlBody .= ' </tr></table>';

        $i++;
    }

//    $htmlBody .= '
//            <table style="width: 98%;">
//                   <tr  style="line-height: 25px; ">
//                        <td style="width: 30%; text-align:left;">
//                        &nbsp;  &nbsp;  &nbsp;  &nbsp; &nbsp; &nbsp; &nbsp;   ' . $elementName . '   </td>';
//
//###################### TD
//    $htmlBody .= ' <td style="width: 3%; "> :  </td>';
//###################### TD
//    $htmlBody .= '      <td style="width: 42%; "> ';
//
//    $htmlBody .= '   <span> ';
//    $htmlBody .= $culture[$element];
//    $htmlBody .= '   </span> ';
//
//    $htmlBody .= ' </td>';
//
//###################### TD
//    $htmlBody .= ' <td style="width: 25%; ">  </td>';
//######################
//    $htmlBody .= ' </tr>
//        </table>';


    return $htmlBody;
}

##############################  blood Pdf Prepare ######################################

function bloodHtml($blood, $catName, $invname) {
    $htmlBody = '';

    $htmlBody .= testHead($catName, $invname);

    $elements = array("Hgb" => "hgb", "RBC" => "rbc", "Hct" => "hct", "Hgb %" => "hgbpercent"
        , "MCV" => "mcv_calc", "MCH" => "mch_calc", "MCHC" => "mchc_calc", "RDW" => "rdw"
        , "Plt" => "plt", "WBC" => "wbc", "Mentzer Index %" => "mindex");

    $htmlBody .= bloodElementsDraw($elements, $blood);

    $elements = array("Neutrophil" => "neutrophil", "Lymphocytes" => "lymphocytes"
        , "Monocytes" => "monocytes", "Eosinophils" => "eosinophils", "Basophils" => "basophils");

    $htmlBody .= bloodElementsDraw2($elements, $blood);

    $htmlBody .= commentsPrint($blood['comment']);

    return $htmlBody;
}

function bloodElementsDraw2($elements, $blood) {
    $htmlBody = '';

    $htmlBody .= '
            <table style="width: 98%;">
                   <tr  style="line-height: 25px; ">
                        <td  style="width: 30%;font-weight: bold ; "> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Differential </td>
                       <td  style="width: 35%;text-align:left;font-weight: bold ;" colspan="3">   &nbsp; &nbsp; Relative Counts % </td>
                       <td  style="text-align:left;font-weight: bold ;" colspan="3"> Absolute Counts k/ul  </td>
                    </tr>';

    $htmlBody .= '  </table>';

    $htmlBody .= '
            <table style="width: 98%;"> ';

    foreach ($elements as $showName => $dbName) {
        $htmlBody .= bloodCommon2($blood, $dbName, $showName);
    }

    $htmlBody .= '  </table>';

    return $htmlBody;
}

function bloodCommon2($blood, $element, $elementName) {
    $htmlBody = '';

    $htmlBody .= '
                   <tr  style="line-height: 23px; ">
                   <td style="width: 3%; "></td>
                        <td style="width: 27%; text-align:left;">
                        <ul>
                        <li style="list-style: disc;">  ' . $elementName . '     </li>
                    </ul>
                    </td>';
    ###################### TD
    $htmlBody .= ' <td style="width: 3%; "> :   ';
    $htmlBody .= ' </td>';

###################### TD
    $htmlBody .= '      <td style="width: 9%; "> ';

    if ($blood[$element . '_r_low'] == 1 || $blood[$element . '_r_high'] == 1) {
        $htmlBody .= '    <span style="background-color: #E5E5E5;" > ';
    } else {
        $htmlBody .= '   <span> ';
    }

    $htmlBody .= ' ' . sympolErrorResolve($blood[$element . '_r']);

    $htmlBody .= '   </span> ';
    $htmlBody .= ' </td>';

###################### TD
    $htmlBody .= ' <td style="width: 5%; ">  ';

    if ($blood[$element . '_r_low'] == 1) {
        $htmlBody .= ' L ';
    } elseif ($blood[$element . '_r_high'] == 1) {
        $htmlBody .= ' H ';
    }

    $htmlBody .= ' </td>';

###################### TD
    $htmlBody .= ' <td style="width: 17%; ">  ';

    if ($blood[$element . '_r_range_txt'] != Null || $blood[$element . '_r_range_txt'] != '') {
        $htmlBody .= ' ' . sympolErrorResolve($blood[$element . '_r_range_txt']);
    }

    $htmlBody .= ' </td>';
############################################
#
###################### TD
    $htmlBody .= '      <td style="width: 10%; "> ';

    if ($blood[$element . '_abs_low'] == 1 || $blood[$element . '_abs_high'] == 1) {
        $htmlBody .= '    <span style="background-color: #E5E5E5;" > ';
    } else {
        $htmlBody .= '   <span> ';
    }

    $htmlBody .= ' ' . sympolErrorResolve($blood[$element . '_abs']);

    $htmlBody .= '   </span> ';
    $htmlBody .= ' </td>';

###################### TD
    $htmlBody .= ' <td style="width:5%; ">  ';

    if ($blood[$element . '_abs_low'] == 1) {
        $htmlBody .= ' L ';
    } elseif ($blood[$element . '_abs_high'] == 1) {
        $htmlBody .= ' H ';
    }

    $htmlBody .= ' </td>';

###################### TD
    $htmlBody .= ' <td style="width: 21%; ">  ';

    if ($blood[$element . '_abs_range_txt'] != Null || $blood[$element . '_abs_range_txt'] != '') {
        $htmlBody .= ' ' . sympolErrorResolve($blood[$element . '_abs_range_txt']);
    }

    $htmlBody .= ' </td>';
############################################
    ############################################
    $htmlBody .= ' </tr> ';

    return $htmlBody;
}

function bloodElementsDraw($elements, $blood) {
    $htmlBody = '';

    foreach ($elements as $showName => $dbName) {
        $htmlBody .= bloodCommon($blood, $dbName, $showName);
    }

    return $htmlBody;
}

function bloodCommon($test, $element, $elementName) {
    $htmlBody = '';
    if ($test[$element] != Null && $test[$element] != '') {
        $htmlBody .= '
            <table style="width: 98%;">
                   <tr  style="line-height: 25px; ">
                        <td style="width: 33%; text-align:left;">
                       <ul><li style="list-style: disc;"> ' . $elementName . '  </li>  </ul> </td>';

###################### TD
        $htmlBody .= ' <td style="width: 3%; "> :   ';
        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= '      <td style="width: 23%; "> ';

        if ($test[$element . '_low'] == 1 || $test[$element . '_high'] == 1) {
            $htmlBody .= '    <span style="background-color: #E5E5E5;" > ';
        } else {
            $htmlBody .= '   <span> ';
        }

        if (in_array($element, $dashArray)) {
            $htmlBody .= sympolErrorResolve($test[$element]) . ' - ' . sympolErrorResolve($test[$element . '2']);
        }
        ###
        else if (in_array($element, $spaceArray)) {
            $htmlBody .= $test[$element];
            if ($test[$element . '2'] != Null && $test[$element . '2'] != '') {
                $htmlBody .= ' ' . sympolErrorResolve($test[$element . '2']);
            }
            if ($test[$element . '3'] != Null && $test[$element . '3'] != '') {
                $htmlBody .= ' ' . sympolErrorResolve($test[$element . '3']);
            }
        }
        ###
        else {
            $htmlBody .= ' ' . sympolErrorResolve($test[$element]);
        }



        $htmlBody .= '   </span> ';

        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= ' <td style="width: 12%; ">  ';
        $htmlBody .= $test[$element . '_invest_units'];
        $htmlBody .= ' </td>';
###################### TD
        $htmlBody .= ' <td style="width: 4%; ">  ';

        if ($test[$element . '_low'] == 1) {
            $htmlBody .= ' L ';
        } elseif ($test[$element . '_high'] == 1) {
            $htmlBody .= ' H ';
        }

        $htmlBody .= ' </td>';

###################### TD
        $htmlBody .= ' <td style="width: 25%; ">  ';

        if ($test[$element . '_range_txt'] != Null || $test[$element . '_range_txt'] != '') {
            $htmlBody .= sympolErrorResolve($test[$element . '_range_txt']);
        }

        $htmlBody .= ' </td>';
######################
        $htmlBody .= ' </tr>
        </table>';
    }

    return $htmlBody;
}

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

//function testElementsDraw($elements, $test, $dashArray, $spaceArray) {
//    $htmlBody = '';
//
//    foreach ($elements as $showName => $dbName) {
//        $htmlBody .= otherCommon($test, $dbName, $showName, $dashArray, $spaceArray);
//    }
//
//    return $htmlBody;
//}
#############################################################################################

function investsForPrint($invResIds, $gender, $age, $ageUnit, $smarty, $source) {
    $smarty->assign('source', $source);
    $notUrine = 0;
    $invResults = array();

    foreach ($invResIds as $invResId) {
        $in = R::load('investigationresults', $invResId);

        $obj = R::load('invests', $in->investid);

        $cat = R::load('investcats', $obj->investcatid);
        $in->invname = $obj->name;
        $in->special_inv_type = $obj->special_inv_type;
        $in->invests = $obj;
        switch ($obj->special_inv_type) {

## urine
            case 2:
                $urine_count = R::count('investigationresults_urine', 'investigationresults_id = ?', [$in->id]);
                if ($urine_count < 1) {
                    $urine = R::xdispense('investigationresults_urine');
                    $urine->investigationresults_id = $in->id;
                    r::store($urine);
                }
                $in->urine = printUrine($in, $gender, $age, $ageUnit, $smarty);

                $smarty->assign('catName', $cat->name);
                $smarty->assign('urinePrint', 1);
                $smarty->assign('inv', $in);
                $smarty->display('lab/print/print_head.html');
                $smarty->display('lab/print/print_urine.html');
                $smarty->display('lab/print/print_footer.html');

                if ($source == 5) {
                    $smarty->display('lab/print/line.html');
                }

                break;

## stool
            case 3:
                $stool_count = R::count('investigationresults_stool', 'investigationresults_id = ?', [$in->id]);
                if ($stool_count < 1) {
                    $stool = R::xdispense('investigationresults_stool');
                    $stool->investigationresults_id = $in->id;
                    r::store($stool);
                }
                $in->stool = printStool($in, $gender, $age, $ageUnit, $smarty);
                $notUrine++;
                break;

## blood picture
            case 1:
                $blood_count = R::count('investigationresults_blood', 'investigationresults_id = ?', [$in->id]);
                if ($blood_count < 1) {
                    $blood = R::xdispense('investigationresults_blood');
                    $blood->investigationresults_id = $in->id;
                    r::store($blood);
                }
                $in->blood = printBlood($in, $gender, $age, $ageUnit, $smarty);
                $notUrine++;
                break;

## Culture
            case 4:

                $culture_count = R::count('investigationresults_culture', 'investigationresults_id = ?', [$in->id]);
                if ($culture_count < 1) {
                    $culture = R::xdispense('investigationresults_culture');
                    $culture->investigationresults_id = $in->id;
                    r::store($culture);
                }

                $in->culture = printCulture($in, $smarty);
                $notUrine++;
                break;

## ESR
            case 5:
                $esr_count = R::count('investigationresults_esr', 'investigationresults_id = ?', [$in->id]);
                if ($esr_count < 1) {
                    $esr = R::xdispense('investigationresults_esr');
                    $esr->investigationresults_id = $in->id;
                    r::store($esr);
                }

                $in->esr = loadEsrRanges($in, $gender, $age, $ageUnit, $smarty);
                $notUrine++;
                break;

## Cross Matching
            case 6:
                $cross_count = R::count('investigationresults_cross', 'investigationresults_id = ?', [$in->id]);
                if ($cross_count < 1) {
                    $cross = R::xdispense('investigationresults_cross');
                    $cross->investigationresults_id = $in->id;
                    r::store($cross);
                }

                $in->cross = printCross($in, $smarty);
                $notUrine++;
                break;

## Fluid
            case 7:

                $notUrine++;
                break;

## Custom
            case 11:
                $in->elements = customInvDetails($in, $gender, $age, $ageUnit, $smarty, 1);
                $notUrine++;
                break;

## Clothing time
            case 8:
                $clothing_count = R::count('investigationresults_times', 'investigationresults_id = ?', [$in->id]);
                if ($clothing_count < 1) {
                    $clothing = R::xdispense('investigationresults_times');
                    $clothing->investigationresults_id = $in->id;
                    r::store($clothing);
                }

                $in->clothing = loadClothingDetails($in, $gender, $age, $ageUnit, $smarty, 1);
                $notUrine++;
                break;

## PT + APTT
            case 9:
## PT
            case 12:
##  APTT
            case 13:
                $pt_count = R::count('investigationresults_pt', 'investigationresults_id = ?', [$in->id]);
                if ($pt_count < 1) {
                    $pt = R::xdispense('investigationresults_pt');
                    $pt->investigationresults_id = $in->id;
                    r::store($pt);
                }

                $in->pt = loadPtDetails($in, $gender, $age, $ageUnit, $smarty, 1);
                $notUrine++;
                break;

## ABO/RH
            case 10:
                $aborh_count = R::count('investigationresults_aborh', 'investigationresults_id = ?', [$in->id]);
                if ($aborh_count < 1) {
                    $aborh = R::xdispense('investigationresults_aborh');
                    $aborh->investigationresults_id = $in->id;
                    r::store($aborh);
                }

                $in->aborh = printAborh($in, $smarty);
                $notUrine++;
                break;

            default :
                $in = printCommon($in, $smarty);
                $notUrine++;
                break;
        }



        if ($obj->special_inv_type != 2) {
            $invResults[$cat->name][] = $in;
        }
    }


    $smarty->assign('result', $invResults);
    if ($notUrine > 0) {
        $smarty->display('lab/print/print_head.html');
        $smarty->display('lab/print/print.html');
        $smarty->display('lab/print/print_footer.html');
    }
}

function printUrine($in, $gender, $age, $ageUnit, $smarty) {

    $urineSql = urineSql();

    $urine = R::getRow($urineSql . ' where investigationresults_urine.investigationresults_id = ? ', [$in->id]);

    $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"
    );
    foreach ($elements as $showName => $dbName) {

        $range = Null;

        $hName = $dbName . '_high';
        $lName = $dbName . '_low';

        $urine[$hName] = 0;
        $urine[$lName] = 0;

        $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and agefrom <= ?
                    and ageto >= ?  and investid = ?  and age_units = ?   and invest_child = ?
                    ', [$gender, '', -1, $age, $age, $in->investid, $ageUnit, $showName]);

        if (!(count($range) > 0)) {

            $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?   || gender = ?)  and ( agefrom = ?  || agefrom = ?  )
                    and ( ageto = ?  || ageto = ?  )   and investid = ?   and invest_child = ?
                    ', [$gender, '', -1, Null, '', Null, '', $in->investid, $showName]);
        }

        if (count($range) > 0) {

            $n1 = $dbName . '_range_txt';
            $n2 = $dbName . '_range_low';
            $n3 = $dbName . '_range_high';
            $n4 = $dbName . '_invest_units';

            $urine[$n1] = $range->range_txt;
            $urine[$n2] = $range->range_low;
            $urine[$n3] = $range->range_high;
            $urine[$n4] = $range->invest_units;

            if (is_numeric($range->range_low) && is_numeric($urine[$dbName]) && $urine[$dbName] < $range->range_low) {
                $urine[$lName] = 1;
            }

####
            elseif (is_numeric($range->range_high) && is_numeric($urine[$dbName]) && $urine[$dbName] > $range->range_high) {
                $urine[$hName] = 1;
            }
        }
    }

    return $urine;
}

function printStool($in, $gender, $age, $ageUnit, $smarty) {

    $stoolSql = stoolSql();

    $stool = R::getRow($stoolSql . ' where investigationresults_stool.investigationresults_id = ? ', [$in->id]);

    $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"
    );

    foreach ($elements as $showName => $dbName) {

        $range = Null;

        $hName = $dbName . '_high';
        $lName = $dbName . '_low';

        $stool[$hName] = 0;
        $stool[$lName] = 0;

        $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and agefrom <= ?
                    and ageto >= ?  and investid = ?  and age_units = ?   and invest_child = ?
                    ', [$gender, '', -1, $age, $age, $in->investid, $ageUnit, $showName]);

        if (!(count($range) > 0)) {

            $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?   || gender = ?)  and ( agefrom = ?  || agefrom = ?  )
                    and ( ageto = ?  || ageto = ?  )   and investid = ?   and invest_child = ?
                    ', [$gender, '', -1, Null, '', Null, '', $in->investid, $showName]);
        }

        if (count($range) > 0) {

            $n1 = $dbName . '_range_txt';
            $n2 = $dbName . '_range_low';
            $n3 = $dbName . '_range_high';
            $n4 = $dbName . '_invest_units';

            $stool->$n1 = $range->range_txt;
            $stool->$n2 = $range->range_low;
            $stool->$n3 = $range->range_high;
            $stool->$n4 = $range->invest_units;

            $stool[$n1] = $range->range_txt;
            $stool[$n2] = $range->range_low;
            $stool[$n3] = $range->range_high;
            $stool[$n4] = $range->invest_units;

            if (is_numeric($range->range_low) && is_numeric($stool[$dbName]) && $stool[$dbName] < $range->range_low) {
                $stool[$lName] = 1;
            }

####
            elseif (is_numeric($range->range_high) && is_numeric($stool[$dbName]) && $stool[$dbName] > $range->range_high) {
                $stool[$hName] = 1;
            }
        }
    }

    return $stool;
}

function printBlood($in, $gender, $age, $ageUnit, $smarty) {

    $blood = R::findOne('investigationresults_blood', 'investigationresults_id = ? ', [$in->id]);

    $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"
    );

    foreach ($elements as $showName => $dbName) {

        $range = Null;

        $hName = $dbName . '_high';
        $lName = $dbName . '_low';

        $blood->$hName = 0;
        $blood->$lName = 0;

        $rangeid = $dbName . '_rangeid';

        if ($blood->$rangeid && $blood->$rangeid > 0) {
            $range = R::load('inv_ranges', $blood->$rangeid);
        }


        if (!(count($range) > 0)) {
            $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and agefrom <= ?
                    and ageto >= ?  and investid = ?  and age_units = ?   and invest_child = ?
                    ', [$gender, '', -1, $age, $age, $in->investid, $ageUnit, $showName]);

            if (!(count($range) > 0)) {

                $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?   || gender = ?)  and ( agefrom = ?  || agefrom = ?  )
                    and ( ageto = ?  || ageto = ?  )   and investid = ?   and invest_child = ?
                    ', [$gender, '', -1, Null, '', Null, '', $in->investid, $showName]);
            }
        }

        if (count($range) > 0) {

            $range_txt = $dbName . '_range_txt';
            $n2 = $dbName . '_range_low';
            $n3 = $dbName . '_range_high';
            $n4 = $dbName . '_invest_units';
//
            $blood->$range_txt = $range->range_txt;
            $blood->$n2 = $range->range_low;
            $blood->$n3 = $range->range_high;
            $blood->$n4 = $range->invest_units;

            if (is_numeric($range->range_low) && is_numeric($blood->$dbName) && $blood->$dbName < $range->range_low) {
                $blood->$lName = 1;
            }

####
            elseif (is_numeric($range->range_high) && is_numeric($blood->$dbName) && $blood->$dbName > $range->range_high) {
                $blood->$hName = 1;
            }
        }
    }

    return $blood;
}

function printCulture($in, $smarty) {

    $culture = loadCultureDetails($in->id, $smarty, 1);

    return $culture;
}

function loadEsrRanges($in, $gender, $age, $ageUnit, $smarty) {

    $esrSql = esrSql();

    $esr = R::getRow($esrSql . ' where investigationresults_esr.investigationresults_id = ? ', [$in->id]);

    $elements = array("hour1", "hour2");

    foreach ($elements as $single) {
        $esr = elementRanges($in, $gender, $age, $ageUnit, $single, $esr, 'investigationresults_esr', $smarty);
    }

    return $esr;
}

function printCross($in, $smarty) {

    $cross = loadCrossDetails($in->id, $smarty, 1);

    return $cross;
}

function customInvDetails($in, $gender, $age, $ageUnit, $smarty, $print = 0) {
    $elements = R::findAll('invest_elements', 'investid = ?  and  deleted = ?  ', [$in->investid, 0]);
    foreach ($elements as $data) {
        $custom_count = R::count('investigationresults_custom', 'investigationresults_id = ?  and element_id = ? '
                        , [$in->id, $data->id]);
        if ($custom_count < 1) {
            $custom = R::xdispense('investigationresults_custom');
            $custom->investigationresults_id = $in->id;
            $custom->element_id = $data->id;
            r::store($custom);
        }

        $custom = R::findOne('investigationresults_custom', 'investigationresults_id = ?  and element_id = ? '
                        , [$in->id, $data->id]);
        if ($print == 1 && $custom->element_select > 0) {
            $obj = R::load('custom_select', $custom->element_select);
            $custom->element_select_text = $obj->name;
        }
        $data->content = $custom;
        $data = customElementRanges($in, $gender, $age, $ageUnit, $data->show_name, $data, 'investigationresults_custom');
    }

    return $elements;
}

function loadClothingDetails($in, $gender, $age, $ageUnit, $smarty, $print = 0) {

    $clothing = R::findOne('investigationresults_times', 'investigationresults_id = ? ', [$in->id]);

    $elements = array("Bleeding Time" => "bleeding", "Clothing Time" => "clothing");

    foreach ($elements as $showName => $dbName) {

        $range = Null;

        $hName = $dbName . '_high';
        $lName = $dbName . '_low';
        $rangestxt = $dbName . '_ranges';
        $rangeid = $dbName . '_rangeid';

        if ($clothing->$rangeid && $clothing->$rangeid > 0) {
            $range = R::load('inv_ranges', $clothing->$rangeid);
        }

        if (!(count($range) > 0)) {
            $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and agefrom <= ?
                    and ageto >= ?  and investid = ?  and age_units = ?   and invest_child = ?
                    ', [$gender, '', -1, $age, $age, $in->investid, $ageUnit, $showName]);

            if (count($range) > 0 && $clothing->$rangeid < 1 && $print == 0) {
                r::exec(' update investigationresults_times set  ' . $rangeid . ' = ' . $range->id . '  where id =  ' . $clothing->id);
            }

            if (!(count($range) > 0)) {

                $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?   || gender = ?)  and ( agefrom = ?  || agefrom = ?  )
                    and ( ageto = ?  || ageto = ?  )   and investid = ?   and invest_child = ?
                    ', [$gender, '', -1, Null, '', Null, '', $in->investid, $showName]);

                if (count($range) > 0 && $clothing->$rangeid < 1 && $print == 0) {
                    r::exec(' update investigationresults_times set  ' . $rangeid . ' = ' . $range->id . '  where id =  ' . $clothing->id);
                }
            }
        }

        $clothing->$hName = 0;
        $clothing->$lName = 0;

        if (count($range) > 0) {

            $clothing->$rangeid = $range->id;

            $range_txt = $dbName . '_range_txt';
            $clothing->$range_txt = $range->range_txt;

            if (is_numeric($range->range_low) && is_numeric($clothing->$dbName) && $clothing->$dbName < $range->range_low) {
                $clothing->$lName = 1;
            }

####
            elseif (is_numeric($range->range_high) && is_numeric($clothing->$dbName) && $clothing->$dbName > $range->range_high) {
                $clothing->$hName = 1;
            }
        }

        if ($print == 1) {
            $n2 = $dbName . '_range_low';
            $n3 = $dbName . '_range_high';
            $n4 = $dbName . '_invest_units';

            $clothing->$n2 = $range->range_low;
            $clothing->$n3 = $range->range_high;
            $clothing->$n4 = $range->invest_units;
        } else {
            $ranges = R::findAll('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and investid = ?  and invest_child = ?
                    ', [$gender, '', -1, $in->investid, $showName]);

            $clothing->$rangestxt = $ranges;
        }
    }

    return $clothing;
}

function loadPtDetails($in, $gender, $age, $ageUnit, $smarty, $print = 0) {

    $pt = R::findOne('investigationresults_pt', 'investigationresults_id = ? ', [$in->id]);

    $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");

    foreach ($elements as $showName => $dbName) {

        $range = Null;

        $hName = $dbName . '_high';
        $lName = $dbName . '_low';
        $rangestxt = $dbName . '_ranges';
        $rangeid = $dbName . '_rangeid';

        if ($pt->$rangeid && $pt->$rangeid > 0) {
            $range = R::load('inv_ranges', $pt->$rangeid);
        }

        if (!(count($range) > 0)) {
            $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and agefrom <= ?
                    and ageto >= ?  and investid = ?  and age_units = ?   and invest_child = ?
                    ', [$gender, '', -1, $age, $age, $in->investid, $ageUnit, $showName]);

            if (count($range) > 0 && $pt->$rangeid < 1 && $print == 0) {
                r::exec(' update investigationresults_pt set  ' . $rangeid . ' = ' . $range->id . '  where id =  ' . $pt->id);
            }

            if (!(count($range) > 0)) {

                $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?   || gender = ?)  and ( agefrom = ?  || agefrom = ?  )
                    and ( ageto = ?  || ageto = ?  )   and investid = ?   and invest_child = ?
                    ', [$gender, '', -1, Null, '', Null, '', $in->investid, $showName]);

                if (count($range) > 0 && $pt->$rangeid < 1 && $print == 0) {
                    r::exec(' update investigationresults_pt set  ' . $rangeid . ' = ' . $range->id . '  where id =  ' . $pt->id);
                }
            }
        }

        $pt->$hName = 0;
        $pt->$lName = 0;

        if (count($range) > 0) {

            $pt->$rangeid = $range->id;

            $range_txt = $dbName . '_range_txt';
            $pt->$range_txt = $range->range_txt;

            $n2 = $dbName . '_range_low';
            $n3 = $dbName . '_range_high';
            $n4 = $dbName . '_invest_units';

            $pt->$n2 = $range->range_low;
            $pt->$n3 = $range->range_high;
            $pt->$n4 = $range->invest_units;

            if (is_numeric($range->range_low) && is_numeric($pt->$dbName) && $pt->$dbName < $range->range_low) {
                $pt->$lName = 1;
            }

####
            elseif (is_numeric($range->range_high) && is_numeric($pt->$dbName) && $pt->$dbName > $range->range_high) {
                $pt->$hName = 1;
            }
        }

        if ($print == 0) {
            $ranges = R::findAll('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and investid = ?  and invest_child = ?
                    ', [$gender, '', -1, $in->investid, $showName]);

            $pt->$rangestxt = $ranges;
        }
    }

    return $pt;
}

function printAborh($in, $smarty) {

    $aborh = loadAborhDetails($in->id, $smarty, 1);

    return $aborh;
}

function printCommon($in, $smarty) {

    $in->high = 0;
    $in->low = 0;

    if ($in->rangeid > 0) {
        $range = R::load('inv_ranges', $in->rangeid);

        if (is_numeric($range->range_low) && is_numeric($in->investresult) && $in->investresult < $range->range_low) {
            $in->low = 1;
        } elseif (is_numeric($range->range_high) && is_numeric($in->investresult) && $in->investresult > $range->range_high) {
            $in->high = 1;
        }

        $in->range = $range;
    }

    return $in;
}

function urineSql() {

    $sql = ' select investigationresults_urine.id , investigationresults_urine.comment
             , investigationresults_urine.pbcs   , investigationresults_urine.pbcs2
              , investigationresults_urine.pus   , investigationresults_urine.pus2
                 ';

    $colmsSql = '';

    $joinSql = '';

    $tables = array("volume", "color", "odor", "ova", "bacteria", "mucus", "trophazite"
        , "blood", "leucocytes", "aspect", "deposit", "reaction"
        , "protein", "fungi", "artifacts", "crystal", "casts2", "casts", "epithelial"
        , "urobilinigen", "bilirubin", "gravity", "nitrite", "acetone", "sugar", "bacteria2"
        , "amorphous2", "amorphous", "crystal2"
    );

    foreach ($tables as $tableName) {
## selected colums
        $colmsSql .= '  , urine_' . $tableName . '.name as  ' . $tableName;

## join tables
        $joinSql .= ' left  join urine_' . $tableName . '  on   urine_' . $tableName . '.id  =  investigationresults_urine.' . $tableName;
    }

    $sql .= $colmsSql;
    $sql .= ' from investigationresults_urine ';
    $sql .= $joinSql;

    return $sql;
}

function stoolSql() {

    $sql = ' select investigationresults_stool.id , investigationresults_stool.comment
                 , investigationresults_stool.wbc   , investigationresults_stool.wbc2
                  , investigationresults_stool.rbc   , investigationresults_stool.rbc2
                ';

    $colmsSql = '';

    $joinSql = '';

    $tables = array("blood", "ciliate", "color", "consistency", "cysts", "flagellates"
        , "prog", "parasitology2", "parasitology", "ova2", "larva2", "cysts2"
        , "prog2", "reaction", "mucus", "flagellates2", "trophozoite",
        "trophozoite2", "trophozoite3", "undigested", "odor", "food", "undigested2"
        , "undigested3", "undigested4", "ova", "larva"
    );

    foreach ($tables as $tableName) {
## selected colums
        $colmsSql .= '  , stool_' . $tableName . '.name as  ' . $tableName;

## join tables
        $joinSql .= ' left  join stool_' . $tableName . '  on   stool_' . $tableName . '.id  =  investigationresults_stool.' . $tableName;
    }

    $sql .= $colmsSql;
    $sql .= ' from investigationresults_stool ';
    $sql .= $joinSql;

    return $sql;
}

function loadCultureDetails($investigationresults_id, $smarty, $print = 0) {

    $cultureSql = cultureSql($print);

    $culture = R::getRow($cultureSql . ' where investigationresults_culture.investigationresults_id = ? ', [$investigationresults_id]);

    $culture['investigationresults_culture_hs'] = cultureFor('investigationresults_culture_hs', $culture['id'], $smarty);
    $culture['investigationresults_culture_ls'] = cultureFor('investigationresults_culture_ls', $culture['id'], $smarty);
    $culture['investigationresults_culture_ms'] = cultureFor('investigationresults_culture_ms', $culture['id'], $smarty);
    $culture['investigationresults_culture_rs'] = cultureFor('investigationresults_culture_rs', $culture['id'], $smarty);

    if ($print == 0) {
        loadAllAbbr($culture['id'], $smarty);
    }

    return $culture;
}

function esrSql() {

    $sql = ' select investigationresults_esr.*    ';

    $colmsSql = '';

    $joinSql = '';

    $tables = array("hour1", "hour2");

    foreach ($tables as $tableName) {
## selected colums
        $colmsSql .= '  , esr_' . $tableName . '.name as  ' . $tableName . '_value';

## join tables
        $joinSql .= ' left  join esr_' . $tableName . '  on   esr_' . $tableName . '.id  =  investigationresults_esr.' . $tableName;
    }

    $sql .= $colmsSql;
    $sql .= ' from investigationresults_esr ';
    $sql .= $joinSql;

    return $sql;
}

function elementRanges($in, $gender, $age, $ageUnit, $element, $res_obj, $table, $smarty) {

    $rangeid = $element . '_rangeid';
    $rangestxt = $element . '_ranges';
    $rangeUnit = $element . '_unit';
    $high = $element . '_high';
    $low = $element . '_low';
    $range_txt = $element . '_range_txt';
    $value = $element . '_value';

    $n2 = $element . '_range_low';
    $n3 = $element . '_range_high';

    if ($res_obj[$rangeid] < 1) {
        $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and agefrom <= ?
                    and ageto >= ?  and investid = ?  and age_units = ?   and invest_child = ?
                    ', [$gender, '', -1, $age, $age, $in->investid, $ageUnit, $element]);

        if (count($range) > 0 && $res_obj[$rangeid] < 1) {
            r::exec(' update ' . $table . ' set  ' . $rangeid . ' = ' . $range->id . '  where id =  ' . $res_obj['id']);
            $res_obj[$rangeid] = $range->id;
        } else {


            $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and ( agefrom = ?  || agefrom = ?  )
                    and ( ageto = ?  || ageto = ?  )   and investid = ?   and invest_child = ?
                    ', [$gender, '', -1, Null, '', Null, '', $in->investid, $element]);

            if (count($range) > 0 && $res_obj[$rangeid] < 1) {
                r::exec(' update ' . $table . ' set  ' . $rangeid . ' = ' . $range->id . '  where id =  ' . $res_obj['id']);
                $res_obj[$rangeid] = $range->id;
            }
        }
    }


    if ($res_obj[$rangeid] > 0) {

//   $res_obj[$range] = '';
        $res_obj[$rangestxt] = '';
        $res_obj[$rangeUnit] = '';
        $res_obj[$range_txt] = '';
        $res_obj[$high] = 0;
        $res_obj[$low] = 0;

        $range = R::load('inv_ranges', $res_obj[$rangeid]);

        $res_obj[$rangeUnit] = $range->invest_units;
        $res_obj[$range_txt] = $range->range_txt;
        $res_obj[$n2] = $range->range_low;
        $res_obj[$n3] = $range->range_high;

        if (is_numeric($range->range_low) && is_numeric($res_obj[$value]) && $res_obj[$value] < $range->range_low) {
            $res_obj[$low] = 1;
        }

####
        elseif (is_numeric($range->range_high) && is_numeric($res_obj[$value]) && $res_obj[$value] > $range->range_high) {
            $res_obj[$high] = 1;
        }
    }




    $ranges = R::findAll('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and investid = ?  and invest_child = ?
                    ', [$gender, '', -1, $in->investid, $element]);

    $res_obj[$rangestxt] = $ranges;

    return $res_obj;
}

function loadCrossDetails($investigationresults_id, $smarty, $print = 0) {

    $crossSql = crossSql($print);
    $crossDonnerSql = crossDonnerSql($print);

    $cross = R::getRow($crossSql . ' where investigationresults_cross.investigationresults_id = ? ', [$investigationresults_id]);

    $donners = R::getAll($crossDonnerSql . ' where investigationresults_cross_donners.investigationresults_cross_id = ? ', [$cross['id']]);

    if (count($donners) < 1) {
        $donner = R::xdispense('investigationresults_cross_donners');
        $donner->investigationresults_cross_id = $cross['id'];
        r::store($donner);
    }


    $donners = R::getAll($crossDonnerSql . ' where investigationresults_cross_donners.investigationresults_cross_id = ? ', [$cross['id']]);

    $cross['donners'] = $donners;
    $cross['donnersItr'] = count($donners);

    return $cross;
}

function customElementRanges($in, $gender, $age, $ageUnit, $element, $res_obj, $table) {

    $rangeid = 'element_text_rangeid';
    $rangestxt = 'element_text_ranges';
    $rangeUnit = 'element_text_unit';
    $high = 'element_text_high';
    $low = 'element_text_low';
    $range_txt = 'element_text_range_txt';
    $value = 'element_text';

    $n2 = 'element_text_range_low';
    $n3 = 'element_text_range_high';

    if ($res_obj->content->$rangeid < 1) {
        $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and agefrom <= ?
                    and ageto >= ?  and investid = ?  and age_units = ?   and invest_child = ?
                    ', [$gender, '', -1, $age, $age, $in->investid, $ageUnit, $element]);

        if (count($range) > 0 && $res_obj->content->$rangeid < 1) {
            r::exec(' update ' . $table . ' set  ' . $rangeid . ' = ' . $range->id . '  where id =  ' . $res_obj->content->id);
            $res_obj->content->$rangeid = $range->id;
        } else {


            $range = R::findOne('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and ( agefrom = ?  || agefrom = ?  )
                    and ( ageto = ?  || ageto = ?  )   and investid = ?   and invest_child = ?
                    ', [$gender, '', -1, Null, '', Null, '', $in->investid, $element]);

            if (count($range) > 0 && $res_obj->content->$rangeid < 1) {
                r::exec(' update ' . $table . ' set  ' . $rangeid . ' = ' . $range->id . '  where id =  ' . $res_obj->content->id);
                $res_obj->content->$rangeid = $range->id;
            }
        }
    }


    if ($res_obj->content->$rangeid > 0) {

//     $res_obj->content->$range = '';
        $res_obj->content->$rangestxt = '';
        $res_obj->content->$rangeUnit = '';
        $res_obj->content->$range_txt = '';
        $res_obj->content->$high = 0;
        $res_obj->content->$low = 0;

        $range = R::load('inv_ranges', $res_obj->content->$rangeid);
//            print_r($range);

        $res_obj->content->$rangeUnit = $range->invest_units;
        $res_obj->content->$range_txt = $range->range_txt;
        $res_obj->content->$n2 = $range->range_low;
        $res_obj->content->$n3 = $range->range_high;

        if (is_numeric($range->range_low) && is_numeric($res_obj->content->$value) && $res_obj->content->$value < $range->range_low) {
            $res_obj->content->$low = 1;
        }

####
        elseif (is_numeric($range->range_high) && is_numeric($res_obj->content->$value) && $res_obj->content->$value > $range->range_high) {
            $res_obj->content->$high = 1;
        }
    }


    $ranges = R::findAll('inv_ranges', ' ( gender = ? || gender = ?  || gender = ? )  and investid = ?  and invest_child = ?
                    ', [$gender, '', -1, $in->investid, $element]);

    $res_obj->$rangestxt = $ranges;

    return $res_obj;
}

function loadAborhDetails($investigationresults_id, $smarty, $print = 0) {

    $aborhSql = aborhSql($print);

    $aborh = R::getRow($aborhSql . ' where investigationresults_aborh.investigationresults_id = ? ', [$investigationresults_id]);

    return $aborh;
}

function cultureSql($print) {

    $sql = ' select investigationresults_culture.*    ';

    $colmsSql = '';

    $joinSql = '';

    if ($print == 1) {

        $tables = array("sample", "organism_a", "organism_b", "organism_c"
            , "condition", "condition1", "colony_count", "sensitivity_cat");

        foreach ($tables as $tableName) {
## selected colums
            $colmsSql .= '  , culture_' . $tableName . '.name as  ' . $tableName . '_value';

## join tables
            $joinSql .= ' left  join culture_' . $tableName . '  on   culture_' . $tableName . '.id  =  investigationresults_culture.' . $tableName;
        }


        $sql .= $colmsSql;

        $sql .= ' from investigationresults_culture ';

        $sql .= $joinSql;
    } else {
        $sql .= ' from investigationresults_culture ';
    }

    return $sql;
}

function loadAllAbbr($culture_id, $smarty) {

    $s = ' select  antibiotic_sensitivity_id  from investigationresults_culture_hs where  deleted != 1   and
                  investigationresults_culture_id = ' . $culture_id;

    $s .= '  union  ';

    $s .= ' select  antibiotic_sensitivity_id  from investigationresults_culture_ls where   deleted != 1   and
                  investigationresults_culture_id = ' . $culture_id;

    $s .= '  union  ';

    $s .= ' select  antibiotic_sensitivity_id  from investigationresults_culture_ms where   deleted != 1   and
                  investigationresults_culture_id = ' . $culture_id;

    $s .= '  union  ';

    $s .= ' select  antibiotic_sensitivity_id  from investigationresults_culture_rs where   deleted != 1   and
                  investigationresults_culture_id = ' . $culture_id;

    if ($culture_id > 0) {
        $sql = 'select * from antibiotic_sensitivity where deleted != 1
                     and id not in ( ' . $s . ' )
                 order by abbr asc ';
    } else {
        $sql = 'select * from antibiotic_sensitivity where deleted != 1
                 order by id asc ';
    }

    $antibiotic_sensitivity = R::getAll($sql);

    $smarty->assign('antibiotic_sensitivity', $antibiotic_sensitivity);
    $smarty->assign('allAbrRslt', $antibiotic_sensitivity);
}

function crossSql($print) {

    $sql = ' select investigationresults_cross.*    ';

    $colmsSql = '';

    $joinSql = '';

    if ($print == 1) {

        $tables = array("abo", "rh");

        foreach ($tables as $tableName) {
## selected colums
            $colmsSql .= '  , cross_' . $tableName . '.name as  ' . $tableName . '_value';

## join tables
            $joinSql .= ' left  join cross_' . $tableName . '  on   cross_' . $tableName . '.id  =  investigationresults_cross.' . $tableName;
        }


        $sql .= $colmsSql;

        $sql .= ' from investigationresults_cross ';

        $sql .= $joinSql;
    } else {
        $sql .= ' from investigationresults_cross ';
    }

    return $sql;
}

function aborhSql($print) {

    $sql = ' select investigationresults_aborh.*    ';

    $colmsSql = '';

    $joinSql = '';

    if ($print == 1) {

        $tables = array("abo", "rh");

        foreach ($tables as $tableName) {
## selected colums
            $colmsSql .= '  , cross_' . $tableName . '.name as  ' . $tableName . '_value';

## join tables
            $joinSql .= ' left  join cross_' . $tableName . '  on   cross_' . $tableName . '.id  =  investigationresults_aborh.' . $tableName;
        }


        $sql .= $colmsSql;

        $sql .= ' from investigationresults_aborh ';

        $sql .= $joinSql;
    } else {
        $sql .= ' from investigationresults_aborh ';
    }

    return $sql;
}

function crossDonnerSql($print) {

    $sql = ' select investigationresults_cross_donners.*    ';

    $colmsSql = '';

    $joinSql = '';

    if ($print == 1) {

        $tables = array("abo", "rh", "compatibility", "hcv", "hbsag", "hv");

        foreach ($tables as $tableName) {
## selected colums
            $colmsSql .= '  , cross_' . $tableName . '.name as  ' . $tableName . '_value';

## join tables
            $joinSql .= ' left  join cross_' . $tableName . '  on   cross_' . $tableName . '.id  =  investigationresults_cross_donners.' . $tableName;
        }


        $sql .= $colmsSql;

        $sql .= ' from investigationresults_cross_donners ';

        $sql .= $joinSql;
    } else {
        $sql .= ' from investigationresults_cross_donners ';
    }

    return $sql;
}

function cultureFor($tableName, $culture_id, $smarty) {
    $sql = ' select  ' . $tableName . '.id  ,   ' . $tableName . '.sensitive    ';
    $sql .= '  ,   antibiotic_sensitivity.abbr ,   antibiotic_sensitivity.scientific_name ,   antibiotic_sensitivity.sensitivity   ';

    $sql .= '  from ' . $tableName . '   ';

    $sql .= '   join antibiotic_sensitivity  on   ' . $tableName . '.antibiotic_sensitivity_id  =  antibiotic_sensitivity.id';

    $sql .= '  where ' . $tableName . '.investigationresults_culture_id = ' . $culture_id . ' and  ' . $tableName . '.deleted != 1   ';

    $result = R::getAll($sql);

    $smarty->assign($tableName, $result);
    $smarty->assign('tabRslt', $result);
    $smarty->assign($tableName . 'Count', count($result));
    $smarty->assign('resTableName', $tableName);

    return $result;
}

############################## Summary Case ################################

function caseSummary($patient_id, $followupId, $smarty) {
    try {

        $programesetting = R::findOne('programesetting');
        $smarty->assign('programesetting', $programesetting);

        personalHistory($patient_id, $smarty);
        menstrualHistory($patient_id, $smarty);
        obstetricHistory($patient_id, $smarty);
        pastHistory($patient_id, $smarty);
        familyHistory($patient_id, $smarty);
        pastHx($patient_id, $smarty);
        sexualHistory($patient_id, $smarty);
        investigation($patient_id, $smarty);
        pasrArt($patient_id, $smarty);

        $smarty->assign('newPage', $followupId);

        if ($followupId > 0) {
            printSheet($followupId, $smarty);
        }

        $smarty->display('patienthistory/printcase.html');

        if ($followupId > 0) {
            $smarty->display('ovumpickup_embryotrans/printsheet.html');
        }
#################################
    } catch (Exception $ex) {
        echo $ex;
    }
}

function personalHistory($patient_id, $smarty) {
    $patient = R::load('patients', $patient_id);

    $phpersonal = R::findOne('phpersonal', 'del = ? and patientid = ? order by id DESC', [0, $patient_id]);
    $smarty->assign('phpersonal', $phpersonal);

    $today1 = new DateTime(date('Y-m-d'));
    $dateHusband = new DateTime($patient->husbanddateofbirth);
    $dateWife = new DateTime($patient->dateofbirth);

    if ($patient->dateofbirth == '0000-00-00' || is_null($patient->dateofbirth)) {
        $smarty->assign('wAge', 0);
    } else {
## calculate wife age
        $interva2 = $today1->diff($dateWife);
        $smarty->assign('wAge', $interva2->y);
    }

    if ($patient->husbanddateofbirth == '0000-00-00' || is_null($patient->husbanddateofbirth)) {
        $smarty->assign('hAge', 0);
        $patient->husbanddateofbirth = '00-00-0000';
    } else {
## calculate husband age
        $interval = $today1->diff($dateHusband);
        $smarty->assign('hAge', $interval->y);
        $patient->husbanddateofbirth = date('d-m-Y ', strtotime($patient->husbanddateofbirth));
    }

    if ($patient->mirragefromdate == '0000-00-00' || is_null($patient->mirragefromdate)) {
        $patient->mirragefromdate = '';
    } else {
        $patient->mirragefromdate = date('d/m/Y', strtotime($patient->mirragefromdate));
    }

    if (!empty($patient->wifejob)) {
        $wifeJob = R::findOne('wifejobs', 'id = ? ', [$patient->wifejob]);
        $patient->wifejob = $wifeJob->title;
    }

    if (!empty($patient->husbandjob)) {
        $husbandJob = R::findOne('husbandjobs', 'id = ? ', [$patient->husbandjob]);
        $patient->husbandjob = $husbandJob->title;
    }

    $smarty->assign('patient', $patient);
}

function menstrualHistory($patient_id, $smarty) {
    $phmenstrual = R::findOne('phmenstrual', 'del = ? and patientid = ? order by phl_mp  DESC, id desc', [0, $patient_id]);
    if (!empty($phmenstrual->phlMP)) {
        $phmenstrual->phlMP = date('d/m/Y', strtotime($phmenstrual->phlMP));
    }


    $phregualrity = R::load('phregularity', $phmenstrual->phregularity);
    $phmenstrual->phregularity = $phregualrity->name;

    $phamount = R::load('phamount', $phmenstrual->phamount);
    $phmenstrual->phamount = $phamount->name;

    $phdysmenorrhoea = R::load('phdysmenorrhoea', $phmenstrual->phdysmenorrhoea);
    $phmenstrual->phdysmenorrhoea = $phdysmenorrhoea->name;

    $smarty->assign('phmenstrual', $phmenstrual);
}

function obstetricHistory($patientId, $smarty) {

    $getAllPatientData = R::getRow("SELECT * FROM patients WHERE id = $patientId");

#### c.s count
    $csdata = R::getAll('select id from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [2, $patientId]);
    $lastCs = R::getRow('select id ,obsdate  from phobstetric where obstermination =? and del = 0  and patientid = ? order by obsdate desc   ', [2, $patientId]);
    $cs = $getAllPatientData['cs'];
    $cscounter = count($csdata) + $cs;
    $smarty->assign('cscounter', $cscounter);

    if (!empty($lastCs['obsdate'])) {
        $lastCs['obsdate'] = date('d/m/Y', strtotime($lastCs['obsdate']));
    }

    $smarty->assign('lastCs', $lastCs);
    $smarty->assign('lastCsDelivery', $lastCs['obsdate']);

#### p count
    $svddata = R::getAll('select id from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [1, $patientId]);
    $p = $getAllPatientData['pno'];
    $pcounter = count($svddata) + $cscounter + $p;
    $smarty->assign('pcounter', $pcounter);

###AB COUNT
    $Abortiondata = R::getAll('select id ,obsdate , obstrduration from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [4, $patientId]);
//  $lastAbortion = R::getRow('select id ,obsdate , obstrduration  from phobstetric where obstermination =? and del = 0  and patientid = ? order by obsdate desc   ', [4, $patientId]);
    $ab = $getAllPatientData['ab'];
    $abcounter = count($Abortiondata) + $ab;
    $smarty->assign('abcounter', $abcounter);

    foreach ($Abortiondata as $abortion) {
        if (!empty($abortion['obsdate'])) {
            $abortion['obsdate'] = date('d/m/Y', strtotime($abortion['obsdate']));
        }

        if (!empty($abortion['obstrduration'])) {
            $abortion['obstrduration'] = $abortion['obstrduration'] . ' W ';
        }
    }

    $smarty->assign('Abortiondata', $Abortiondata);
    $smarty->assign('AbortiondataCount', count($Abortiondata));

###Ectopic COUNT
    $Ectopicdata = R::getAll('select id from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [3, $patientId]);
    $Ectopic = $getAllPatientData['ectopic'];
    $Ectopiccounter = count($Ectopicdata) + $Ectopic;
    $smarty->assign('Ectopiccounter', $Ectopiccounter);

###Vmole COUNT
    $Vmoledata = R::getAll('select id from phobstetric where obstermination =? and del = 0  and patientid = ?  ', [5, $patientId]);
    $vmodel = $getAllPatientData['vmodel'];
    $vmodelcounter = count($Vmoledata) + $vmodel;
    $smarty->assign('vmodelcounter', $vmodelcounter);

    $currently = 0;
    if ($getAllPatientData['currently'] == 1) {
        $currently = 1;
    }

    $obstriccountnew = $currently + $pcounter + $abcounter + $Ectopiccounter + $vmodelcounter;
    $smarty->assign('myallobsteric', $obstriccountnew);
}

function pastHistory($patient_id, $smarty) {
    gynecological($patient_id, $smarty);
    medical($patient_id, $smarty);
    surgical($patient_id, $smarty);
}

function familyHistory($patient_id, $smarty) {
    $results = R::findall('phfamily', 'del = ? and patientid = ?
                order by   id DESC', [0, $patient_id]);

    $hus_family = '';
    $family = '';

    $i = 1;
    $j = 1;
    foreach ($results as $obj) {
        $rel = '';
        if ($obj->family_disease > 0) {
            if ($obj->family_relative > 0) {
                $relative = R::load('phfamilyrelative', $obj->family_relative);
                $rel = $relative->name . ' : ';
            }
            $operation = R::load('phfamilydisease', $obj->family_disease);
## husband ###############################################
            if ($obj->for_husband == 1) {
                if ($i > 1) {
                    $hus_family .= ' - ';
                }
                $hus_family .= $rel . ' ' . $operation->name;

                if (!empty($obj->familynote)) {
                    $hus_family .= '( ' . $obj->familynote . ' )';
                }

                $i++;
            }
## wife ###############################################
            else {
                if ($j > 1) {
                    $family .= ' - ';
                }
                $family .= $rel . ' ' . $operation->name;

                if (!empty($obj->familynote)) {
                    $family .= '( ' . $obj->familynote . ' )';
                }

                $j++;
            }
        }
    }
    $smarty->assign('hus_family', $hus_family);
    $smarty->assign('family', $family);
}

function pastHx($patient_id, $smarty) {
    $phpasthx = R::findall('phpasthx', 'del = ? and patientid = ? order by id DESC', [0, $patient_id]);
    $txt = '';

    $i = 1;
    foreach ($phpasthx as $data) {
        $phpasthxtypes = R::load('phpasthxtypes', $data->pasthx_type);
        if ($i > 1) {
            $txt .= ' - ';
        }
        $txt .= $phpasthxtypes->name;

        if (!empty($data->pasthxnote)) {
            $txt .= '( ' . $data->pasthxnote . ' )';
        }


        $i++;
    }
    $smarty->assign('phpasthx', $txt);
}

function sexualHistory($patient_id, $smarty) {
    $phsexual = R::findOne('phsexual', 'del = ? and patientid = ? order by id DESC', [0, $patient_id]);
    $sexual_type = R::load('phsexualtypes', $phsexual->sexual_type);
    $phsexual->sexual_type = $sexual_type->name;
    $smarty->assign('phsexual', $phsexual);
}

function investigation($patient_id, $smarty) {
    $semen = R::findOne('semen', 'patientid = ? and del = 0 order by sdate desc, id desc', [$patient_id]);
    if (!empty($semen->sdate) && $semen->sdate) {
        $semen->sdate = date('d/m/Y', strtotime($semen->sdate));
    }

    $smarty->assign('semen', $semen);

    $hormon = R::findOne('hormon', 'patientid = ? and del = 0 order by sdate desc, id desc', [$patient_id]);
    if (!empty($hormon->sdate)) {
        $hormon->sdate = date('d/m/Y', strtotime($hormon->sdate));
    }
    $smarty->assign('hormon', $hormon);

    $hsg = R::findOne('hsg', 'patientid = ? and del = 0 order by sdate desc, id desc', [$patient_id]);
    if (!empty($hsg->sdate)) {
        $hsg->sdate = date('d/m/Y', strtotime($hsg->sdate));
    }
    $smarty->assign('hsg', $hsg);

    $laparoscopy = R::findOne('laparoscopy', 'patientid = ? and del = 0 order by sdate desc, id desc', [$patient_id]);
    if (!empty($laparoscopy->sdate)) {
        $laparoscopy->sdate = date('d/m/Y', strtotime($laparoscopy->sdate));
    }
    $smarty->assign('laparoscopy', $laparoscopy);

    $hysteroscopy = R::findOne('hysteroscopy', 'patientid = ? and del = 0 order by sdate desc, id desc', [$patient_id]);
    if (!empty($hysteroscopy->sdate)) {
        $hysteroscopy->sdate = date('d/m/Y', strtotime($hysteroscopy->sdate));
    }
    $smarty->assign('hysteroscopy', $hysteroscopy);

    $ustv = R::findOne('ustv', 'patientid = ? and del = 0 order by sdate desc, id desc', [$patient_id]);
    if (!empty($ustv->sdate)) {
        $ustv->sdate = date('d/m/Y', strtotime($ustv->sdate));
    }
    $smarty->assign('ustv', $ustv);

    $otherinvest = R::findOne('otherinvestigationsrows', 'patientid = ? and deleted = 0 order by date desc, id desc', [$patient_id]);

    if (!empty($otherinvest->date)) {
        $otherinvest->date = date('d/m/Y', strtotime($otherinvest->date));
    }
    $investValues = R::findAll('otherinvestigationsvalues', 'investrowid = ? ', [$otherinvest->id]);
    foreach ($investValues as $data) {
        $other = R::load('otherinvestigations', $data->investid);
        $data->investName = $other->name;
    }
    $smarty->assign('otherinvest', $investValues);
    $smarty->assign('otherinvestDate', $otherinvest->date);
}

function pasrArt($patient_id, $smarty) {

    $iui = R::findall('phpastart', ' arttype = 1  and del = ? and patientid = ? order by artyear desc, id DESC', [0, $patient_id]);
    $icsi = R::findall('phpastart', ' arttype = 3  and del = ? and patientid = ? order by artyear desc, id DESC', [0, $patient_id]);

    foreach ($iui as $data) {
        $center = R::load('phpastartcenter', $data->artcenter);
        $data->artcenter = $center->name;

        $result = R::load('phpastartresult', $data->result);
        $data->result = $result->name;
    }

    foreach ($icsi as $data) {
        $center = R::load('phpastartcenter', $data->artcenter);
        $data->artcenter = $center->name;

        $result = R::load('phpastartresult', $data->result);
        $data->result = $result->name;
    }
    $smarty->assign('iui', $iui);
    $smarty->assign('iuiCount', count($iui));
    $smarty->assign('icsi', $icsi);
    $smarty->assign('icsiCount', count($icsi));
}

function printSheet($followupId, $smarty) {
    $followup = R::load('followup_operation', $followupId);

    $sql = '  select patients.id   , patients.wifename  ,  patients.husdandname  , "" as wAge   , "" as hAge
                    ,  patients.husbanddateofbirth  ,  patients.dateofbirth ,  patients.phone,  patients.mobile
                    ,  patients.wifenationalid ,  patients.husbandnationalid    ,  patients.address
                  , (CASE   WHEN patients.rfc = 1 THEN "Yes"   WHEN patients.rfc = 2 THEN "No" ELSE ""   END ) AS rfc
                    , (CASE   WHEN patients.wrfc = 1 THEN "Yes"   WHEN patients.wrfc = 2 THEN "No" ELSE ""   END ) AS wrfc
                    ,  knownfrom.name   as  knownfrom   , "" as diagnosis       ,  patients.statusno
                     ,  patients.refer_doctor  ,  patients.h_refer_doctor ,  patients.refer_doctor_tb,  patients.h_refer_doctor_tb

                    , (CASE   WHEN patients.doctor1 > 0 THEN doctor1.name      ELSE "لا يوجد "   END ) AS doctor1
                    , (CASE   WHEN patients.h_doctor1 > 0 THEN h_doctor1.name      ELSE "لا يوجد "   END ) AS h_doctor1
                    , (CASE   WHEN patients.doctor2 > 0 THEN doctor2.name      ELSE "لا يوجد "   END ) AS doctor2
                    , (CASE   WHEN patients.h_doctor2 > 0 THEN h_doctor2.name      ELSE "لا يوجد "   END ) AS h_doctor2

                   , wifejobs.title as wifejob  ,   husbandjobs.title as husbandjob
                   , religion.name as religion  ,   hreligion.name as hreligion
                    , nationality.name as nationality  ,   hnationality.name as hnationality

                     from    patients
                     left join knownfrom             on knownfrom.id = patients.knownfrom
                     left join wifejobs                 on wifejobs.id = patients.wifejob
                     left join husbandjobs         on husbandjobs.id = patients.husbandjob
                     left join religion                 on religion.id = patients.religion
                     left join hreligion                on hreligion.id = patients.h_religion
                     left join nationality                 on nationality.id = patients.nationality
                     left join hnationality            on hnationality.id = patients.h_nationality
                      left join awusers   doctor1       on doctor1.user_id = patients.doctor1
                     left join awusers     h_doctor1     on h_doctor1.user_id = patients.h_doctor1
                     left join awusers   doctor2       on doctor2.user_id = patients.doctor2
                     left join awusers     h_doctor2      on h_doctor2.user_id = patients.h_doctor2

                    where   patients.id =  ' . $followup->patientid;

    $patient = R::getRow($sql);

    $today1 = new DateTime(date('Y-m-d'));

    $dateHusband = new DateTime($patient['husbanddateofbirth']);
    $dateWife = new DateTime($patient['dateofbirth']);

    if ($patient['dateofbirth'] == '0000-00-00' || is_null($patient['dateofbirth'])) {
        $patient['wAge'] = 0;
    } else {
## calculate wife age
        $interva2 = $today1->diff($dateWife);
        $patient['wAge'] = $interva2->y;
    }


    if ($patient['husbanddateofbirth'] == '0000-00-00' || is_null($patient['husbanddateofbirth'])) {
        $patient['hAge'] = 0;
    } else {
## calculate husband age
        $interval = $today1->diff($dateHusband);
        $patient['hAge'] = $interval->y;
    }


    if ($patient['refer_doctor'] > 0) {
        if ($patient['refer_doctor_tb'] == 1) {
            $refer = R::getRow('select name from awusers where user_id = ?', [$patient['refer_doctor']]);
            $patient['refer_doctor'] = $refer['name'];
        } else {
            $refer = R::load('refer', $patient['refer_doctor']);
            $patient['refer_doctor'] = $refer->name;
        }
    } else {
        $patient['refer_doctor'] = "لا يوجد ";
    }


    if ($patient['h_refer_doctor'] > 0) {
        if ($patient['h_refer_doctor_tb'] == 1) {
            $refer = R::getRow('select name from awusers where user_id = ?', [$patient['h_refer_doctor']]);
            $patient['h_refer_doctor'] = $refer['name'];
        } else {
            $refer = R::load('refer', $patient['h_refer_doctor']);
            $patient['h_refer_doctor'] = $refer->name;
        }
    } else {
        $patient['h_refer_doctor'] = "لا يوجد ";
    }

    $v = 1;
    $diagnosis = ' ';
    $selectArray = explode(',', $followup->diagnosis);

    foreach ($selectArray as $data) {
        $diag = R::load('diagnosis', $data);
        if ($diag->conditions < 1) {
            if ($v > 1) {
                $diagnosis .= ' , ';
            }

            $diagnosis .= $diag->name;

            $v++;
        }
    }

    $patient['diagnosis'] = $diagnosis;
    $smarty->assign('patient', $patient);
}

function medical($patient_id, $smarty) {
    $results = R::findall('phpastmedical', 'del = ? and patientid = ?
                order by   id DESC', [0, $patient_id]);

    $hus_medical = '';
    $medical = '';

    $i = 1;
    $j = 1;
    foreach ($results as $obj) {
        if ($obj->medicaldisease > 0) {
            $operation = R::load('phpastmedicaldisease', $obj->medicaldisease);
## husband ###############################################
            if ($obj->for_husband == 1) {
                if ($i > 1) {
                    $hus_medical .= ' - ';
                }
                $hus_medical .= $operation->name;

                if (!empty($obj->medicalnote)) {
                    $hus_medical .= '( ' . $obj->medicalnote . ' )';
                }

                $i++;
            }
## wife ###############################################
            else {
                if ($j > 1) {
                    $medical .= ' - ';
                }
                $medical .= $operation->name;

                if (!empty($obj->medicalnote)) {
                    $medical .= '( ' . $obj->medicalnote . ' )';
                }

                $j++;
            }
        }
    }
    $smarty->assign('hus_medical', $hus_medical);
    $smarty->assign('medical', $medical);
}

function surgical($patient_id, $smarty) {
    $results = R::findall('phpastsurgical', 'del = ? and patientid = ?
                order by phsurgicalyear desc,  id DESC', [0, $patient_id]);

    $hus_surgical = '';
    $surgical = '';

    $i = 1;
    $j = 1;
    foreach ($results as $obj) {
        if ($obj->surgicaloperation > 0) {
            $operation = R::load('phpastsurgicaloperation', $obj->surgicaloperation);

## husband ###############################################
            if ($obj->for_husband == 1) {
                if ($i > 1) {
                    $hus_surgical .= ' - ';
                }
                $hus_surgical .= $operation->name;

                if (!empty($obj->surgicalnote)) {
                    $hus_surgical .= '( ' . $obj->surgicalnote . ' )';
                }

                $i++;
            }
## wife ###############################################
            else {
                if ($j > 1) {
                    $surgical .= ' - ';
                }
                $surgical .= $operation->name;

                if (!empty($obj->surgicalnote)) {
                    $surgical .= '( ' . $obj->surgicalnote . ' )';
                }

                $j++;
            }
        }
    }
    $smarty->assign('hus_surgical', $hus_surgical);
    $smarty->assign('surgical', $surgical);
}

function gynecological($patient_id, $smarty) {
    $gCological = R::findall('phpastgynecological', 'del = ? and patientid = ?
                order by gynecologicalyear desc,  id DESC', [0, $patient_id]);

    $gynecological = '';

    $i = 1;
    foreach ($gCological as $obj) {
        if ($obj->gynecologicaloperation > 0) {
            $operation = R::load('phpastgynecologicaloperation', $obj->gynecologicaloperation);
            if ($i > 1) {
                $gynecological .= ' - ';
            }

            $gynecological .= $operation->name;

            if (!empty($obj->gynecologicalnote)) {
                $gynecological .= '( ' . $obj->gynecologicalnote . ' )';
            }
            $i++;
        }
    }
    $smarty->assign('gynecological', $gynecological);
}

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

function loadRays($patientId, $visitId = 0, $patData = 0) {

    $programesetting = R::findOne('programesetting');
    if ($programesetting->branches == 1) {
        $userBranches = userBranches();
        $s = '  ,  0  as allowChange  ';
    } else {
        $s = '   ,  1 as allowChange  ';
    }


    $ext = '';

    if ($visitId > 0) {
        $ext = ' and visits.id =  ' . $visitId;
    }

    $raysVisits = R::getAll(' select visits.id  as visitId  , visits.visitdate  , visits.branch_id  ' . $s . '
              from visits   where   visits.for_department = 5  and visits.deleted = 0 and visits.patientid = ?
                  and visits.detectionid != 999  and visits.detectionid != 9999
                     ' . $ext . '  order by visits.visitdate desc  ', [$patientId]);

    $i = 0;
    foreach ($raysVisits as $visit) {
        $raysresults = R::findall('raysresults', 'deleted = ? and visitid = ? ', [0, $visit['visitId']]);

        foreach ($raysresults as $in) {
            $ray = R::load('rays', $in->rayid);
            $in->invname = $ray->name;

            $imgs = R::findall('raysresults_img', 'deleted = ? and raysresults_id = ? ', [0, $in->id]);
            $in->imgs = $imgs;
        }

        $raysVisits[$i]['raysresults'] = $raysresults;

        if ($programesetting->branches == 1 && ($userBranches[0] == -1 || in_array($visit['branch_id'], $userBranches))) {
            $raysVisits[$i]['allowChange'] = 1;
        }

        if ($patData > 0) {
            $sql = ' select  patients.wifename as  wifeName ,   patients.husdandname as  husbandName
            , visits.for_husband    ,   patients.statusno  as statusNo
            ,   patients_childs.gender  as child_gender   ,   visits.child ,   patients_childs.child_name
                         from     visits
                          join       patients                                           on patients.id  = visits.patientid
                          left  join       patients_childs                       on patients_childs.id  = visits.child
                        where   visits.id =   ' . $visit['visitId'] . '      ';
            $patient = R::getRow($sql);

            if ($patient['for_husband'] == 1) {
                $patientName = $patient['husbandName'];
            } else if ($patient['for_husband'] == 2) {
                if (is_null($patient['child_name']) || $patient['child_name'] == '') {
                    if ($patient['child_gender'] == 1) {
                        $patientName = 'الطفل / ' . $patient['wifeName'];
                    } else {
                        $patientName = 'الطفلة / ' . $patient['wifeName'];
                    }
                } else {
                    $patientName = $patient['child_name'] . '  /  ' . $patient['wifeName'];
                }
            } else {
                $patientName = $patient['wifeName'];
            }

            $patientD = $patientName . ' - ' . $patient['statusNo'];

            $raysVisits[$i]['patientD'] = $patientD;
            $raysVisits[$i]['patientName'] = $patientName;
        }
        $i++;
    }

    return $raysVisits;
}

function userBranches() {
    $related_branches = array();
    $user = R::getRow('SELECT related_branches FROM awusers
                    WHERE user_id = ? LIMIT 1', [$_SESSION['user_id']]);

    if ($user['related_branches'] == 0 && $user['related_branches'] != '' && $user['related_branches'] != null) {
        array_push($related_branches, -1);
    } else {
        $relBranches = explode(',', $user['related_branches']);
        foreach ($relBranches as $value) {
            $value = trim($value);
            array_push($related_branches, $value);
        }
    }
    return $related_branches;
}

function patDetailsCommon($visitId) {
    $visit = R::load('visits', $visitId);

    $patient = R::getRow('SELECT patients.husbanddateofbirth , patients.wifename  , patients.dateofbirth
                            , patients.statusno , patients.husdandname , wifetypes.title as wifeTypeName
                             , husbandtypes.title as husbandTypeName
                    FROM patients
                    left join   wifetypes                     on wifetypes.id = patients.wiftypeid
                    left join   husbandtypes             on husbandtypes.id = patients.husbandtypeid
                          WHERE patients.id = "' . $visit->patientid . '"   ');

    $name = '';
    $sex = '';
    $title = '';

    if ($visit->for_husband == 1) {
        $date = $patient['husbanddateofbirth'];
        $name = $patient['husdandname'];
        $title = $patient['husbandTypeName'];
        $gender = 1;
        $sex = 'Male';
    } else if ($visit->for_husband == 2) {
        $child = R::load('patients_childs', $visit->child);
        $date = $child->birth_date;
        //  $name = $child->child_name;

        if ($child->gender == 1) {
            $gender = 1;
            $title = 'الطفل ';
            $sex = 'Male';
            if (is_null($child->child_name) || $child->child_name == '') {
                $name = 'الطفل / ' . $patient['wifename'];
            } else {
                $name = $child->child_name . '  /  ' . $patient['wifename'];
            }
        } else {
            $gender = 0;
            $sex = 'Female';
            $title = 'الطفلة ';
            if (is_null($child->child_name) || $child->child_name == '') {
                $name = 'الطفلة / ' . $patient['wifename'];
            } else {
                $name = $child->child_name . '  /  ' . $patient['wifename'];
            }
        }
    } else {
        $date = $patient['dateofbirth'];
        $name = $patient['wifename'];
        $title = $patient['wifeTypeName'];
        $sex = 'Female';
        $gender = 0;
    }

    $result = array(
        "visitdate" => $visit->visitdate,
        "visittime" => $visit->visittime,
        "doctorName" => getDoctorName($visit->for_doctor),
        "title" => $title,
        "name" => $name,
        "sex" => $sex,
        "date" => $date,
        "statusNo" => $patient['statusno'],
        "gender" => $gender
    );

    return $result;
}

function getDoctorName($doctorId) {
    $doctorName = '';
    if (!empty($doctorId)) {
        $doc_info = R::getRow('select * from awusers where user_id = ?', [$doctorId]);
        $doctorName = $doc_info['name'];
    }
    return $doctorName;
}

function sympolErrorResolve($text) {
    $text = str_replace('<br>', 'addNewLineSol', $text); // Replaces <  with &lt;.
    $text = str_replace('</br>', 'addNewLineSol', $text); // Replaces <  with &lt;.
    $text = str_replace('<br/>', 'addNewLineSol', $text); // Replaces <  with &lt;.
    $text = str_replace('<br />', 'addNewLineSol', $text); // Replaces <  with &lt;.

    $text = str_replace('<', '&lt;', $text); // Replaces <  with &lt;.
    $text = str_replace('>', '&gt;', $text); // Replaces <  with &lt;.

    $text = str_replace('addNewLineSol', '<br />', $text); // Replaces <  with &lt;.

    return $text;
}
