<?php

/*
 * awframework from aw.inc present aw controller
 * it will help you develop easy and fast with secure tools
 * you can edit and add what you feel right
 * don't change in strucure of file
 */

require_once("imp/_imp.php");

class Controllers {

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

    // it will run in everytime with
    // default requried
    public function __construct() {
        require_once("../public/aw_config.php");
        require_once("imp/_autho.php"); //general functions
        $this->smarty = $smarty;
        $this->hosturl = $hosturl;

        //here name of controll to known
        $this->controllname = 'operations';
        $this->shcontrollname = 'Home';
        $this->smarty->assign('controllname', $this->controllname);
        $this->smarty->assign('shcontrollname', $this->shcontrollname);

        //breadcrumbs
        require_once("../../_library/plugins/Breadcrumbs/Breadcrumbs.php");
        $acty = filter_input(INPUT_GET, 'ac');
        $bc = new breadcrumbs($hosturl, '', '', $acty);
        $bc->crumbs();
        $breadcrumbs = $bc->breadcrumbs;
        $smarty->assign('breadcrumbs', $breadcrumbs);

        # here show the active page in menu
        // array called active[] with level of active element
        $active[0] = 'Operations'; //controller name or tab name
        $this->active = $active;

        R::ext('xdispense', function ($type) {
            return R::getRedBean()->dispense($type);
        });


        //here will call all php pages
        require_once("_header.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");
    }

    //here the frist page and
    //the frist action in this class
    public function index() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //here will load the menu show
        $allPatient = R::findAll('patients');
        $this->smarty->assign('allPatient', $allPatient);

        $today = date("Y/m/d");
        $this->smarty->assign('today', date('Y/m/d', strtotime($today)));

