<?php

//require_once("imp/_imp.php");
require_once("../public/aw_config.php");
//include PHPExcel library
require_once "Classes/PHPExcel/IOFactory.php";

startexcel();

function startexcel() {
    $patientList = R::findAll('excelinfopatients');    ## get all patients ned to generate excel to them

    R::exec('TRUNCATE TABLE excelinfopatients');     ## empty table

    createexcel($patientList);
}

function createexcel($patientList) {
    foreach ($patientList as $p) {
        $table = createhtmltable($p->patientid);

        ######################################################################### Save excel sheet  #######################################################################################        
        //prepare download
        $filename = date('Y-m-d') . '.xlsx';

        ## Put the html into a temporary file
        $tmpfile = time() . '.html';

        file_put_contents($tmpfile, $table);

        // Read the contents of the file into PHPExcel Reader class
        $reader = new PHPExcel_Reader_HTML;
        $content = $reader->load($tmpfile);

############### #################################### style ###########################################
        $content = style($content);
        $content = styleantenatal($content, $p->patientid);
###############################################################################################################
        //prepare download
        // Pass to writer and output as needed

        $objWriter = PHPExcel_IOFactory::createWriter($content, 'Excel2007');

        $target_dir = "../excel_backups";
        $ar = $p->statusno;

        if (!file_exists($target_dir . '/' . $ar)) {
            mkdir($target_dir . '/' . $ar, 0777, true);
        }

        $objWriter->save('../excel_backups/' . $ar . '/' . $filename);
        //$objWriter->save(str_replace($filename,'../excel_backups/xx.xls',$filename));   ## this replace if file with the same name exist
        // Delete temporary file
        unlink($tmpfile);

        //exit; //done.. exiting
    }
}

function style($content) {
    ## Auto size columns for active sheet
    foreach (range('E', 'Z') as $columnID) {
        $content->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
    }
    foreach (range('A', 'A') as $columnID) {
        $content->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
    }

    ## all cells  text alignment left
    $style = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,));
    $content->getDefaultStyle()->applyFromArray($style);

    ##  wrap text in colum 
    $content->getActiveSheet()->getStyle('B1:B' . $content->getActiveSheet()->getHighestRow())->getAlignment()->setWrapText(true);
    $content->getActiveSheet()->getStyle('D1:D' . $content->getActiveSheet()->getHighestRow())->getAlignment()->setWrapText(true);
    ## set width to specific column 
    $content->getActiveSheet()->getColumnDimension('B')->setWidth(40);
    $content->getActiveSheet()->getColumnDimension('C')->setWidth(40);
    $content->getActiveSheet()->getColumnDimension('D')->setWidth(40);

    $colArray = array('A2:A2', 'D2:D2', 'A5:A13', 'A15:A20', 'A22:A40', 'A42:A46', 'A48:A54'
        , 'A56:A61', 'A63:A68', 'A70:A74', 'A76:A87', 'A89:A97', 'A99:A105', 'A107:A113', 'A115:A121'
        , 'A123:A129', 'A131:A137', 'A139:A157', 'A159:A162', 'A164:A169', 'A171:A194', 'A196:A198', 'A200:A202', 'A204:A212');

    ## backdround color   and font style
    $backColorArray = array('fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '666666'),));
    ## make border around group of cells and style it 
    $borderArray = array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN, 'color' => array('rgb' => 'ffffff'),)));
    ## font color 
    $colorArray = array('font' => array('bold' => true, 'color' => array('rgb' => 'ffffff')));
    ##merge cells 4
    $mergeArray = array(5, 15, 22, 42, 48, 56, 63, 70, 76, 89, 90, 99, 107, 115, 123, 131, 139, 159, 164, 171, 196, 200, 204);
    foreach ($mergeArray as $col) {
        $content->getActiveSheet()->mergeCells('A' . $col . ':R' . $col);
        $content->getActiveSheet()->getStyle('A' . $col . ':A' . $col)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $content->getActiveSheet()->getStyle('A' . $col . ':R' . $col)->applyFromArray($borderArray);
    }


    foreach ($colArray as $col) {
        $content->getActiveSheet()->getStyle($col)->applyFromArray($backColorArray);
        $content->getActiveSheet()->getStyle($col)->applyFromArray($borderArray);
        $content->getActiveSheet()->getStyle($col)->applyFromArray($colorArray);
    }
    unset($backColorArray);
    unset($colorArray);
    unset($borderArray);

    return $content;
}

