<?php

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 = 'store';
        $this->shcontrollname = 'Store';
        $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] = 'Store'; //controller name
        // do name  // switch($do)
        switch ($acty) {
            case '':$active[0] = 'Stores';    // == active name in add menue
                break;
            case 'show':$active[0] = 'show';
                break;
            case 'transfer':$active[0] = 'Drug Transfer';
                break;
            default :$active[0] = 'Stores';
                break;
        }
        $this->active = $active;
//        print_r($active);
//        print_r($acty);
        //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
    ## show  stores html page 
    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('store/stores.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    ## transfer drugs between stores

    public function transfer() {
        //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

        $drugs = R::getAll('SELECT  id , drugname , drugtype   FROM phdrugs order by drugname asc');

        $this->smarty->assign('drugs', $drugs);

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

    ## transfer drugs between stores

    public function transferdrug() {
        //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']);

        $storeDrugsValidationId = filter_input(INPUT_POST, 'storeDrugsValidationId');
        $movedBalance = filter_input(INPUT_POST, 'movedBalance');
        $storeTo = filter_input(INPUT_POST, 'storeTo');

        $before = 0;     ## for store to not for from 

        try {
            $storedrugsvalidationFrom = R::load('storedrugsvalidation', $storeDrugsValidationId);
            $storedrugs = R::load('storedrugs', $storedrugsvalidationFrom->storedrugid);
            $storeFrom = $storedrugs->storeid;
            $drugId = $storedrugs->drugid;
            $validTo = $storedrugsvalidationFrom->validateto;


            if ($storedrugsvalidationFrom->currentbalance >= $movedBalance) {
                $storedrugsvalidationFrom->currentbalance = $storedrugsvalidationFrom->currentbalance - $movedBalance;
                R::store($storedrugsvalidationFrom);

                $storeDrugs = R::findOne('storedrugs', ' deleted = 0 and  storeid = ' . $storeTo . ' and drugid = ' . $drugId);
                if (count($storeDrugs) > 0) {
                    $storeDrugsId = $storeDrugs->id;
                } else {
                    $storeDrugs = R::dispense('storedrugs');
                    $storeDrugs->storeid = $storeTo;
                    $storeDrugs->drugid = $drugId;
                    $storeDrugs->deleted = 0;
                    $storeDrugsId = R::store($storeDrugs);
                }


                $storedrugsvalidationTo = R::findOne('storedrugsvalidation', '  storedrugid = ' . $storeDrugsId . ' and validateto = "' . $validTo . '"');
                if (count($storedrugsvalidationTo) > 0) {
                    $before = $storedrugsvalidationTo->currentbalance;
                    $storedrugsvalidationTo->currentbalance = $storedrugsvalidationTo->currentbalance + $movedBalance;
                } else {
                    $storedrugsvalidationTo = R::dispense('storedrugsvalidation');
                    $storedrugsvalidationTo->storedrugid = $storeDrugsId;
                    $storedrugsvalidationTo->validateto = $storedrugsvalidationFrom->validateto;
                    $storedrugsvalidationTo->currentbalance = $movedBalance;
                }

                R::store($storedrugsvalidationTo);


                //here the add in tbl drugmovements
                $drugMovement = R::dispense('drugmovements');
                $drugMovement->drugid = $drugId;
                $drugMovement->amountbefore = $before;
                $drugMovement->amountafter = $before + $movedBalance;
                $drugMovement->amount = $movedBalance;
                $drugMovement->operationdate = date('Y-m-d H:i:s');
                $drugMovement->operationtype = 2;
                $drugMovement->storeidfrom = $storeFrom;
                $drugMovement->storeidto = $storeTo;
                $drugMovement->comment = 'transfer drug between stores';
                $drugMovement->relatedid = 0;     ## bill id if import , or receipt id for export , 0 for transfer
                $drugMovement->userid = $_SESSION['user_id'];
                R::store($drugMovement);


                echo 1;
            } else {
                echo 'drug balance in store is less than moved balance';
            }
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    ## fill stores datatable with data 

    public function showstores() {
        //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 = "stores";


        $aColumns = array('id', 'name');

        // 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 = "WHERE (";
        if (isset($_GET['sSearch']) && $_GET['sSearch'] != "") {
            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 .= ' AND deleted = 0';
        } else {
            $sWhere .= ' deleted = 0';
        }

        $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=delete href=javascript:;>Delete </a>";
            $output['aaData'][] = $row;
        }

        echo json_encode($output);
    }

    ## save new store in database

    public function addstore() {
        //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']);

        $storeName = filter_input(INPUT_POST, 'storeName');

        try {
            $oldStore = R::findOne('stores', 'name = "' . $storeName . '" and deleted = 0');
            if (count($oldStore) > 0) {
                echo -1;
            } else {
                $store = R::dispense('stores');
                $store->name = $storeName;
                $store->doctorid = $_SESSION['user_id'];
                $store->deleted = 0;
                R::store($store);
                echo 1;
            }
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    ## save new store in database

    public function updatestore() {
        //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']);

        $storeId = filter_input(INPUT_POST, 'storeId');
        $storeName = filter_input(INPUT_POST, 'storeName');

        try {
            $oldStore = R::findOne('stores', 'deleted = 0 and name = "' . $storeName . '" and id !=' . $storeId);
            if (count($oldStore) > 0) {
                echo -1;
            } else {
                $store = R::load('stores', $storeId);
                $store->name = $storeName;
                $store->doctorid = $_SESSION['user_id'];
                $store->deleted = 0;
                R::store($store);
                echo 1;
            }
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    ## save new store in database

    public function deletestore() {
        //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']);

        $storeId = filter_input(INPUT_POST, 'storeId');
        try {
            $storedrugs = R::findOne('storedrugs', ' storeid =' . $storeId . ' and deleted = 0');
            if (count($storedrugs) > 0) {
                echo -1;
            } else {
                $store = R::load('stores', $storeId);
                $store->deleted = 1;
                R::store($store);
                echo 1;
            }
        } catch (Exception $ex) {
            echo $ex;
        }
    }

    ## save new store in database

    public function search() {
        //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']);

        $drugId = filter_input(INPUT_POST, 'drugId');
        try {
            $sql = 'select storedrugsvalidation.id ,stores.name ,phdrugs.drugname, storedrugsvalidation.currentbalance , storedrugsvalidation.validateto from storedrugs';
            $sql .=' join storedrugsvalidation on storedrugs.id = storedrugsvalidation.storedrugid';
            $sql .=' join stores on stores.id = storedrugs.storeid';
            $sql .=' join phdrugs on phdrugs.id = storedrugs.drugid';
            $sql .=' where storedrugs.drugid =' . $drugId . ' and storedrugs.deleted = 0';
            $sql .=' and  storedrugsvalidation.currentbalance  > 0';
            $drugs = R::getAll($sql);

            if (count($drugs) > 0) {
                $returnarray = R::getAll('SELECT id , name FROM stores WHERE deleted  = 0 ');
                if (count($returnarray) > 0) {
                    $stores = '';
                    foreach ($returnarray as $single) {
                        $stores .= '<option value="' . $single['id'] . '">' . rtrim($single['name']) . '</option>';
                    }
                }
                $itr = 0;
                foreach ($drugs as $single) {
                    $itr++;
                    echo '<tr>';
                    echo '<td class="hide_me">' . rtrim($single['id']) . '</td>';
                    echo '<td>' . rtrim($single['name']) . '</td>';
                    echo '<td>' . rtrim($single['drugname']) . '</td>';
                    echo '<td>' . rtrim($single['validateto']) . '</td>';
                    echo '<td>' . rtrim($single['currentbalance']) . '</td>';
                    echo '<td><input type="text"  id="movedBalance' . $itr . '"  class="form-control positivefloat" value="0"></td>';
                    echo '<td><select id="stores' . $itr . '"   class="form-control">' . $stores . '</select></td>';
                    echo '<td><a class="btn grey-cascade btn-xs transferDrug" data-id="' . rtrim($single['id']) . '" data-itr="' . $itr . '"  href="#" >Transfer</a></td>';
                    echo '</tr>';
                }
            } else {
                
            }
        } catch (Exception $ex) {
            echo $ex;
        }
    }

//    ## show all content in store report
//
//    public function show() {
//        //check login
//        autho::checkautho($this->hosturl . "/../core");
//        //check authoize
//        autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
//        //check authoize
//
//        $drugstore = R::findAll('pharmacystore');
//        foreach ($drugstore as $datastore) {
//            $durgsdetails = R::findOne('drugs', 'id = ?', [$datastore->drug_id]);
//            $datastore->drugname = $durgsdetails->drugname;
//        }
//        // calling html files
//        $this->smarty->assign('drugstore', $drugstore);
//        header::headershow($this->smarty, $this->hosturl);
//        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
//        $this->smarty->display('store/show.html');
//        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
//        footer::footershow($this->smarty, $this->hosturl);
//    }
    // at the end of class call
    public function __destruct() {
        //close connection
        R::close();
    }

}
