<?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', 'currentbalance');

        // 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++) {
                if ($aColumns[$i] == "version") {
                    /* Special output formatting for 'version' column */
                    $row[] = ($aRow[$aColumns[$i]] == "0") ? '-' : $aRow[$aColumns[$i]];
                } else if ($aColumns[$i] != ' ') {
                    /* General output */
                    $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 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, 'id');
        $listword = filter_input(INPUT_POST, 'searchtxt');
        switch ($id) {
            case 'drugcat':
                $returnarray = R::getAll('SELECT 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 '</ul>';
                }
                break;
            case 'drugname':
                $returnarray = R::getAll('SELECT 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 '</ul>';
                }

                break;
            case 'drugtype':
                $returnarray = R::getAll('SELECT 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 '</ul>';
                }

                break;
            case 'drugdos':
                $returnarray = R::getAll('SELECT 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 '</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');
        $initialbalance = filter_input(INPUT_POST, 'initial');

        $drug = R::dispense('drugs');

        $drug->drugname = $name;
        $drug->drugtype = $type;
        $drug->drugcat = $cat;
        $drug->drugdos = $dos;
        $drug->initialbalance = $initialbalance;
        $drug->currentbalance = $initialbalance;
        try {
            R::store($drug);
            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, 'd_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');

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

        $drug->drugname = $name;
        $drug->drugtype = $type;
        $drug->drugcat = $cat;
        $drug->drugdos = $dos;
        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
        $id = filter_input(INPUT_POST, 'd_id');
        $drug = R::load('drugs', $id);
        try {
            R::trash($drug);
            echo 1;
        } catch (Exception $ex) {
            echo 'sorry !!!! drug could not be deleted';
        }
    }

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

}
