<?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("../../core/controllers/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("../../core/controllers/imp/_autho.php"); //general functions
        $this->smarty = $smarty;
        $this->hosturl = $hosturl;

        //here name of controll to known
        $this->controllname = 'drugs';
        $this->shcontrollname = 'drugs';
        $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] = 'pharmacy'; //controller name or tab name
        $active[1] = 'drugs'; //controller name
// do name  // switch($do)
        switch ($acty) {
            case '':$active[2] = 'show';
                break;
            case 'show':$active[2] = 'show';
                break;
            default :$active[2] = 'show';
                break;
        }
        $this->active = $active;


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

    //here the frist page and
    //the frist action in this class
    public function index() {
        //check login
        autho::checkautho($this->hosturl . "/../core");
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //here will load the menu show
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('medicineview/drugs.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

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

        $sIndexColumn = "id";

        /* DB table to use */
        $sTable = "drugs";


        $aColumns = array('id', 'drugcat', 'drugname', 'drugtype', 'drugdos', 'minimumbalance');

        // Indexed column (used for fast and accurate table cardinality)

        /*
         * Paging
         */
        $sLimit = "";
        if (isset($_GET['iDisplayStart']) && $_GET['iDisplayLength'] != '-1') {
            $sLimit = "LIMIT " . intval($_GET['iDisplayStart']) . ", " .
                    intval($_GET['iDisplayLength']);
        }


        /*
         * Ordering
         */
        $sOrder = "";
        if (isset($_GET['iSortCol_0'])) {
            $sOrder = "ORDER BY  ";
            for ($i = 0; $i < intval($_GET['iSortingCols']); $i++) {
                if ($_GET['bSortable_' . intval($_GET['iSortCol_' . $i])] == "true") {
                    $sOrder .= $aColumns[intval($_GET['iSortCol_' . $i])] . "
                    " . ($_GET['sSortDir_' . $i] === 'asc' ? 'asc' : 'desc') . ", ";
                }
            }

            $sOrder = substr_replace($sOrder, "", -2);
            if ($sOrder == "ORDER BY") {
                $sOrder = "";
            }
        }


        /*
         * Filtering
         * NOTE this does not match the built-in DataTables filtering which does it
         * word by word on any field. It's possible to do here, but concerned about efficiency
         * on very large tables, and MySQL's regex functionality is very limited
         */
        $sWhere = "";
        if (isset($_GET['sSearch']) && $_GET['sSearch'] != "") {
            $sWhere = "WHERE (";
            for ($i = 0; $i < count($aColumns); $i++) {
                if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true") {
                    $sWhere .= $aColumns[$i] . " LIKE '%" . $_GET['sSearch'] . "%' OR ";
                }
            }
            $sWhere = substr_replace($sWhere, "", -3);
            $sWhere .= ')';
        }

        /* Individual column filtering */
        for ($i = 0; $i < count($aColumns); $i++) {
            if (isset($_GET['bSearchable_' . $i]) && $_GET['bSearchable_' . $i] == "true" && $_GET['sSearch_' . $i] != '') {
                if ($sWhere == "") {
                    $sWhere = "WHERE ";
                } else {
                    $sWhere .= " AND ";
                }
                $sWhere .= $aColumns[$i] . " LIKE '%" . $_GET['sSearch_' . $i] . "%' ";
            }
        }

        $sQuery = "SELECT SQL_CALC_FOUND_ROWS " . str_replace(" , ", " ", implode(", ", $aColumns)) . " FROM  $sTable $sWhere $sOrder $sLimit ";
        //print_r($sQuery);
        $rResult = R::getAll($sQuery);

        /* Data set length after filtering */
        $sQuery = "SELECT FOUND_ROWS()";

        $rResultFilterTotal = R::getAll($sQuery);
        //$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
        $iFilteredTotal = $rResultFilterTotal[0];
        //print_r($iFilteredTotal["FOUND_ROWS()"]);
        /* Total data set length */
        $sQuery = "SELECT $sIndexColumn FROM  $sTable ";
        $rResultTotal = R::getAll($sQuery);
        //$aResultTotal = mysql_fetch_array($rResultTotal);
        $iTotal = count($rResultTotal);

        $output = array(
            //"sEcho" => intval($_GET['sEcho']),
            "iTotalRecords" => $iTotal,
            "iTotalDisplayRecords" => $iFilteredTotal["FOUND_ROWS()"],
            "aaData" => array()
        );

        foreach ($rResult as $aRow) {
            $row = array();
            for ($i = 0; $i < count($aColumns); $i++) {
                $row[] = $aRow[$aColumns[$i]];
            }
            $row[] = "<a class=edit href=javascript:;>Edit </a>";
            $row[] = "<a class=duplicate href=javascript:;>Duplicate </a>";
            $row[] = "<a class=delete href=javascript:;>Delete </a>";
            $output['aaData'][] = $row;
        }

        echo json_encode($output);
    }

    public function getstores() {
        //check login
        autho::checkautho($this->hosturl . "/../core");
        //check authoize
        //autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
        //check authoize
        //autho::checkauthoize($this->controllname,$this->hosturl,$_SESSION['role_id']);
        $itr = filter_input(INPUT_POST, 'newItr');
        $returnarray = R::getAll('SELECT id , name FROM stores WHERE deleted  = 0 ');
        if (count($returnarray) > 0) {
            echo '<select id="stores' . $itr . '"  name="stores' . $itr . '"  class="form-control">';
            foreach ($returnarray as $single) {
                echo '<option value="' . $single['id'] . '">' . rtrim($single['name']) . '</option>';
            }
            echo '</select>';
        }
    }

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

        $id = filter_input(INPUT_POST, 'listid');
        $listword = filter_input(INPUT_POST, 'searchtxt');
        switch ($id) {
            case 'groupmedcine':
                $returnarray = R::getAll('SELECT distinct drugcat FROM drugs WHERE drugcat LIKE ? ', [ $listword . '%']);
                if (count($returnarray) > 0) {
                    //echo '<ul style="list-style-type:none">';
                    foreach ($returnarray as $single) {
                        // echo '<li class="choosen" data-type="cat">' . rtrim($single['drugcat']) . '</li>';
                        echo '<option  value="' . rtrim($single['drugcat']) . '"></option>';
                    }
                    //    echo '</ul>';
                }
                break;
            case 'namemedcine':
                $returnarray = R::getAll('SELECT distinct  drugname FROM drugs WHERE drugname LIKE ? ', [ $listword . '%']);
                if (count($returnarray) > 0) {
                    //  echo '<ul style="list-style-type:none">';
                    foreach ($returnarray as $single) {
                        // echo '<li class="choosen" data-type="name">' . rtrim($single['drugname']) . '</li>';
                        echo '<option  value="' . rtrim($single['drugname']) . '"></option>';
                    }
                    //echo '</ul>';
                }

                break;
            case 'frommedcine':
                $returnarray = R::getAll('SELECT distinct  drugtype FROM drugs WHERE drugtype LIKE ? ', [ $listword . '%']);
                if (count($returnarray) > 0) {
                    // echo '<ul style="list-style-type:none">';
                    foreach ($returnarray as $single) {
                        //    echo '<li class="choosen" data-type="type">' . rtrim($single['drugtype']) . '</li>';
                        echo '<option  value="' . rtrim($single['drugtype']) . '"></option>';
                    }
                    //   echo '</ul>';
                }

                break;
            case 'usemedcine':
                $returnarray = R::getAll('SELECT distinct  drugdos FROM drugs WHERE drugdos LIKE ? ', [ $listword . '%']);
                if (count($returnarray) > 0) {
                    //   echo '<ul style="list-style-type:none">';
                    foreach ($returnarray as $single) {
                        //     echo '<li class="choosen" data-type="dos">' . rtrim($single['drugdos']) . '</li>';
                        echo '<option  value="' . rtrim($single['drugdos']) . '"></option>';
                    }
                    //    echo '</ul>';
                }

                break;
        }
    }

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

        $name = filter_input(INPUT_POST, 'drugname');
        $cat = filter_input(INPUT_POST, 'drugcat');
        $dos = filter_input(INPUT_POST, 'drugdos');
        $type = filter_input(INPUT_POST, 'drugtype');
        $minimunBalance = filter_input(INPUT_POST, 'minimunBalance');
        $validateItr = filter_input(INPUT_POST, 'validateItr');

        $this->addNewDrug($cat, $name, $type, $dos, $minimunBalance, $validateItr);
    }

    private function addNewDrug($drugCat, $drugName, $drugType, $drugUse, $minimunBalance, $validateItr) {
        ## check if drug with the same name and type and use  exist in drugs table
        $drugs = R::findAll('drugs', 'drugname = ?  and drugtype = ?  and  drugdos = ? ', [$drugName, $drugType, $drugUse]);
        ## if exist return error duplicated         exit here 
        if (count($drugs) > 0) {
            echo 'sorry !!!! drug with the same name ,form  and use exist';
        }
        ## if not exist insert it   in drugs table
        else {
            ##  insert it   in drugs table
            $drug = R::dispense('drugs');
            $drug->drugname = $drugName;
            $drug->drugtype = $drugType;
            $drug->drugcat = $drugCat;
            $drug->drugdos = $drugUse;
            $drug->initialbalance = $minimunBalance;
            $drug->minimumbalance = $minimunBalance;
            try {
                R::store($drug);
                ################################################ this table is for pharmacy section #################################
                ## check if drug with the same name and type  exist in phdrugs table
                $phdrug = R::findOne('phdrugs', 'drugname = ?  and drugtype = ?  ', [$drugName, $drugType]);
                ## if not exist insert it   in phdrugs  table
                if (count($phdrug) < 1) {
                    $phdrugs = R::dispense('phdrugs');
                    $phdrugs->drugname = $drugName;
                    $phdrugs->drugtype = $drugType;
                    $phdrugs->drugcat = $drugCat;
                    $phdrugs->minimumbalance = $minimunBalance;
                    $drugId = R::store($phdrugs);

                    ######################################  add to stores system ##########################################
                    for ($i = 1; $i <= $validateItr; $i++) {
                        $storeId = filter_input(INPUT_POST, 'stores' . $i);

                        ## check if drug added to this store before else add it 
                        $storeDrugs = R::getRow('select id from storedrugs where deleted = 0 and storeid = ' . $storeId . ' and drugid = ' . $drugId);
                        if (count($storeDrugs) > 0) {
                            $storeDrugsId = $storeDrugs['id'];
                        } else {
                            $storeDrugs = R::dispense('storedrugs');
                            $storeDrugs->storeid = $storeId;
                            $storeDrugs->drugid = $drugId;
                            $storeDrugs->deleted = 0;
                            $storeDrugsId = R::store($storeDrugs);
                        }

                        $validateTo = filter_input(INPUT_POST, 'validateTo' . $i);
                        $quantity = filter_input(INPUT_POST, 'quantity' . $i);

                        ## check if drug with the same validation date exist in this store add quantity else add it 
                        //   $storeDrugsValidation = R::getRow('select id , currentbalance from storedrugsvalidation where  storedrugid = ' . $storeDrugsId . ' and validateto = "' . $validateTo . '"');
                        $storeDrugsValidation = R::findOne('storedrugsvalidation', 'storedrugid = ' . $storeDrugsId . ' and validateto = "' . $validateTo . '"');
                        if (count($storeDrugsValidation) > 0) {
                            $storeDrugsValidation->currentbalance = $storeDrugsValidation->currentbalance + $quantity;
                            R::store($storeDrugsValidation);
                        } else {
                            $storeDrugsValidation = R::dispense('storedrugsvalidation');
                            $storeDrugsValidation->storedrugid = $storeDrugsId;
                            $storeDrugsValidation->validateto = $validateTo;
                            $storeDrugsValidation->currentbalance = $quantity;
                            R::store($storeDrugsValidation);
                        }
                    }

                    echo 1;
                }
            } catch (Exception $ex) {
                echo 'sorry !!!! drug could not be added';
            }
        }
    }

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

        $id = filter_input(INPUT_POST, 'drugId');
        $name = filter_input(INPUT_POST, 'drugname');
        $cat = filter_input(INPUT_POST, 'drugcat');
        $dos = filter_input(INPUT_POST, 'drugdos');
        $type = filter_input(INPUT_POST, 'drugtype');
        $minimunBalance = filter_input(INPUT_POST, 'minimunBalance');

        $drug = R::load('drugs', $id);

        $drug->drugname = $name;
        $drug->drugtype = $type;
        $drug->drugcat = $cat;
        $drug->drugdos = $dos;
        $drug->minimumbalance = $minimunBalance;
        try {
            R::store($drug);
            echo 1;
        } catch (Exception $ex) {
            echo 'sorry !!!! drug could not be saved';
        }
    }

    public function deletedrug() {
        autho::checkautho($this->hosturl . "/../core");
        //check authoize
        //autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
        //check authoize
        //autho::checkauthoize($this->controllname,$this->hosturl,$_SESSION['role_id']);
        //here will load the menu show
        $drugId = filter_input(INPUT_POST, 'drugId');
        try {
            $sql = 'select id from gynadrugs where drugid =' . $drugId . ' and deleted = 0';
            $sql .= ' union select id from mainantenentaldrugs where drugid =' . $drugId . ' and deleted = 0';
            $sql .= ' union select id from operativedetailsdrugs where drugid =' . $drugId . ' and deleted = 0';
            $sql .= ' union select id from recorddrugs where drugid =' . $drugId . ' and deleted = 0';
            $sql .= ' union select id from infertilitydrugs where drugid =' . $drugId . ' and deleted = 0';
            $sql .= ' union select id from followupcarddrugs where drugid =' . $drugId . ' and deleted = 0';
            $sql .= ' union select id from followupdrugs where drugid =' . $drugId . ' and deleted = 0';

            #### chech if drug is used before
            $drugExist = R::getAll($sql);
            if (count($drugExist) > 0) {
                echo -1;
            } else {
                $sql = 'select storedrugs.id from storedrugs';
                $sql .=' join storedrugsvalidation on storedrugs.id = storedrugsvalidation.storedrugid';
                $sql .=' where storedrugs.drugid =' . $drugId . ' and storedrugs.deleted = 0';
                $sql .=' and  storedrugsvalidation.currentbalance  > 0';
                $drugStoreExist = R::getAll($sql);
                if (count($drugStoreExist) > 0) {
                    echo -2;
                } else {
                    $drug = R::load('drugs', $drugId);
                    R::trash($drug);
                    echo 1;
                }
            }
        } catch (Exception $ex) {
            echo $ex;
            //echo 'sorry !!!! drug could not be deleted';
        }
    }

    public function newmodify() {
        $allDrugs = R::findAll('drugs');
        print_r('<pre>');
        print_r(' total no of drugs = ' . count($allDrugs));
        print_r('</pre>');

        $i = 0;
        foreach ($allDrugs as $drug) {
            $phdrug = R::findOne('phdrugs', 'drugname = ?  and drugtype = ?  ', [$drug->drugname, $drug->drugtype]);
            if (count($phdrug) < 1) {
                $phdrug = R::dispense('phdrugs');
                $phdrug->drugname = $drug->drugname;
                $phdrug->drugtype = $drug->drugtype;
                $phdrug->drugcat = $drug->drugcat;
                $phdrug->minimumbalance = $drug->minimumbalance;
                $drugId = R::store($phdrug);
            }
            $i++;
            echo 'now we are at drug no' . $i . '  --- ';
        }
    }

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

}
