<?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 = 'drugsex';
        $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] = 'drugs'; //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("_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
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('drugs/drugs.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function show() {
        //check login
        autho::checkautho($this->hosturl);
        //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');

        // 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;
        }
        //print_r($output);
        echo json_encode($output);
    }

    public function getthisserach() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        
        $listname = filter_input(INPUT_POST, 'listid');
        $listword = filter_input(INPUT_POST, 'searchtxt');
        switch ($listname) {
            case 'groupmedcine':
                $returnarray =  R::getAll('SELECT DISTINCT  drugcat FROM drugs WHERE drugcat LIKE ?  ', [ $listword . '%']);
                foreach ($returnarray as $single) {
                    echo '<option value="' . rtrim($single['drugcat']) . '"></option>';
                }
                break;
            case 'namemedcine':
                $returnarray = R::getAll('SELECT DISTINCT drugname FROM drugs WHERE drugname LIKE ? ', [ $listword . '%']);
                foreach ($returnarray as $single) {
                    echo '<option value="' . rtrim($single['drugname']) . '">';
                }
                break;
            case 'frommedcine':
                $returnarray = R::getAll('SELECT DISTINCT drugtype FROM drugs WHERE drugtype LIKE ? ', [ $listword . '%']);
                foreach ($returnarray as $single) {
                    echo '<option value="' . rtrim($single['drugtype']). '">';
                }

                break;
            case 'usemedcine':
                $returnarray = R::getAll('SELECT DISTINCT drugdos FROM drugs WHERE drugdos LIKE ? ', [ $listword . '%']);
                foreach ($returnarray as $single) {
                    echo '<option value="' . rtrim($single['drugdos']) . '">';
                }

                break;
        }

    }


    public function adddrug() {
        //check login
        autho::checkautho($this->hosturl);
        //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');

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

        $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 added';
        }
    }

    public function updatedrug() {
        //check login
        autho::checkautho($this->hosturl);
        //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() {
       //check login
        autho::checkautho($this->hosturl);
        //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();
    }

}