function styleantenatal($content, $patientId) {
    $patient = R::load('patients', $patientId);
    $content->getActiveSheet()->setCellValue('B2', $patient->wifename);
    ## backdround color   and font style
    $backColorArray = array('fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => '666666'),));
    ## make border around group of cells and style it 
    $borderArray = array('borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_THIN, 'color' => array('rgb' => 'ffffff'),)));
    ## font color 
    $colorArray = array('font' => array('bold' => true, 'color' => array('rgb' => 'ffffff')));

    $allObj = R::findAll('mainantenental', ' patientid = ?', [$patientId]);
    $noOfAntinatal = count($allObj);
    if ($noOfAntinatal > 0) {

        ##merge cells 
        $mergeArray = array(206);
        $mergeArray1 = array();
        $row = 206;
        for ($i = 1; $i < $noOfAntinatal; $i++) {
            $newRow = $row + 28;
            array_push($mergeArray, $newRow);
            $rowUs = 'A' . ($row + 8) . ':A' . ($row + 8 + 10);
            $rowLab = 'A' . ($row + 20) . ':A' . ($row + 20 + 2);
            $rowTTt = 'A' . ($row + 24) . ':A' . ($row + 24 + 2);
            array_push($mergeArray1, ($row + 8));
            array_push($mergeArray1, ($row + 20));
            array_push($mergeArray1, ($row + 24));

            $content->getActiveSheet()->getStyle($rowUs)->applyFromArray($backColorArray);
            $content->getActiveSheet()->getStyle($rowUs)->applyFromArray($borderArray);
            $content->getActiveSheet()->getStyle($rowUs)->applyFromArray($colorArray);

            $content->getActiveSheet()->getStyle($rowLab)->applyFromArray($backColorArray);
            $content->getActiveSheet()->getStyle($rowLab)->applyFromArray($borderArray);
            $content->getActiveSheet()->getStyle($rowLab)->applyFromArray($colorArray);

            $content->getActiveSheet()->getStyle($rowTTt)->applyFromArray($backColorArray);
            $content->getActiveSheet()->getStyle($rowTTt)->applyFromArray($borderArray);
            $content->getActiveSheet()->getStyle($rowTTt)->applyFromArray($colorArray);

            $row = $newRow;
        }
        array_push($mergeArray1, ($row + 8));
        array_push($mergeArray1, ($row + 20));
        array_push($mergeArray1, ($row + 24));

        $rowUs = 'A' . ($row + 8) . ':A' . ($row + 8 + 10);
        $rowLab = 'A' . ($row + 20) . ':A' . ($row + 20 + 2);
        $rowTTt = 'A' . ($row + 24) . ':A' . ($row + 24 + 2);

        $content->getActiveSheet()->getStyle($rowUs)->applyFromArray($backColorArray);
        $content->getActiveSheet()->getStyle($rowUs)->applyFromArray($borderArray);
        $content->getActiveSheet()->getStyle($rowUs)->applyFromArray($colorArray);

        $content->getActiveSheet()->getStyle($rowLab)->applyFromArray($backColorArray);
        $content->getActiveSheet()->getStyle($rowLab)->applyFromArray($borderArray);
        $content->getActiveSheet()->getStyle($rowLab)->applyFromArray($colorArray);

        $content->getActiveSheet()->getStyle($rowTTt)->applyFromArray($backColorArray);
        $content->getActiveSheet()->getStyle($rowTTt)->applyFromArray($borderArray);
        $content->getActiveSheet()->getStyle($rowTTt)->applyFromArray($colorArray);

        foreach ($mergeArray as $col) {
            $content->getActiveSheet()->mergeCells('A' . $col . ':R' . $col);
            $content->getActiveSheet()->getStyle('A' . $col . ':A' . $col)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        }
        foreach ($mergeArray1 as $col) {
            $content->getActiveSheet()->mergeCells('A' . $col . ':B' . $col);
            $content->getActiveSheet()->getStyle('A' . $col . ':A' . $col)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        }



        $colArray = array();
        foreach ($mergeArray as $value) {
            $newVal = $value + 6;
            $element = 'A' . $value . ':A' . $newVal;
            array_push($colArray, $element);
        }


        foreach ($colArray as $col) {
            $content->getActiveSheet()->getStyle($col)->applyFromArray($backColorArray);
            $content->getActiveSheet()->getStyle($col)->applyFromArray($borderArray);
            $content->getActiveSheet()->getStyle($col)->applyFromArray($colorArray);
        }
        unset($backColorArray);
        unset($colorArray);
        unset($borderArray);
    }

    return $content;
}

function createhtmltable($patientId) {
    $tables = '';

    ## functions each one return  table with controll data
    ###########################################################  patient name and date  #######################################################################################
    ## name and date 
    $t1 = nameanddate($patientId);
    $tables .= $t1;
    ###########################################################  patient history  #######################################################################################     
    #### Menstrual History
    $t2 = menstrualhistory($patientId);
    $tables .= $t2;

    ##Contraception History
    $t3 = contraceptionhistory($patientId);
    $tables .= $t3;

    ###Obstetric History
    $t4 = obstetrichistory($patientId);
    $tables .= $t4;

    ###Past History - Medical
    $t5 = medical($patientId);
    $tables .= $t5;

    ###Past History - Surgical
    $t6 = surgical($patientId);
    $tables .= $t6;

    ###Past History - Gynecological
    $t7 = gynecological($patientId);
    $tables .= $t7;

    ###Past History - ART
    $t8 = art($patientId);
    $tables .= $t8;

    ### Family History
    $t9 = familyhistory($patientId);
    $tables .= $t9;

    ############################################################  Examination  #######################################################################################  
    $t26 = examination($patientId);
    $tables .= $t26;
    #############################################################  Investigations  #######################################################################################     
    ###Investigations - Semen
    $t10 = semen($patientId);
    $tables .= $t10;

    ###Investigations - HSG
    $t11 = hsg($patientId);
    $tables .= $t11;

    ###Investigations - US/TVS
    $t12 = ustvs($patientId);
    $tables .= $t12;

    ###Investigations - LAPAROSCOPY
    $t13 = laparoscopy($patientId);
    $tables .= $t13;

    ###Investigations - HYSTEROSCOPY
    $t14 = hysteroscopy($patientId);
    $tables .= $t14;

    ###Investigations - MRI/CT
    $t15 = mrict($patientId);
    $tables .= $t15;

    ###Investigations - HORMONES
    $t16 = hormones($patientId);
    $tables .= $t16;

    ###Investigations - PATHOLOGY
    $t17 = pathology($patientId);
    $tables .= $t17;

    #############################################################  Gyna  #######################################################################################
    ###Gyna - Visits
    $t18 = visits($patientId);
    $tables .= $t18;

    ###Gyna -Folliculometry
    $t19 = folliculometry($patientId);
    $tables .= $t19;

    ###Gyna -investigation
    $t20 = investigation($patientId);
    $tables .= $t20;

    ###Gyna -Treatment
    $t21 = treatment($patientId);
    $tables .= $t21;

    ##############################################################  Antenatal  #######################################################################################
    ###Antenatal Visits
    $t22 = antenatal($patientId);
    $tables .= $t22;

    ################################################################################################################################################     
    return $tables;
}

function nameanddate($patientId) {
    $patient = R::load('patients', $patientId);
    $table = '<table>'
            . '<tr><td>Patient Id</td><td>' . $patient->wifename . '</td><td></td><td>Date</td><td>' . date('Y-m-d') . '</td></tr>'
            . '<tr><td></td><td></td><td></td><td></td><td></td></tr>'
            . '</table>';
    return $table;
}

function menstrualhistory($patientId) {
    $trDate = '<tr><td>Date</td>';
    $trMenarche = '<tr><td>Menarche</td>';
    $trDuration = '<tr><td>Duration</td>';
    $trLength = '<tr><td>Length</td>';
    $trRegularity = '<tr><td>Regularity</td>';
    $trAmount = '<tr><td>Amount</td>';
    $trDysmenorrhoea = '<tr><td>Dysmenorrhoea</td>';
    $trLMP = '<tr><td>LMP</td>';

    $table = '<table><tr><td>Menstrual History</td></tr>';

    $allphmenstrual = R::findall('phmenstrual', 'del = ? and patientid = ? order by id DESC', [0, $patientId]);
    foreach ($allphmenstrual as $myallphmenstrual) {
        $userData = R::getRow('select user_name from awusers where user_id = ' . $myallphmenstrual->doctorid);
        $myallphmenstrual->username = $userData['user_name'];
        if (!empty($myallphmenstrual->phregularity)) {
            $reqularity = R::getRow('select name from phregularity where id = ' . $myallphmenstrual->phregularity);
            $myallphmenstrual->reg = $reqularity['name'];
        }
        if (!empty($myallphmenstrual->phamount)) {
            $amount = R::getRow('select name from phamount where id = ' . $myallphmenstrual->phamount);
            $myallphmenstrual->amount = $amount['name'];
        }
        if (!empty($myallphmenstrual->phdysmenorrhoea)) {
            $dysmenorrhoea = R::getRow('select name from phdysmenorrhoea where id = ' . $myallphmenstrual->phdysmenorrhoea);
            $myallphmenstrual->dysm = $dysmenorrhoea['name'];
        }

        $trDate .= '<td>' . $myallphmenstrual->sysdate . '</td>';
        $trMenarche .= '<td>' . $myallphmenstrual->menarche . '</td>';
        $trDuration .= '<td>' . $myallphmenstrual->duration . '</td>';
        $trLength .= '<td>' . $myallphmenstrual->length . '</td>';
        $trRegularity .= '<td>' . $myallphmenstrual->reg . '</td>';
        $trAmount .= '<td>' . $myallphmenstrual->amount . '</td>';
        $trDysmenorrhoea .= '<td>' . $myallphmenstrual->dysm . '</td>';
        $trLMP .= '<td>' . $myallphmenstrual->phl_mp . '</td>';
    }

    $trDate .= '</tr>';
    $trMenarche .= '</tr>';
    $trDuration .= '</tr>';
    $trLength .= '</tr>';
    $trRegularity .= '</tr>';
    $trAmount .= '</tr>';
    $trDysmenorrhoea .= '</tr>';
    $trLMP .= '</tr>';

    $table .= $trDate;
    $table .= $trMenarche;
    $table .= $trDuration;
    $table .= $trLength;
    $table .= $trRegularity;
    $table .= $trAmount;
    $table .= $trDysmenorrhoea;
    $table .= $trLMP;
    $table .= '</table>';
    return $table;
}

function contraceptionhistory($patientId) {
    $trDate = '<tr><td>Date</td>';
    $trType = '<tr><td>Type</td>';
    $trDuration = '<tr><td>Duration</td>';
    $trStopped = '<tr><td>Stopped</td>';
    $trNotes = '<tr><td>Notes</td>';

    $table = '<table><tr><td>Contraception History</td></tr>';

    $allcontract = R::findall('phcontraception', 'del = ? and patientid = ? and (contype != "" or contduration != "" or contstopped != "" or contranote != "") order by id DESC', [0, $patientId]);
    foreach ($allcontract as $myallcontract) {

        $userData = R::getRow('select user_name from awusers where user_id = ' . $myallcontract->doctorid);
        $myallcontract->username = $userData['user_name'];

        if (!empty($myallcontract->contype)) {
            $contype = R::getRow('select name from phcontracttype where id = ' . $myallcontract->contype);
            $myallcontract->type = $contype['name'];
        }
        $trDate .= '<td>' . $myallcontract->sysdate . '</td>';
        $trType .= '<td>' . $myallcontract->type . '</td>';
        $trDuration .= '<td>' . $myallcontract->contduration . '</td>';
        $trStopped .= '<td>' . $myallcontract->contstopped . '</td>';
        $trNotes .= '<td>' . $myallcontract->contranote . '</td>';
    }
    $trDate .= '</tr>';
    $trType .= '</tr>';
    $trDuration .= '</tr>';
    $trStopped .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trType;
    $table .= $trDuration;
    $table .= $trStopped;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function obstetrichistory($patientId) {
    $trDate = '<tr><td>Date</td>';
    $trDuration = '<tr><td>Duration</td>';
    $trTermination = '<tr><td>Termination</td>';
    $trPlace = '<tr><td>Place</td>';
    $trType = '<tr><td>Type</td>';
    $trOutCome = '<tr><td>OutCome</td>';
    $trGender = '<tr><td>Gender</td>';
    $trWeight = '<tr><td>Baby Weight</td>';
    $trName = '<tr><td>Baby Name</td>';
    $trOutCome1 = '<tr><td>OutCome</td>';
    $trGender1 = '<tr><td>Gender</td>';
    $trWeight1 = '<tr><td>Baby Weight</td>';
    $trName1 = '<tr><td>Baby Name</td>';
    $trOutCome2 = '<tr><td>OutCome</td>';
    $trGender2 = '<tr><td>Gender</td>';
    $trWeight2 = '<tr><td>Baby Weight</td>';
    $trName2 = '<tr><td>Baby Name</td>';
    $trNotes = '<tr><td>Notes</td>';

    $table = '<table><tr><td>Obstetric History</td></tr>';

    $allobsteric = R::findall('phobstetric', 'del = ? and patientid = ? and (obstrduration != "" or obstermination != "" or obsplace != "" or obsdate != ""  or obsnote != "")  order by id DESC', [0, $patientId]);

    foreach ($allobsteric as $myallobsteric) {
        $userData = R::getRow('select user_name from awusers where user_id = ' . $myallobsteric->doctorid);
        $myallobsteric->username = $userData['user_name'];

        if (!empty($myallobsteric->obstermination)) {
            $terminate = R::getRow('select name from phobstericterminate where id = ' . $myallobsteric->obstermination);
            $myallobsteric->term = $terminate['name'];
        }
        if (!empty($myallobsteric->obsplace)) {
            $place = R::getRow('select name from phobstericterplace where id = ' . $myallobsteric->obsplace);
            $myallobsteric->place = $place['name'];
        }


        if ($myallobsteric->obstermination == 1 || $myallobsteric->obstermination == 2) {
            switch ($myallobsteric->babygendernew) {
                case 0:
                    $myallobsteric->babygendernew = 'Male';
                    break;
                case 1:
                    $myallobsteric->babygendernew = 'Female';
                    break;
                default:
                    $myallobsteric->babygendernew = '--';
                    break;
            }

            switch ($myallobsteric->outcomeid) {
                case 0:
                    $myallobsteric->outcom = 'Male';
                    break;
                case 1:
                    $myallobsteric->outcom = 'Female';
                    break;
                case 2:
                    $myallobsteric->outcom = 'Twins';
                    break;
                case 3:
                    $myallobsteric->outcom = 'Triplets';
                    break;
                default:
                    $myallobsteric->outcom = '--';
                    break;
            }

            switch ($myallobsteric->babygendernew1) {
                case 0:
                    $myallobsteric->babygendernew1 = 'Male';
                    break;
                case 1:
                    $myallobsteric->babygendernew1 = 'Female';
                    break;
                default:
                    $myallobsteric->babygendernew1 = '--';
                    break;
            }


            switch ($myallobsteric->babygendernew2) {
                case 0:
                    $myallobsteric->babygendernew2 = 'Male';
                    break;
                case 1:
                    $myallobsteric->babygendernew2 = 'Female';
                    break;
                default:
                    $myallobsteric->babygendernew2 = '--';
                    break;
            }

            switch ($myallobsteric->babytype) {
                case 0:
                    $myallobsteric->babytype = 'Living';
                    break;
                case 1:
                    $myallobsteric->babytype = 'Dead';
                    break;
                default:
                    $myallobsteric->babytype = '--';
                    break;
            }


            switch ($myallobsteric->babytype1) {
                case 0:
                    $myallobsteric->babytype1 = 'Living';
                    break;
                case 1:
                    $myallobsteric->babytype1 = 'Dead';
                    break;
                default:
                    $myallobsteric->babytype1 = '--';
                    break;
            }


            switch ($myallobsteric->babytype2) {
                case 0:
                    $myallobsteric->babytype2 = 'Living';
                    break;
                case 1:
                    $myallobsteric->babytype2 = 'Dead';
                    break;
                default:
                    $myallobsteric->babytype2 = '--';
                    break;
            }
        } else {
            $myallobsteric->babygendernew = '--';
            $myallobsteric->babygendernew1 = '--';
            $myallobsteric->babygendernew2 = '--';
            $myallobsteric->babytype = '--';
            $myallobsteric->babytype1 = '--';
            $myallobsteric->babytype2 = '--';
            $myallobsteric->outcom = '--';
        }

        if ($myallobsteric->outcomeid == 0 || $myallobsteric->outcomeid == 1) {
            $myallobsteric->babygendernew1 = '--';
            $myallobsteric->babygendernew2 = '--';
            $myallobsteric->babytype1 = '--';
            $myallobsteric->babytype2 = '--';
        } elseif ($myallobsteric->outcomeid == 2) {
            $myallobsteric->babygendernew2 = '--';
            $myallobsteric->babytype2 = '--';
        }

        $trDate .= '<td>' . $myallobsteric->obsdate . '</td>';
        $trDuration .= '<td>' . $myallobsteric->obstrduration . '</td>';
        $trTermination .= '<td>' . $myallobsteric->term . '</td>';
        $trPlace .= '<td>' . $myallobsteric->place . '</td>';
        $trType .= '<td>' . $myallobsteric->outcom . '</td>';
        $trOutCome .= '<td>' . $myallobsteric->babytype . '</td>';
        $trGender .= '<td>' . $myallobsteric->babygendernew . '</td>';
        $trWeight .= '<td>' . $myallobsteric->babyweight . '</td>';
        $trName .= '<td>' . $myallobsteric->babyname . '</td>';
        $trOutCome1 .= '<td>' . $myallobsteric->babytype1 . '</td>';
        $trGender1 .= '<td>' . $myallobsteric->babygendernew1 . '</td>';
        $trWeight1 .= '<td>' . $myallobsteric->babyweight1 . '</td>';
        $trName1 .= '<td>' . $myallobsteric->babyname1 . '</td>';
        $trOutCome2 .= '<td>' . $myallobsteric->babytype2 . '</td>';
        $trGender2 .= '<td>' . $myallobsteric->babygendernew2 . '</td>';
        $trWeight2 .= '<td>' . $myallobsteric->babyweight2 . '</td>';
        $trName2 .= '<td>' . $myallobsteric->babyname2 . '</td>';
        $trNotes .= '<td>' . $myallobsteric->obsnote . '</td>';
    }

    $trDate .= '</tr>';
    $trDuration .= '</tr>';
    $trTermination .= '</tr>';
    $trPlace .= '</tr>';
    $trType .= '</tr>';
    $trOutCome .= '</tr>';
    $trGender .= '</tr>';
    $trWeight .= '</tr>';
    $trName .= '</tr>';
    $trOutCome1 .= '</tr>';
    $trGender1 .= '</tr>';
    $trWeight1 .= '</tr>';
    $trName1 .= '</tr>';
    $trOutCome2 .= '</tr>';
    $trGender2 .= '</tr>';
    $trWeight2 .= '</tr>';
    $trName2 .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trDuration;
    $table .= $trTermination;
    $table .= $trPlace;
    $table .= $trType;
    $table .= $trOutCome;
    $table .= $trGender;
    $table .= $trWeight;
    $table .= $trName;
    $table .= $trOutCome1;
    $table .= $trGender1;
    $table .= $trWeight1;
    $table .= $trName1;
    $table .= $trOutCome2;
    $table .= $trGender2;
    $table .= $trWeight2;
    $table .= $trName2;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function medical($patientId) {
    $trDate = '<tr><td>Date</td>';
    $trDisease = '<tr><td>Disease</td>';
    $trNotes = '<tr><td>Notes</td>';
    $trFor = '<tr><td>For</td>';

    $table = '<table><tr><td>Past H Medical</td></tr>';

    $allpastmedical = R::findall('phpastmedical', 'del = ? and patientid = ? and (medicaldisease != "" or medicalnote != "")  order by id DESC', [0, $patientId]);
    foreach ($allpastmedical as $myallpastmedical) {
        $userData = R::getRow('select user_name from awusers where user_id = ' . $myallpastmedical->doctorid);
        $myallpastmedical->username = $userData['user_name'];
        if (!empty($myallpastmedical->medicaldisease)) {
            $disease = R::getRow('select name from phpastmedicaldisease where id = ' . $myallpastmedical->medicaldisease);
            $myallpastmedical->disease = $disease['name'];
        }

        $trDate .= '<td>' . $myallpastmedical->sysdate . '</td>';
        $trDisease .= '<td>' . $myallpastmedical->disease . '</td>';
        $trNotes .= '<td>' . $myallpastmedical->medicalnote . '</td>';
        if ($myallpastmedical->for_husband == 1) {
            $trFor .= '<td> Husband </td>';
        } else {
            $trFor .= '<td> Wife </td>';
        }
    }

    $trDate .= '</tr>';
    $trDisease .= '</tr>';
    $trNotes .= '</tr>';
    $trFor .= '</tr>';

    $table .= $trDate;
    $table .= $trDisease;
    $table .= $trNotes;
    $table .= $trFor;

    $table .= '</table>';
    return $table;
}

function surgical($patientId) {
    $trDate = '<tr><td>Date</td>';
    $trOperation = '<tr><td>Operation</td>';
    $trYear = '<tr><td>Year</td>';
    $trSurgon = '<tr><td>Surgon</td>';
    $trNotes = '<tr><td>Notes</td>';
    $trFor = '<tr><td>For</td>';

    $table = '<table><tr><td>Past H Surgical</td></tr>';

    $allpastsurgical = R::findall('phpastsurgical', 'del = ? and patientid = ? and (surgicaloperation != "" or phsurgicalyear != "" or phsurgicalsurgeon != "" or surgicalnote != "") order by id DESC', [0, $patientId]);
    foreach ($allpastsurgical as $myallpastsurgical) {
        $userData = R::getRow('select user_name from awusers where user_id = ' . $myallpastsurgical->doctorid);
        $myallpastsurgical->username = $userData['user_name'];
        if (!empty($myallpastsurgical->surgicaloperation)) {
            $operation = R::getRow('select name from phpastsurgicaloperation where id = ' . $myallpastsurgical->surgicaloperation);
            $myallpastsurgical->operation = $operation['name'];
        }

        $trDate .= '<td>' . $myallpastsurgical->sysdate . '</td>';
        $trOperation .= '<td>' . $myallpastsurgical->operation . '</td>';
        $trYear .= '<td>' . $myallpastsurgical->phsurgicalyear . '</td>';
        $trSurgon .= '<td>' . $myallpastsurgical->phsurgicalsurgeon . '</td>';
        $trNotes .= '<td>' . $myallpastsurgical->surgicalnote . '</td>';
        if ($myallpastsurgical->for_husband == 1) {
            $trFor .= '<td> Husband </td>';
        } else {
            $trFor .= '<td> Wife </td>';
        }
    }

    $trDate .= '</tr>';
    $trOperation .= '</tr>';
    $trYear .= '</tr>';
    $trSurgon .= '</tr>';
    $trNotes .= '</tr>';
    $trFor .= '</tr>';

    $table .= $trDate;
    $table .= $trOperation;
    $table .= $trYear;
    $table .= $trSurgon;
    $table .= $trNotes;
    $table .= $trFor;

    $table .= '</table>';
    return $table;
}

function gynecological($patientId) {
    $table = '<table><tr><td>Past H GYNECOLOGICAL</td></tr>';
    $trDate = '<tr><td>Date</td>';
    $trOperation = '<tr><td>Operation</td>';
    $trYear = '<tr><td>Year</td>';
    $trSurgon = '<tr><td>Surgon</td>';
    $trNotes = '<tr><td>Notes</td>';

    $allphpastgynecological = R::findall('phpastgynecological', 'del = ? and patientid = ? and (gynecologicaloperation != "" or gynecologicalyear != "" or gynecologicalsurgeon != "" or gynecologicalnote != "") order by id DESC', [0, $patientId]);
    foreach ($allphpastgynecological as $myallphpastgynecological) {
        $userData = R::getRow('select user_name from awusers where user_id = ' . $myallphpastgynecological->doctorid);
        $myallphpastgynecological->username = $userData['user_name'];
        if (!empty($myallphpastgynecological->gynecologicaloperation)) {
            $operation = R::getRow('select name from phpastgynecologicaloperation where id = ' . $myallphpastgynecological->gynecologicaloperation);
            $myallphpastgynecological->operation = $operation['name'];
        }

        $trDate .= '<td>' . $myallphpastgynecological->sysdate . '</td>';
        $trOperation .= '<td>' . $myallphpastgynecological->operation . '</td>';
        $trYear .= '<td>' . $myallphpastgynecological->gynecologicalyear . '</td>';
        $trSurgon .= '<td>' . $myallphpastgynecological->gynecologicalsurgeon . '</td>';
        $trNotes .= '<td>' . $myallphpastgynecological->gynecologicalnote . '</td>';
    }



    $trDate .= '</tr>';
    $trOperation .= '</tr>';
    $trYear .= '</tr>';
    $trSurgon .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trOperation;
    $table .= $trYear;
    $table .= $trSurgon;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function art($patientId) {
    $table = '<table><tr><td>Past H ART</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trType = '<tr><td>Type</td>';
    $trCenter = '<tr><td>Center</td>';
    $trYear = '<tr><td>Year</td>';
    $trNotes = '<tr><td>Notes</td>';

    $allphpastart = R::findall('phpastart', 'del = ? and patientid = ? and (arttype != "" or artcenter != "" or artyear != "" or artnote != "")  order by id DESC', [0, $patientId]);
    foreach ($allphpastart as $myallphpastart) {
        $userData = R::getRow('select user_name from awusers where user_id = ' . $myallphpastart->doctorid);
        $myallphpastart->username = $userData['user_name'];
        if (!empty($myallphpastart->arttype)) {
            $type = R::getRow('select name from phpastarttype where id = ' . $myallphpastart->arttype);
            $myallphpastart->type = $type['name'];
        }
        if (!empty($myallphpastart->artcenter)) {
            $center = R::getRow('select name from phpastartcenter where id = ' . $myallphpastart->artcenter);
            $myallphpastart->center = $center['name'];
        }

        $trDate .= '<td>' . $myallphpastart->sysdate . '</td>';
        $trType .= '<td>' . $myallphpastart->type . '</td>';
        $trCenter .= '<td>' . $myallphpastart->center . '</td>';
        $trYear .= '<td>' . $myallphpastart->artyear . '</td>';
        $trNotes .= '<td>' . $myallphpastart->artnote . '</td>';
    }

    $trDate .= '</tr>';
    $trType .= '</tr>';
    $trCenter .= '</tr>';
    $trYear .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trType;
    $table .= $trCenter;
    $table .= $trYear;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function familyhistory($patientId) {
    $table = '<table><tr><td>Family History</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trDisease = '<tr><td>Disease</td>';
    $trRelative = '<tr><td>Relative</td>';
    $trNotes = '<tr><td>Notes</td>';

    $allphfamily = R::findall('phfamily', 'del = ? and patientid = ? and (family_disease != "" or family_relative != "" or familynote != "")   order by id DESC', [0, $patientId]);
    foreach ($allphfamily as $myallphfamily) {
        $userData = R::getRow('select user_name from awusers where user_id = ' . $myallphfamily->doctorid);
        $myallphfamily->username = $userData['user_name'];
        if (!empty($myallphfamily->family_disease)) {
            $disease = R::getRow('select name from phfamilydisease where id = ' . $myallphfamily->family_disease);
            $myallphfamily->disease = $disease['name'];
        }
        if (!empty($myallphfamily->family_relative)) {
            $relative = R::getRow('select name from phfamilyrelative where id = ' . $myallphfamily->family_relative);
            $myallphfamily->relative = $relative['name'];
        }

        $trDate .= '<td>' . $myallphfamily->sysdate . '</td>';
        $trDisease .= '<td>' . $myallphfamily->disease . '</td>';
        $trRelative .= '<td>' . $myallphfamily->relative . '</td>';
        $trNotes .= '<td>' . $myallphfamily->familynote . '</td>';
    }

    $trDate .= '</tr>';
    $trDisease .= '</tr>';
    $trRelative .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trDisease;
    $table .= $trRelative;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function examination($patientId) {
    $table = '<table><tr><td>Examination</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trWeight = '<tr><td>Weight</td>';
    $trHeight = '<tr><td>Height</td>';
    $trBMI = '<tr><td>BMI</td>';
    $trbP = '<tr><td>bP</td>';
    $trpulse = '<tr><td>pulse</td>';
    $trHeadandneck = '<tr><td>Headandneck</td>';
    $trChestandheart = '<tr><td>Chestandheart</td>';
    $trAbdomen = '<tr><td>Abdomen</td>';
    $trPelvis = '<tr><td>Pelvis</td>';
    $trExtremitis = '<tr><td>Extremitis</td>';

    $allexmination = R::getAll('select examination.*, awusers.user_name as docname from examination,awusers where  examination.doctorid = awusers.user_id and del = 0 and patientid = ? and (weight != "" or height != "" or bmi != "" or b_p != "" or pulse != "" or headandneck != "" or chestandheart != "" or abdomen != "" or pelvis != "" or extremitis != "")', [$patientId]);
    foreach ($allexmination as $myallexmination) {
        $trDate .= '<td>' . $myallexmination['examinationdate'] . '</td>';
        $trWeight .= '<td>' . $myallexmination['weight'] . '</td>';
        $trHeight .= '<td>' . $myallexmination['height'] . '</td>';
        $trBMI .= '<td>' . $myallexmination['bmi'] . '</td>';
        $trbP .= '<td>' . substr($myallexmination['b_p'], 0, 3) . '/' . substr($myallexmination['b_p'], 3, 3) . '</td>';
        $trpulse .= '<td>' . $myallexmination['pulse'] . '</td>';
        $trHeadandneck .= '<td>' . $myallexmination['headandneck'] . '</td>';
        $trChestandheart .= '<td>' . $myallexmination['chestandheart'] . '</td>';
        $trAbdomen .= '<td>' . $myallexmination['abdomen'] . '</td>';
        $trPelvis .= '<td>' . $myallexmination['pelvis'] . '</td>';
        $trExtremitis .= '<td>' . $myallexmination['extremitis'] . '</td>';
    }

    $trDate .= '</tr>';
    $trWeight .= '</tr>';
    $trHeight .= '</tr>';
    $trBMI .= '</tr>';
    $trbP .= '</tr>';
    $trpulse .= '</tr>';
    $trHeadandneck .= '</tr>';
    $trChestandheart .= '</tr>';
    $trAbdomen .= '</tr>';
    $trPelvis .= '</tr>';
    $trExtremitis .= '</tr>';

    $table .= $trDate;
    $table .= $trWeight;
    $table .= $trHeight;
    $table .= $trBMI;
    $table .= $trbP;
    $table .= $trpulse;
    $table .= $trHeadandneck;
    $table .= $trChestandheart;
    $table .= $trAbdomen;
    $table .= $trPelvis;
    $table .= $trExtremitis;

    $table .= '</table>';
    return $table;
}

function semen($patientId) {
    $table = '<table><tr><td>Investigation </td></tr><tr><td>Semen</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trCount = '<tr><td>Count</td>';
    $trMotilityA = '<tr><td>MotilityA</td>';
    $trMotilityAB = '<tr><td>MotilityA+B</td>';
    $trNormal = '<tr><td>Normal</td>';
    $trPusCells = '<tr><td>Pus cells</td>';
    $trNotes = '<tr><td>Notes</td>';

    $allsemen = R::getAll('select semen.*, awusers.user_name as docname from semen,awusers where  semen.doctorid = awusers.user_id and semen.patientid = ? and semen.del = 0  and (!isNull(`count`) or !isNull(`motilitya`) or !isNull(`motilityab`) or !isNull(`normal`) or !isNull(`puscell`) or !isNull(`normaltype`) or !isNull(`oligo`) or !isNull(`astheno`) or !isNull(`tetrato`) or !isNull(`notes`))', [$patientId]);
    foreach ($allsemen as $myallsemen) {
        $trDate .= '<td>' . $myallsemen['sdate'] . '</td>';
        $trCount .= '<td>' . $myallsemen['count'] . '</td>';
        $trMotilityA .= '<td>' . $myallsemen['motilitya'] . '</td>';
        $trMotilityAB .= '<td>' . $myallsemen['motilityab'] . '</td>';
        $trNormal .= '<td>' . $myallsemen['normal'] . '</td>';
        $trPusCells .= '<td>' . $myallsemen['puscell'] . '</td>';
        $trNotes .= '<td>' . $myallsemen['notes'] . '</td>';
    }


    $trDate .= '</tr>';
    $trCount .= '</tr>';
    $trMotilityA .= '</tr>';
    $trMotilityAB .= '</tr>';
    $trNormal .= '</tr>';
    $trPusCells .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trCount;
    $table .= $trMotilityA;
    $table .= $trMotilityAB;
    $table .= $trNormal;
    $table .= $trPusCells;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function hsg($patientId) {
    $table = '<table><tr><td>HSG</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trUterus = '<tr><td>Uterus</td>';
    $trRTube = '<tr><td>R.tube</td>';
    $trLTube = '<tr><td>L.tube</td>';
    $trSmear = '<tr><td>Smear</td>';
    $trNotes = '<tr><td>Notes</td>';

    $allhsg = R::getAll('select hsg.*, awusers.user_name as docname from hsg,awusers where  hsg.doctorid = awusers.user_id and hsg.patientid = ? and hsg.del = 0 and (!isNull(`uterus`) or !isNull(`ltube`) or !isNull(`smear`) or !isNull(`rtube`) or !isNull(`notes`))', [$patientId]);
    foreach ($allhsg as $myallhsg) {
        $trDate .= '<td>' . $myallhsg['sdate'] . '</td>';
        $trUterus .= '<td>' . $myallhsg['uterus'] . '</td>';
        $trRTube .= '<td>' . $myallhsg['rtube'] . '</td>';
        $trLTube .= '<td>' . $myallhsg['ltube'] . '</td>';
        $trSmear .= '<td>' . $myallhsg['smear'] . '</td>';
        $trNotes .= '<td>' . $myallhsg['notes'] . '</td>';
    }



    $trDate .= '</tr>';
    $trUterus .= '</tr>';
    $trRTube .= '</tr>';
    $trLTube .= '</tr>';
    $trSmear .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trUterus;
    $table .= $trRTube;
    $table .= $trLTube;
    $table .= $trSmear;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function ustvs($patientId) {
    $table = '<table><tr><td>US/TVS</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trUterus = '<tr><td>Uterus</td>';
    $trRTube = '<tr><td>R.adnexa</td>';
    $trLTube = '<tr><td>L.adnexa</td>';
    $trSmear = '<tr><td>Pelvis</td>';
    $trNotes = '<tr><td>Notes</td>';

    $allustv = R::getAll('select ustv.*, awusers.user_name as docname from ustv,awusers where  ustv.doctorid = awusers.user_id and ustv.patientid = ? and ustv.del = 0 and (!isNULL(`uterus`) or !isNULL(`radnexa`) or !isNULL(`ladnexa`) or !isNULL(`pelvis`) or !isNull(`notes`))', [$patientId]);
    foreach ($allustv as $myallustv) {
        $trDate .= '<td>' . $myallustv['sdate'] . '</td>';
        $trUterus .= '<td>' . $myallustv['uterus'] . '</td>';
        $trRTube .= '<td>' . $myallustv['radnexa'] . '</td>';
        $trLTube .= '<td>' . $myallustv['ladnexa'] . '</td>';
        $trSmear .= '<td>' . $myallustv['pelvis'] . '</td>';
        $trNotes .= '<td>' . $myallustv['notes'] . '</td>';
    }

    $trDate .= '</tr>';
    $trUterus .= '</tr>';
    $trRTube .= '</tr>';
    $trLTube .= '</tr>';
    $trSmear .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trUterus;
    $table .= $trRTube;
    $table .= $trLTube;
    $table .= $trSmear;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function laparoscopy($patientId) {
    $table = '<table><tr><td>LAPAROSCOPY</td></tr>';
    $trDate = '<tr><td>Date</td>';
    $trUterus = '<tr><td>Uterus</td>';
    $trRTube = '<tr><td>R.adnexa</td>';
    $trLTube = '<tr><td>L.adnexa</td>';
    $trSmear = '<tr><td>Pelvis</td>';
    $trNotes = '<tr><td>Notes</td>';

    $alllaparoscopy = R::getAll('select laparoscopy.*, awusers.user_name as docname from laparoscopy,awusers where  laparoscopy.doctorid = awusers.user_id and laparoscopy.patientid = ? and laparoscopy.del = 0 and ( !isNull(`uterus`) or !isNull(`radnexa`) or !isNull(`ladnexa`) or !isNull(`pelvis`) or !isNull(`notes`))', [$patientId]);
    foreach ($alllaparoscopy as $myalllaparoscopy) {
        $trDate .= '<td>' . $myalllaparoscopy['sdate'] . '</td>';
        $trUterus .= '<td>' . $myalllaparoscopy['uterus'] . '</td>';
        $trRTube .= '<td>' . $myalllaparoscopy['radnexa'] . '</td>';
        $trLTube .= '<td>' . $myalllaparoscopy['ladnexa'] . '</td>';
        $trSmear .= '<td>' . $myalllaparoscopy['pelvis'] . '</td>';
        $trNotes .= '<td>' . $myalllaparoscopy['notes'] . '</td>';
    }

    $trDate .= '</tr>';
    $trUterus .= '</tr>';
    $trRTube .= '</tr>';
    $trLTube .= '</tr>';
    $trSmear .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trUterus;
    $table .= $trRTube;
    $table .= $trLTube;
    $table .= $trSmear;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function hysteroscopy($patientId) {
    $table = '<table><tr><td>HYSTEROSCOPY</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trUterus = '<tr><td>Cervix</td>';
    $trRTube = '<tr><td>Uterine Cavity</td>';
    $trLTube = '<tr><td>R.Ostium</td>';
    $trSmear = '<tr><td>L.Ostium</td>';
    $trNotes = '<tr><td>Notes</td>';

    $allhysteroscopy = R::getAll('select hysteroscopy.*, awusers.user_name as docname from hysteroscopy,awusers where  hysteroscopy.doctorid = awusers.user_id and hysteroscopy.patientid = ? and hysteroscopy.del = 0 and( !isNull(`cervix`) or !isNull(`uterine`) or !isNull(`rostium`) or !isNull(`lostium`) or !isNull(`notes`))', [$patientId]);
    foreach ($allhysteroscopy as $myallhysteroscopy) {
        $trDate .= '<td>' . $myallhysteroscopy['sdate'] . '</td>';
        $trUterus .= '<td>' . $myallhysteroscopy['cervix'] . '</td>';
        $trRTube .= '<td>' . $myallhysteroscopy['uterine'] . '</td>';
        $trLTube .= '<td>' . $myallhysteroscopy['rostium'] . '</td>';
        $trSmear .= '<td>' . $myallhysteroscopy['lostium'] . '</td>';
        $trNotes .= '<td>' . $myallhysteroscopy['notes'] . '</td>';
    }

    $trDate .= '</tr>';
    $trUterus .= '</tr>';
    $trRTube .= '</tr>';
    $trLTube .= '</tr>';
    $trSmear .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trUterus;
    $table .= $trRTube;
    $table .= $trLTube;
    $table .= $trSmear;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function mrict($patientId) {
    $table = '<table><tr><td>MRI/CT</td></tr>';
    $trDate = '<tr><td>Date</td>';
    $trUterus = '<tr><td>Uterus</td>';
    $trRTube = '<tr><td>R.adnexa</td>';
    $trLTube = '<tr><td>L.adnexa</td>';
    $trSmear = '<tr><td>Pelvis</td>';
    $trNotes = '<tr><td>Notes</td>';

    $allmrict = R::getAll('select mrict.*, awusers.user_name as docname from mrict,awusers where  mrict.doctorid = awusers.user_id and mrict.patientid = ? and mrict.del = 0 and ( !isNull(`uterus`) or !isNull(`radnexa`) or !isNull(`ladnexa`) or !isNull(`pelvis`) or !isNull(`notes`))', [$patientId]);
    foreach ($allmrict as $myallmrict) {
        $trDate .= '<td>' . $myallmrict['sdate'] . '</td>';
        $trUterus .= '<td>' . $myallmrict['uterus'] . '</td>';
        $trRTube .= '<td>' . $myallmrict['radnexa'] . '</td>';
        $trLTube .= '<td>' . $myallmrict['ladnexa'] . '</td>';
        $trSmear .= '<td>' . $myallmrict['pelvis'] . '</td>';
        $trNotes .= '<td>' . $myallmrict['notes'] . '</td>';
    }

    $trDate .= '</tr>';
    $trUterus .= '</tr>';
    $trRTube .= '</tr>';
    $trLTube .= '</tr>';
    $trSmear .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trUterus;
    $table .= $trRTube;
    $table .= $trLTube;
    $table .= $trSmear;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function hormones($patientId) {
    $table = '<table><tr><td>HORMONES</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trFSH = '<tr><td>FSH</td>';
    $trLH = '<tr><td>LH</td>';
    $trPRL = '<tr><td>PRL</td>';
    $trE2 = '<tr><td>E2</td>';
    $trAMH = '<tr><td>AMH</td>';
    $trFreeT = '<tr><td>FreeT</td>';
    $trTotalT = '<tr><td>TotalT</td>';
    $trP4 = '<tr><td>P4</td>';
    $trTSH = '<tr><td>TSH</td>';
    $trT3 = '<tr><td>T3</td>';
    $trT4 = '<tr><td>T4</td>';
    $trDHEAS = '<tr><td>DHEAS</td>';
    $trDHT = '<tr><td>DHT</td>';
    $trBHCG = '<tr><td>B-HCG</td>';
    $trInhibinB = '<tr><td>InhibinB</td>';
    $trASD = '<tr><td>ASD</td>';
    $trNotes = '<tr><td>Notes</td>';

    $allhormon = R::getAll('select hormon.*, awusers.user_name as docname from hormon,awusers where  hormon.doctorid = awusers.user_id and hormon.patientid = ? and hormon.del = 0 and(!isNull(`lh`) or !isNull(`prl`) or !isNull(`etwo`) or !isNull(`amh`) or !isNull(`freet`) or !isNull(`totalt`) or !isNull(`pfour`) or !isNull(`tsh`) or !isNull(`tthree`) or !isNull(`dht`) or !isNull(`bhcg`) or !isNull(`inhibinb`) or !isNull(`asd`) or !isNull(`tfour`) or !isNull(`dheas`) or !isNull(`fsh`) or !isNull(`notes`))', [$patientId]);
    foreach ($allhormon as $myallhormon) {
        $trDate .= '<td>' . $myallhormon['sdate'] . '</td>';
        $trFSH .= '<td>' . $myallhormon['fsh'] . '</td>';
        $trLH .= '<td>' . $myallhormon['lh'] . '</td>';
        $trPRL .= '<td>' . $myallhormon['prl'] . '</td>';
        $trE2 .= '<td>' . $myallhormon['etwo'] . '</td>';
        $trAMH .= '<td>' . $myallhormon['amh'] . '</td>';
        $trFreeT .= '<td>' . $myallhormon['freet'] . '</td>';
        $trTotalT .= '<td>' . $myallhormon['totalt'] . '</td>';
        $trP4 .= '<td>' . $myallhormon['pfour'] . '</td>';
        $trTSH .= '<td>' . $myallhormon['tsh'] . '</td>';
        $trT3 .= '<td>' . $myallhormon['tthree'] . '</td>';
        $trT4 .= '<td>' . $myallhormon['tfour'] . '</td>';
        $trDHEAS .= '<td>' . $myallhormon['dheas'] . '</td>';
        $trDHT .= '<td>' . $myallhormon['dht'] . '</td>';
        $trBHCG .= '<td>' . $myallhormon['bhcg'] . '</td>';
        $trInhibinB .= '<td>' . $myallhormon['inhibinb'] . '</td>';
        $trASD .= '<td>' . $myallhormon['asd'] . '</td>';
        $trNotes .= '<td>' . $myallhormon['notes'] . '</td>';
    }

    $trDate .= '</tr>';
    $trFSH .= '</tr>';
    $trLH .= '</tr>';
    $trPRL .= '</tr>';
    $trE2 .= '</tr>';
    $trAMH .= '</tr>';
    $trFreeT .= '</tr>';
    $trTotalT .= '</tr>';
    $trP4 .= '</tr>';
    $trTSH .= '</tr>';
    $trT3 .= '</tr>';
    $trT4 .= '</tr>';
    $trDHEAS .= '</tr>';
    $trDHT .= '</tr>';
    $trBHCG .= '</tr>';
    $trInhibinB .= '</tr>';
    $trASD .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trFSH;
    $table .= $trLH;
    $table .= $trPRL;
    $table .= $trE2;
    $table .= $trAMH;
    $table .= $trFreeT;
    $table .= $trTotalT;
    $table .= $trP4;
    $table .= $trTSH;
    $table .= $trT3;
    $table .= $trT4;
    $table .= $trDHEAS;
    $table .= $trDHT;
    $table .= $trBHCG;
    $table .= $trInhibinB;
    $table .= $trASD;
    $table .= $trNotes;

    $table .= '</table>';
    return $table;
}

function pathology($patientId) {
    $table = '<table><tr><td>PATHOLOGY</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trUterus = '<tr><td>Cytology</td>';
    $trRTube = '<tr><td>Histopathology</td>';

    $allpathology = R::getAll('select pathology.*, awusers.user_name as docname from pathology,awusers where  pathology.doctorid = awusers.user_id and pathology.patientid = ? and pathology.del = 0 and(!isNull(`cytology`) or !isNull(`histopathology`))', [$patientId]);
    foreach ($allpathology as $myallpathology) {
        $trDate .= '<td>' . $myallpathology['sdate'] . '</td>';
        $trUterus .= '<td>' . $myallpathology['cytology'] . '</td>';
        $trRTube .= '<td>' . $myallpathology['histopathology'] . '</td>';
    }

    $trDate .= '</tr>';
    $trUterus .= '</tr>';
    $trRTube .= '</tr>';

    $table .= $trDate;
    $table .= $trUterus;
    $table .= $trRTube;

    $table .= '</table>';
    return $table;
}

function visits($patientId) {
    $table = '<table><tr><td>Gyna</td></tr><tr><td>Visits</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trUterus = '<tr><td>Complaint</td>';
    $trRTube = '<tr><td>Diagnosis</td>';
    $trLTube = '<tr><td>Notes</td>';

    $allgyna = R::getAll('select gyna.* from gyna  where gyna.conditions = 0 and patientid = ? and ( complaint != "" or notes != "" or diagnosisid != "")', [$patientId]);
    foreach ($allgyna as $myallgyna) {
        $trDate .= '<td>' . $myallgyna['gynadate'] . '</td>';
        $trUterus .= '<td>' . $myallgyna['complaint'] . '</td>';
        $trRTube .= '<td>' . $myallgyna['diagnosisid'] . '</td>';
        $trLTube .= '<td>' . $myallgyna['notes'] . '</td>';
    }

    $trDate .= '</tr>';
    $trUterus .= '</tr>';
    $trRTube .= '</tr>';
    $trLTube .= '</tr>';

    $table .= $trDate;
    $table .= $trUterus;
    $table .= $trRTube;
    $table .= $trLTube;

    $table .= '</table>';
    return $table;
}

########stopped here 

function folliculometry($patientId) {
    $table = '<table><tr><td>Gyna - Folliculometry</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trDay = '<tr><td>Day</td>';
    $trEndo = '<tr><td>Endo</td>';
    $trUterusl = '<tr><td>Uterus (L)</td>';
    $trUterusw = '<tr><td>Uterus (W)</td>';
    $trUterusv = '<tr><td>Uterus (V)</td>';
    $trCervixl = '<tr><td>Cervix (L)</td>';
    $trCervixw = '<tr><td>Cervix (W)</td>';
    $trCervixv = '<tr><td>Cervix (V)</td>';
    $trOVARYLtl = '<tr><td>OVARY Lt (L)</td>';
    $trOVARYLtw = '<tr><td>OVARY Lt (W)</td>';
    $trOVARYLtv = '<tr><td>OVARY Lt (V)</td>';
    $trOVARYRtl = '<tr><td>OVARY Rt (L)</td>';
    $trOVARYRtw = '<tr><td>OVARY Rt (W)</td>';
    $trOVARYRtv = '<tr><td>OVARY Rt (V)</td>';

    $trLTovaryName = '<tr><td>LTovary (Name)</td>';
    $trLTovaryLength = '<tr><td>LTovary (Length)</td>';
    $trLTovaryWidth = '<tr><td>LTovary (Width)</td>';
    $trLTovaryVolume = '<tr><td>LTovary (Volume)</td>';

    $trRTovaryName = '<tr><td>Rtovary (Name)</td>';
    $trRTovaryLength = '<tr><td>Rtovary (Length)</td>';
    $trRTovaryWidth = '<tr><td>Rtovary (Width)</td>';
    $trRTovaryVolume = '<tr><td>Rtovary (Volume)</td>';

    $allgynaUS = R::findall('gynaus', 'deleted = ? and patientid = ? and (!isNull(day) or !isNull(endo) or !isNull(ovrayll) or !isNull(ovraylw) or !isNull(ovraylv) or !isNull(ovraylno) or !isNull(ovraylsize) or !isNull(ovrayrl) or !isNull(ovrayrw) or !isNull(ovrayrv) or !isNull(ovrayrno) or !isNull(ovrayrsize) or !isNull(uterusl) or !isNull(uterusw) or !isNull(uterusv) or !isNull(cervixl) or !isNull(cervixw) or !isNull(cervixv) or !isNull(notes))', [0, $patientId]);
    foreach ($allgynaUS as $us) {
        $focilsr = R::findall('gynausficils', 'gynausid = ? and type = ?', [$us->id, 1]);
        $us->focilsr = $focilsr;
        $focilsl = R::findall('gynausficils', 'gynausid = ? and type = ?', [$us->id, 0]);
        $us->focilsl = $focilsl;

        $trDate .= '<td>' . $us->date . '</td>';
        $trDay .= '<td>' . $us->day . '</td>';
        $trEndo .= '<td>' . $us->endo . '</td>';
        $trUterusl .= '<td>' . $us->uterusl . '</td>';
        $trUterusw .= '<td>' . $us->uterusw . '</td>';
        $trUterusv .= '<td>' . $us->uterusv . '</td>';
        $trCervixl .= '<td>' . $us->cervixl . '</td>';
        $trCervixw .= '<td>' . $us->cervixw . '</td>';
        $trCervixv .= '<td>' . $us->cervixv . '</td>';
        $trOVARYLtl .= '<td>' . $us->ovrayll . '</td>';
        $trOVARYLtw .= '<td>' . $us->ovraylw . '</td>';
        $trOVARYLtv .= '<td>' . $us->ovraylv . '</td>';
        $trOVARYRtl .= '<td>' . $us->ovrayrl . '</td>';
        $trOVARYRtw .= '<td>' . $us->ovrayrw . '</td>';
        $trOVARYRtv .= '<td>' . $us->ovrayrv . '</td>';
        $allfocilsrName = '';
        $allfocilsrLength = '';
        $allfocilsrWidth = '';
        $allfocilsrVolume = '';
        $allfocilslName = '';
        $allfocilslLength = '';
        $allfocilslWidth = '';
        $allfocilslVolume = '';
        $i = 1;
        foreach ($focilsr as $fR) {
            if ($i != 1) {
                $allfocilsrName .= ' - ' . $fR->name;
                $allfocilsrLength .= ' - ' . $fR->length;
                $allfocilsrWidth .= ' - ' . $fR->width;
                $allfocilsrVolume .= ' - ' . $fR->volume;
            } else {
                $allfocilsrName .= $fR->name;
                $allfocilsrLength .= $fR->length;
                $allfocilsrWidth .= $fR->width;
                $allfocilsrVolume .= $fR->volume;
            }
            $i++;
        }
        $i = 1;
        foreach ($focilsl as $fL) {
            if ($i != 1) {
                $allfocilslName .= ' - ' . $fL->name;
                $allfocilslLength .= ' - ' . $fL->length;
                $allfocilslWidth .= ' - ' . $fL->width;
                $allfocilslVolume .= ' - ' . $fL->volume;
            } else {
                $allfocilslName .= $fL->name;
                $allfocilslLength .= $fL->length;
                $allfocilslWidth .= $fL->width;
                $allfocilslVolume .= $fL->volume;
            }
            $i++;
        }
        $trRTovaryName .= '<td>' . $allfocilsrName . '</td>';
        $trRTovaryLength .= '<td>' . $allfocilsrLength . '</td>';
        $trRTovaryWidth .= '<td>' . $allfocilsrWidth . '</td>';
        $trRTovaryVolume .= '<td>' . $allfocilsrVolume . '</td>';

        $trLTovaryName .= '<td>' . $allfocilslName . '</td>';
        $trLTovaryLength .= '<td>' . $allfocilslLength . '</td>';
        $trLTovaryWidth .= '<td>' . $allfocilslWidth . '</td>';
        $trLTovaryVolume .= '<td>' . $allfocilslVolume . '</td>';
    }



    $trDate .= '</tr>';
    $trDay .= '</tr>';
    $trEndo .= '</tr>';
    $trUterusl .= '</tr>';
    $trUterusw .= '</tr>';
    $trUterusv .= '</tr>';
    $trCervixl .= '</tr>';
    $trCervixw .= '</tr>';
    $trCervixv .= '</tr>';
    $trOVARYLtl .= '</tr>';
    $trOVARYLtw .= '</tr>';
    $trOVARYLtv .= '</tr>';
    $trOVARYRtl .= '</tr>';
    $trOVARYRtw .= '</tr>';
    $trOVARYRtv .= '</tr>';

    $trLTovaryName .= '</tr>';
    $trLTovaryLength .= '</tr>';
    $trLTovaryWidth .= '</tr>';
    $trLTovaryVolume .= '</tr>';

    $trRTovaryName .= '</tr>';
    $trRTovaryLength .= '</tr>';
    $trRTovaryWidth .= '</tr>';
    $trRTovaryVolume .= '</tr>';

    $table .= $trDate;
    $table .= $trDay;
    $table .= $trEndo;
    $table .= $trUterusl;
    $table .= $trUterusw;
    $table .= $trUterusv;
    $table .= $trCervixl;
    $table .= $trCervixw;
    $table .= $trCervixv;
    $table .= $trOVARYLtl;
    $table .= $trOVARYLtw;
    $table .= $trOVARYLtv;
    $table .= $trOVARYRtl;
    $table .= $trOVARYRtw;
    $table .= $trOVARYRtv;

    $table .= $trLTovaryName;
    $table .= $trLTovaryLength;
    $table .= $trLTovaryWidth;
    $table .= $trLTovaryVolume;

    $table .= $trRTovaryName;
    $table .= $trRTovaryLength;
    $table .= $trRTovaryWidth;
    $table .= $trRTovaryVolume;

    $table .= '</table>';
    return $table;
}

function investigation($patientId) {
    $table = '<table><tr><td>Investigation</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trInvName = '<tr><td>Investigations</td>';

    $idates = R::getAll('SELECT DISTINCT date  FROM gynainvestigation WHERE deleted = ? and patientid = ?  order by date', [0, $patientId]);
    foreach ($idates as $date) {
        $invs = '';
        ## all invs of certain patient
        $PatientInvByDate = R::findall('gynainvestigation', 'deleted = ? and patientid = ? and date = ? ', [0, $patientId, $date['date']]);
        foreach ($PatientInvByDate as $in) {
            $invest = R::load('invests', $in->investid);
            if ($invs == '') {
                $invs .= $invest->name . ' : ' . $in->investresult;
            } else {
                $invs .= ' , ' . $invest->name . ' : ' . $in->investresult;
            }
        }

        $trDate .= '<td>' . $date['date'] . '</td>';
        $trInvName .= '<td>' . $invs . '</td>';
    }

    $trDate .= '</tr>';
    $trInvName .= '</tr>';

    $table .= $trDate;
    $table .= $trInvName;

    $table .= '</table>';
    return $table;
}

function treatment($patientId) {
    $table = '<table><tr><td>Treatment</td></tr>';
    $trDate = '<tr><td>Date</td>';
    $trDrugName = '<tr><td>Drugs</td>';

    $dates = R::getAll('SELECT DISTINCT date  FROM gynadrugs WHERE deleted = ? and patientid = ?  order by date', [0, $patientId]);
    foreach ($dates as $date) {
        $drugs = '';
        ## all prescription of certain patient
        $PatientPresByDate = R::findall('gynadrugs', 'deleted = ? and patientid = ? and date = ? ', [0, $patientId, $date['date']]);
        foreach ($PatientPresByDate as $pres) {
            $dd = R::load('drugs', $pres->drugid);
            if ($drugs == '') {
                $drugs .= $dd->drugname;
            } else {
                $drugs .= ' , ' . $dd->drugname;
            }
        }
        $trDate .= '<td>' . $date['date'] . '</td>';
        $trDrugName .= '<td>' . $drugs . '</td>';
    }


    $trDate .= '</tr>';
    $trDrugName .= '</tr>';

    $table .= $trDate;
    $table .= $trDrugName;

    $table .= '</table>';
    return $table;
}

function antenatal($patientId) {
    $table = '<table><tr><td>Antenatal Visits</td></tr></table>';
    $i = 1;

    $allObj = R::findAll('mainantenental', ' patientid = ?', [$patientId]);
    foreach ($allObj as $mainObj) {
        $table .= '<table><tr><td>Pregnancy No ' . $i . ' Visits </td></tr>';

        $trDate = '<tr><td>Date</td>';
        $trW = '<tr><td>Week</td>';
        $trComplaint = '<tr><td>Complaint</td>';
        $trWt = '<tr><td>Weight</td>';
        $trBp = '<tr><td>Blood Pressure</td>';
        $trNotes = '<tr><td>Notes</td>';
        ####visits  
        $allantenalvisit = R::findall('antenalvisit', 'conditions = 0 AND mainantenentalid = ?', [$mainObj->id]);
        foreach ($allantenalvisit as $myvisit) {
            $date1 = new DateTime($myvisit->antenaldate);
            $date2 = new DateTime($mainObj->lmp);
            $interval = $date1->diff($date2);

            $trDate .= '<td>' . $myvisit->antenaldate . '</td>';
            $trW .= '<td>' . floor($interval->days / 7) . '</td>';
            $trComplaint .= '<td>' . $myvisit->complaint . '</td>';
            $trWt .= '<td>' . $myvisit->wt . '</td>';
            $trBp .= '<td>' . $myvisit->bp . '</td>';
            $trNotes .= '<td>' . $myvisit->notes . '</td>';
        }
        $trDate .= '</tr>';
        $trW .= '</tr>';
        $trComplaint .= '</tr>';
        $trWt .= '</tr>';
        $trBp .= '</tr>';
        $trNotes .= '</tr>';

        $table .= $trDate;
        $table .= $trW;
        $table .= $trComplaint;
        $table .= $trWt;
        $table .= $trBp;
        $table .= $trNotes;
        $table .= '</table>';

        $table .= antenatalus($patientId, $mainObj->id);
        $table .= antenatallab($patientId, $mainObj->id);
        $table .= antenatalttt($patientId, $mainObj->id);

        $i++;
    }

    return $table;
}

function antenatalttt($patientId, $mainObjId) {
    $table = '<table><tr><td>TTT</td></tr>';
    $trDate = '<tr><td>Date</td>';
    $trDrugName = '<tr><td>Drugs</td>';
    ### TTT
    $tdates = R::getAll('SELECT DISTINCT date  FROM mainantenentaldrugs WHERE deleted = ? and patientid = ? and mainantenatalid = ?  order by date', [0, $patientId, $mainObjId]);
    $drugs = '';
    foreach ($tdates as $date) {
        ## all prescription of certain patient
        $PatientPresByDate = R::findall('mainantenentaldrugs', 'deleted = ? and patientid = ? and date = ?  and mainantenatalid = ?', [0, $patientId, $date['date'], $mainObjId]);
        foreach ($PatientPresByDate as $pres) {
            $dd = R::load('drugs', $pres->drugid);
            if ($drugs == '') {
                $drugs .= $dd->drugname;
            } else {
                $drugs .= ' , ' . $dd->drugname;
            }
        }
        $trDate .= '<td>' . $date['date'] . '</td>';
        $trDrugName .= '<td>' . $drugs . '</td>';
    }

    $trDate .= '</tr>';
    $trDrugName .= '</tr>';

    $table .= $trDate;
    $table .= $trDrugName;
    $table .= '</table>';

    return $table;
}

function antenatalus($patientId, $mainObjId) {
    $table = '<table><tr><td>US</td></tr>';

    $trDate = '<tr><td>Date</td>';
    $trNGA = '<tr><td>N(GA)</td>';
    $trGS = '<tr><td>GS</td>';
    $trCRL = '<tr><td>CRL</td>';
    $trFHR = '<tr><td>FHR</td>';
    $trBPD = '<tr><td>BPD</td>';
    $trFL = '<tr><td>FL</td>';
    $trPlacenta = '<tr><td>Placenta</td>';
    $trFWT = '<tr><td>FWT</td>';
    $trNotes = '<tr><td>Notes</td>';

    ###us 
    $allAntUS = R::findall('mainantenentalus', 'deleted = ? and patientid = ? and mainantenatalid = ? ', [0, $patientId, $mainObjId]);
    foreach ($allAntUS as $us) {
        $trDate .= '<td>' . $us->date . '</td>';
        $trNGA .= '<td>' . $us->nga . '</td>';
        $trGS .= '<td>' . $us->gs . '</td>';
        $trCRL .= '<td>' . $us->crl . '</td>';
        $trFHR .= '<td>' . $us->fhr . '</td>';
        $trBPD .= '<td>' . $us->bpd . '</td>';
        $trFL .= '<td>' . $us->fl . '</td>';
        $trPlacenta .= '<td>' . $us->placenta . '</td>';
        $trFWT .= '<td>' . $us->fwt . '</td>';
        $trNotes .= '<td>' . $us->notes . '</td>';
    }

    $trDate .= '</tr>';
    $trNGA .= '</tr>';
    $trGS .= '</tr>';
    $trCRL .= '</tr>';
    $trFHR .= '</tr>';
    $trBPD .= '</tr>';
    $trFL .= '</tr>';
    $trPlacenta .= '</tr>';
    $trFWT .= '</tr>';
    $trNotes .= '</tr>';

    $table .= $trDate;
    $table .= $trNGA;
    $table .= $trGS;
    $table .= $trCRL;
    $table .= $trFHR;
    $table .= $trBPD;
    $table .= $trFL;
    $table .= $trPlacenta;
    $table .= $trFWT;
    $table .= $trNotes;
    $table .= '</table>';
    return $table;
}

function antenatallab($patientId, $mainObjId) {
    $table = '<table><tr><td>Lab</td></tr>';
    $trDate = '<tr><td>Date</td>';
    $trInvName = '<tr><td>Investigations</td>';

    $invsdates = R::getAll('SELECT DISTINCT date  FROM mainantenentalinvest WHERE deleted = ? and patientid = ? and mainantenatalid = ?  order by date', [0, $patientId, $mainObjId]);

    foreach ($invsdates as $date) {
        $invs = '';
        ## all invs of certain patient
        $PatientInvByDate = R::findall('mainantenentalinvest', 'deleted = ? and patientid = ? and date = ? and mainantenatalid = ? ', [0, $patientId, $date['date'], $mainObjId]);
        foreach ($PatientInvByDate as $in) {
            $invest = R::load('invests', $in->investid);
            if ($invs == '') {
                $invs .= $invest->name . ' : ' . $in->investresult;
            } else {
                $invs .= ' , ' . $invest->name . ' : ' . $in->investresult;
            }
        }
        $trDate .= '<td>' . $date['date'] . '</td>';
        $trInvName .= '<td>' . $invs . '</td>';
    }

    $trDate .= '</tr>';
    $trInvName .= '</tr>';

    $table .= $trDate;
    $table .= $trInvName;
    $table .= '</table>';
    return $table;
}