        $patientid = filter_input(INPUT_GET, "patientid");
        if (empty($patientid)) {
            $allData = R::findAll('operations', 'date = ?', [$today]);
            $allData2 = R::findAll('hysteroscopy', 'date = ?', [$today]);
            $allData3 = R::findAll('laparoscopy', 'date = ?', [$today]);
        } else {

            $allData = R::findAll('operations', " LEFT JOIN infertilitysheet
         ON operations.infertilitysheetid = infertilitysheet.id where 1 and  date = '$today' and patientid = $patientid ");
            $allData2 = R::findAll('hysteroscopy', " where 1 and  date = '$today' and patientid = $patientid ");
            $allData3 = R::findAll('laparoscopy', " where 1 and  date = '$today' and patientid = $patientid ");
            $lastVisitData = R::findOne('lastvisit', 'patientid = ? order by id desc ', [$patientid]);
            $lastVisit = R::dispense('lastvisit');
            $lastVisit->patientid = $patientid;
            $lastVisit->control = $this->controllname;
            if ($lastVisitData->patientid == $patientid) {
                $lastVisit->id = $lastVisitData->id;
            }
            R::store($lastVisit);
            $this->smarty->assign('patientid', $patientid);
        }


        $this->smarty->assign('allData', $allData);
        foreach ($allData as $data) {
            $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
            $data->info = R::load('patients', $infertilitysheet->patientid);
            $data->patientid = $infertilitysheet->patientid;
            $data->operationc = R::findAll('operation', "id in (0$data->operation)");
            $data->histopathc = R::findAll('histopath', "id in (0$data->histopath)");
            $data->placec = R::load('place', $data->place);
        }


        $this->smarty->assign('allData2', $allData2);
        foreach ($allData2 as $data) {
            $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
            $data->info = R::load('patients', $infertilitysheet->patientid);
            $data->patientid = $infertilitysheet->patientid;
            $data->copyplace = R::load('copyplace', $data->copyplace);
        }


        $this->smarty->assign('allData3', $allData3);
        foreach ($allData3 as $data) {
            $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
            $data->info = R::load('patients', $infertilitysheet->patientid);
            $data->patientid = $infertilitysheet->patientid;
            $data->laparplace = R::load('laparplace', $data->laparplace);
        }

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('reports2/operations.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function Add() {


        $table = filter_input(INPUT_POST, 'table');
        $id = filter_input(INPUT_POST, 'id');
        $name = filter_input(INPUT_POST, 'name');
        $value = filter_input(INPUT_POST, 'value');

        try {
            $tableadd = R::exec("update $table set $name = '" . $value . "' where id = $id");
            //echo $tableadd;
        } catch (Exception $e) {
            //echo $e->getMessage();
        }
    }

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

        //R::debug(TRUE);
        $fromdate = filter_input(INPUT_POST, 'fromdate');
        $todate = filter_input(INPUT_POST, 'todate');
        $patientid = filter_input(INPUT_POST, 'patientid');
        $this->smarty->assign('patientid', $patientid);
        $todate = date("Y/m/d", strtotime($todate));
        $searchQuery = '';
        if ($patientid) {
            $searchQuery = " and patientid = " . $patientid . " ";
        }
        if ($fromdate) {
            $fromdate = date("Y/m/d", strtotime($fromdate));
            $searchQuery .= " and  date >= '$fromdate' and date <=  '$todate' ";
        }
        $allData = R::findAll('operations', 'LEFT JOIN infertilitysheet
         ON operations.infertilitysheetid = infertilitysheet.id where 1 ' . $searchQuery . '');
        $allData2 = R::findAll('hysteroscopyinfertility', ' LEFT JOIN infertilitysheet
         ON hysteroscopyinfertility.infertilitysheetid = infertilitysheet.id  where 1 ' . $searchQuery . '');
        $allData3 = R::findAll('laparoscopyinfertility', ' LEFT JOIN infertilitysheet
         ON laparoscopyinfertility.infertilitysheetid = infertilitysheet.id where 1 ' . $searchQuery . '');
        $this->smarty->assign('allData', $allData);
        foreach ($allData as $data) {
            $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
            $data->info = R::load('patients', $infertilitysheet->patientid);
            $data->patientid = $infertilitysheet->patientid;
            $data->operationc = R::findAll('operation', "id in (0$data->operation)");
            $data->histopathc = R::findAll('histopath', "id in (0$data->histopath)");
            $data->placec = R::load('place', $data->place);
        }

        $this->smarty->assign('allData2', $allData2);
        foreach ($allData2 as $data) {
            $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
            $data->info = R::load('patients', $infertilitysheet->patientid);
            $data->patientid = $infertilitysheet->patientid;
            $data->copyplace = R::load('copyplace', $data->copyplace);
        }

        $this->smarty->assign('allData3', $allData3);
        foreach ($allData3 as $data) {
            $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
            $data->info = R::load('patients', $infertilitysheet->patientid);
            $data->patientid = $infertilitysheet->patientid;
            $data->laparplace = R::load('laparplace', $data->laparplace);
        }

        $this->smarty->display('reports2/operationssearch.html');
    }

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

        //R::debug(TRUE);
        $fromdate = filter_input(INPUT_POST, 'fromdate');
        $todate = filter_input(INPUT_POST, 'todate');
        $patientid = filter_input(INPUT_POST, 'patientid');
        $this->smarty->assign('patientid', $patientid);
        $todate = date("Y/m/d", strtotime($todate));
        $searchQuery = '';
        if ($patientid) {
            $searchQuery .= " and patientid = " . $patientid . " ";
        }
        if ($fromdate) {
            $fromdate = date("Y/m/d", strtotime($fromdate));
            $searchQuery .= " and  date >= '$fromdate' and date <=  '$todate' ";
        }
        $allData = R::findAll('operations', 'LEFT JOIN infertilitysheet
         ON operations.infertilitysheetid = infertilitysheet.id where 1 ' . $searchQuery . '');
        $allData2 = R::findAll('hysteroscopyinfertility', ' LEFT JOIN infertilitysheet
         ON hysteroscopyinfertility.infertilitysheetid = infertilitysheet.id  where 1 ' . $searchQuery . '');
        $allData3 = R::findAll('laparoscopyinfertility', ' LEFT JOIN infertilitysheet
         ON laparoscopyinfertility.infertilitysheetid = infertilitysheet.id where 1 ' . $searchQuery . '');
        $this->smarty->assign('allData', $allData);
        foreach ($allData as $data) {
            $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
            $data->info = R::load('patients', $infertilitysheet->patientid);
            $data->operationc = R::findAll('operation', "id in ($data->operation)");
            $data->histopathc = R::findAll('histopath', "id in ($data->histopath)");
            $data->placec = R::load('place', $data->place);
        }

        $this->smarty->assign('allData2', $allData2);
        foreach ($allData2 as $data) {
            $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
            $data->info = R::load('patients', $infertilitysheet->patientid);
            $data->copyplace = R::load('copyplace', $data->copyplace);
        }

        $this->smarty->assign('allData3', $allData3);
        foreach ($allData3 as $data) {
            $infertilitysheet = R::load('infertilitysheet', $data->infertilitysheetid);
            $data->info = R::load('patients', $infertilitysheet->patientid);
            $data->laparplace = R::load('laparplace', $data->laparplace);
        }
        $this->smarty->display('reports2/operationsprint.html');
    }

    public function onesetup() {

        //check login
        autho::checkautho($this->hosturl);

        try {
            //delete all but with only default
            #1 clean roles only managment
            #2 clean menu only default
            #3 clean controls only default
            #4 users clean users
            #delete all menus
            $menus = R::findAll('awmenu', 'id > 15');
            #delete from awrolemenu
            foreach ($menus as $one) {
                //get propes
                $rolemenu = R::findAll('awrolemenu', 'menu_id = ?', [$one->id]);
                R::trashAll($rolemenu);
            }
            R::trashAll($menus);
            #delete controles
            $controlls = R::findAll('awcontroll', 'id > 4 and id < 18');
            foreach ($controlls as $one) {
                //get propes
                $inprop = R::findAll('awcontrollprop', 'awcontroll_id = ?', [$one->id]);
                #delete from awrolecontroleprop
                foreach ($inprop as $one) {
                    //get propes
                    $roleprop = R::findAll('awrolecontrollprop', 'controllprop_id = ?', [$one->id]);
                    R::trashAll($roleprop);
                }
                R::trashAll($inprop);
            }
            R::trashAll($controlls);
            #delete othre roles
            $roles = R::findAll('awrole', 'id > 1');
            R::trashAll($roles);
            #delete other users
            //$users = R::findAll('awusers', 'user_id > 1');
            //R::exec('Delete from awusers where user_id > 1');
            //R::trashAll($users);
            ############################
            //new one
            $menusx = R::findAll('awmenu', ' id = 4 or id = 5 or id = 7 or id = 8 or id = 10 or id = 11 or id = 13 or id = 14 or id = 15 ');
            #delete from awrolemenu
            foreach ($menusx as $one) {
                //get propes
                $rolemenu = R::findAll('awrolemenu', 'menu_id = ?', [$one->id]);
                R::trashAll($rolemenu);
            }
            R::trashAll($menusx);

            print_r('trash all , install is good');
        } catch (Exception $ex) {
            print_r('something go wrong  , try again');
        }
    }

    ###########################  Heba   => Operation Waiting List ##############################

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

        $this->smarty->assign('today', date('Y/m/d'));

        $places = R::findAll('place', 'del is null ');
        $this->smarty->assign('places', $places);

        $operations = R::findAll('operation', 'del is null ');
        $this->smarty->assign('operations', $operations);

        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('operation/waitinglist.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function deldataselect() {
        //check login
        autho::checkautho($this->hosturl);

        $table = filter_input(INPUT_POST, 'table');
        $id = filter_input(INPUT_POST, 'id');
        $celtables = R::load($table, $id);
        $celtables->del = 1;
        try {
            $inserted = R::store($celtables);
            echo $inserted;
        } catch (Exception $e) {
            echo 0;
        }
    }

    public function addInList() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //prepar wife data insert
        $patientId = filter_input(INPUT_POST, 'patientid');
        $opDate = date('Y/m/d', strtotime(filter_input(INPUT_POST, 'opdate')));
        $place = filter_input(INPUT_POST, 'placeW');
        $notes = filter_input(INPUT_POST, "notes");

        $operation = implode(',', $_POST['operationW']);

        session_start();

        $insertDataVisits = R::xdispense('op_wait_list');
        $insertDataVisits->patientid = $patientId;
        $insertDataVisits->opdate = $opDate;
        $insertDataVisits->operation = $operation;
        $insertDataVisits->place = $place;
        $insertDataVisits->notes = $notes;
        $insertDataVisits->deleted = 0;
        $insertDataVisits->createdate = date('Y-m-d h:i:s');
        $insertDataVisits->user_id = $_SESSION['user_id'];

        try {
            $insert = R::store($insertDataVisits);

            if ($insert) {
                echo 1;
            } else {
                echo -1;
            }
        } catch (Exception $ex) {
            echo -1;
        }
    }

    function reloadOpVisits() {

        $dateFrom = filter_input(INPUT_POST, "date_from");
        $dateTo = filter_input(INPUT_POST, "date_to");
        $patientId = filter_input(INPUT_POST, "patientId");
        $this->loadVisits($dateFrom, $dateTo, $patientId);
    }

    function loadVisits($dateFrom, $dateTo, $patientId) {
        if ($patientId > 0) {
            $allvisit = $this->visitsFuture($patientId);
            $this->smarty->assign('allvisit', $allvisit);
            $this->smarty->display('operation/listdivfut.html');
        } else {
            if ($dateFrom != '00-00-0000' && !empty($dateFrom)) {
                $dateFrom = date('Y/m/d', strtotime($dateFrom));
            } else {
                $dateFrom = '0000-00-00';
            }

            if ($dateTo != '00-00-0000' && !empty($dateTo)) {
                $dateTo = date('Y/m/d', strtotime($dateTo));
            } else {
                $dateTo = date('Y/m/d');
            }

            $allvisit = $this->listVisits($dateFrom, $dateTo);
            $this->smarty->assign('allvisit', $allvisit);
            $this->smarty->display('operation/listdiv.html');
        }
    }

    function visitsFuture($patientId) {
        $date = date('Y/m/d');
        $sql = '  and  list.opdate  >= "' . $date . '"    and  list.patientid =  ' . $patientId . ' ORDER BY list.opdate ASC';
        $allvisit = $this->listSqlEx($sql);
        return $allvisit;
    }

    function listVisits($dateFrom, $dateTo) {

        $result = array();

        $begin = new DateTime($dateFrom);
        $end = new DateTime($dateTo . ' +1 day');

        $interval = DateInterval::createFromDateString('1 day');
        $period = new DatePeriod($begin, $interval, $end);

        foreach ($period as $dt) {
            $dayDate = $dt->format("Y-m-d");
            $dayName = $this->getDayNameFnAr($dayDate);
            $dayDateAll = $dayName . ' : ' . $dayDate;

            $sql = ' and   list.opdate  =  "' . $dayDate . '"    ORDER BY list.id ASC';
            $allvisit = $this->listSqlEx($sql);

            if (count($allvisit) > 0) {
                $result[$dayDateAll] = $allvisit;
            }
        }

        return $result;
    }

    function listSqlEx($sqlExt) {
        $sql = '       select  list.id as id   , list.operation as  operationIds  , place.title as  place
                            , list.notes   , list.opdate  , patients.wifename  as patientName   
                             , patients.statusno  as patientNo   , patients.husdandname  as husbandName 
                             , patients.address, patients.phone , "" as  operation
                            
                            from      op_wait_list       list 
                            left join   place            on place.id = list.place   
                            join patients                on patients.id = list.patientid


                    where    list.deleted = 0     ' . $sqlExt;

        $allvisit = R::getAll($sql);
        $visits = $this->listCommon($allvisit);
        return $visits;
    }

    function listCommon($allvisit) {
        $j = 0;
        foreach ($allvisit as $data) {
            $operationIds = explode(',', $data['operationIds']);
            $op = '';
            $i = 1;
            foreach ($operationIds as $id) {
                $operation = R::load('operation', $id);
                if ($i > 1) {
                    $op .= ' , ';
                }
                $op .= $operation->title;
                $i++;
            }
            $allvisit[$j]['operation'] = $op;
            $j++;
        }
        return $allvisit;
    }

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

        $id = filter_input(INPUT_POST, 'id');
        try {
            $obj = R::load('op_wait_list', $id);
            $obj->deleted = 1;
            R::store($obj);
            echo 1;
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    public function editVisit() {
        $visitId = filter_input(INPUT_POST, "visitId");
        $visit = R::load('op_wait_list', $visitId);

        $visit->opdate = date("Y/m/d", strtotime($visit->opdate));
        $patient = R::getRow("SELECT * FROM patients WHERE id = $visit->patientid");

        $result = array(
            "opdate" => date("Y/m/d", strtotime($visit->opdate)),
            "patientid" => $visit->patientid,
            "statusno" => $patient['statusno'],
            "operation" => $visit->operation,
            "place" => $visit->place,
            "notes" => $visit->notes
        );

        echo json_encode($result);
    }

    public function updatevisit() {
//check login
        autho::checkautho($this->hosturl);

        $visitId = filter_input(INPUT_POST, "mVisitId");
        $patientId = filter_input(INPUT_POST, 'patientid');
        $opDate = date('Y/m/d', strtotime(filter_input(INPUT_POST, 'opdate')));
        $place = filter_input(INPUT_POST, 'placeW');
        $notes = filter_input(INPUT_POST, "notes");

        $operation = implode(',', $_POST['operationW']);

        $visit = R::load('op_wait_list', $visitId);

        $visit->patientid = $patientId;
        $visit->opdate = $opDate;
        $visit->operation = $operation;
        $visit->place = $place;
        $visit->notes = $notes;

        R::store($visit);

        echo $visitId;
    }

    private function getDayNameFnAr($date) {
        $timestamp = strtotime($date);

        $day = date('w', $timestamp);



        switch ($day) {
            case 0:
                $name = 'الأحد  ';
                break;
            case 1:
                $name = ' الإثنين';
                break;
            case 2:
                $name = ' الثلاثاء';
                break;
            case 3:
                $name = 'الأربعاء ';
                break;
            case 4:
                $name = 'الخميس  ';
                break;
            case 5:
                $name = 'الجمعة ';
                break;
            case 6:
                $name = 'السبت ';
                break;
        }

        return $name;
    }

    public function addnewrecord() {
//check login
        autho::checkautho($this->hosturl);

//vars here
        $table = filter_input(INPUT_POST, 'selectId');
        $name = filter_input(INPUT_POST, 'new_name');

        $obj_id = filter_input(INPUT_POST, 'id');
        $tableName = filter_input(INPUT_POST, 'tableName');
        $colName = filter_input(INPUT_POST, 'colName');

        try {

            $record = R::xdispense($table);
            $record->title = $name;
            $id = R::store($record);

            if ($obj_id > 0) {

                $obj = R::load($tableName, $obj_id);
                $obj->$colName = $id;
                R::store($obj);
            }


            echo $id;
        } catch (Exception $e) {
            echo $e;
        }
    }

    // at the end of class call
    public function __destruct() {
        //close connection
        R::close();
    }

}
