<?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 = 'buys';
        $this->shcontrollname = 'Import';
        $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] = 'Import'; //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
// all drugs will show in selectbox in add new drugs

        $allMed = R::findAll('phdrugs', 'order by drugname asc');
        $this->smarty->assign('allMed', $allMed);

        $stores = R::getAll('SELECT id , name FROM stores WHERE deleted  = 0 ');
        $this->smarty->assign('stores', $stores);

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

    ## insert new drug in importbill and importdetails

    public function addnew() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //vars here
        $invoicenum = filter_input(INPUT_POST, 'invoicenumber');
        $invoicedate = filter_input(INPUT_POST, 'invoicedate');
        $supname = filter_input(INPUT_POST, 'suppliername');
        $itr = filter_input(INPUT_POST, 'itr');


        R::begin();
        try {
            //here the add In tbl importbill
            $invoice = R::dispense('importbill');
            $invoice->invoicenum = $invoicenum;
            $invoice->invoicedate = $invoicedate;
            $invoice->suppliers = $supname;
            $invoice->receiveuser = $_SESSION['user_id'];
            $billId = R::store($invoice);

            for ($i = 1; $i <= $itr; $i++) {
                $drugID = filter_input(INPUT_POST, 'drug' . $i);
                $storeID = filter_input(INPUT_POST, 'store' . $i);
                $validTo = filter_input(INPUT_POST, 'validTo' . $i);
                $amount = filter_input(INPUT_POST, 'balance' . $i);

                $drug = R::findOne('phdrugs', 'id = ?', [$drugID]);
                if (!$drug) {
                    continue;
                }

                $this->addDrugToBill($drugID, $storeID, $validTo, $amount, $billId);
            }
            R::commit();

            $buttonname = filter_input(INPUT_POST, 'save');
            $buttonnewname = filter_input(INPUT_POST, 'savenew');

            if (!empty($buttonnewname)) {
                header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php');
            } else {
                header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            }
        } catch (Exception $e) {
            R::rollback();
            header('Location:' . $this->hosturl . '/controllers/error?ac=notadd&id=' . $this->controllname);
        }
    }

    public function show() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //here will load the menu show

        $importBills = R::findAll('importbill');
        foreach ($importBills as $single) {
            $userid = R::getRow('SELECT * FROM awusers WHERE user_id = ? LIMIT 1', [$single->receiveuser]);
            $single->nameuser = $userid['user_name'];
        }
        $this->smarty->assign('medicineimport', $importBills);

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

    ## Delete invoice from tbl importbill then delete from tbl importdetails and minus the amount value from drugs tbl

    public function del() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //vars here
        $billId = filter_input(INPUT_GET, 'id');
        $importbill = R::load('importbill', $billId);
        $importdrugs = R::findAll('importdrugs', 'billid = ? ', [$billId]);
        $drugmovements = R::findAll('drugmovements', 'operationtype = 0 and relatedid = ? ', [$billId]);

        R::begin();

        try {
            // Delete invoice from tbl importbill
            R::trash($importbill);

            foreach ($importdrugs as $single) {

                $drugID = $single->drugid;
                $storeID = $single->storeid;
                $validTo = $single->validto;
                $amount = $single->amount;

                R::trash($single);

                $this->removeDrugFromBill($drugID, $storeID, $validTo, $amount, $billId, 'delete drug bill');
            }
            R::commit();
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
        } catch (Exception $e) {
            R::rollback();
            header('Location:' . $this->hosturl . '/controllers/error.php?ac=notdel&id=' . $this->controllname);
        }
    }

    public function edit() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //vars here
        $billId = filter_input(INPUT_GET, 'id');
        $importbill = R::load('importbill', $billId);
        $importdrugs = R::findAll('importdrugs', 'billid = ? ', [$billId]);


        $allMed = R::findAll('phdrugs', 'order by drugname asc');
        $this->smarty->assign('allMed', $allMed);

        $stores = R::getAll('SELECT id , name FROM stores WHERE deleted  = 0 ');
        $this->smarty->assign('stores', $stores);


        $this->smarty->assign('importbill', $importbill);
        $this->smarty->assign('importdrugs', $importdrugs);

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

    public function update() {

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

        ## --step 1 -- ##
        ##Get vars to update
        $billId = filter_input(INPUT_POST, 'billID');
        $invoicenumup = filter_input(INPUT_POST, 'invoicenumberup');
        $invoicedateup = filter_input(INPUT_POST, 'invoicedateup');
        $suppliesup = filter_input(INPUT_POST, 'suppliernameup');
        $itr = filter_input(INPUT_POST, 'itr');

        ## --step 2 -- ##
        ##make update in importbill tbl
        $updatebill = R::load('importbill', $billId);
        $updatebill->invoicenum = $invoicenumup;
        $updatebill->invoicedate = $invoicedateup;
        $updatebill->suppliers = $suppliesup;

        R::begin();
        try {
            R::store($updatebill);

            $importdrugs = R::findAll('importdrugs', 'billid = ? ', [$billId]);
            foreach ($importdrugs as $data) {
                $drugID = $data->drugid;
                $storeID = $data->storeid;
                $validTo = $data->validto;
                $amount = $data->amount;
                $billId = $data->billid;

                R::trash($data);

                $this->removeDrugFromBill($drugID, $storeID, $validTo, $amount, $billId, 'update drug bill');
            }

            ## --step 3 -- ##
            ##  loop to retrive all drugs in One bill to update it

            for ($i = 1; $i <= $itr; $i++) {
                $drugID = filter_input(INPUT_POST, 'drug' . $i);
                $storeID = filter_input(INPUT_POST, 'store' . $i);
                $validTo = filter_input(INPUT_POST, 'validTo' . $i);
                $amount = filter_input(INPUT_POST, 'balance' . $i);

                $drug = R::findOne('phdrugs', 'id = ?', [$drugID]);
                if (!$drug) {
                    continue;
                }
                $this->addDrugToBill($drugID, $storeID, $validTo, $amount, $billId);
            }
            R::commit();
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
        } catch (Exception $e) {
            print_r($e);
        }
    }

    private function addDrugToBill($drugID, $storeID, $validTo, $amount, $billId) {

        //here the add in tbl importdrugs
        $importdrugs = R::dispense('importdrugs');
        $importdrugs->drugid = $drugID;
        $importdrugs->storeid = $storeID;
        $importdrugs->validto = $validTo;
        $importdrugs->amount = $amount;
        $importdrugs->billid = $billId;
        $importdrugs->userid = $_SESSION['user_id'];
        R::store($importdrugs);


        $storeDrugs = R::findOne('storedrugs', ' 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);
        }

        $before = 0;

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

        R::store($storedrugsvalidation);

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

    private function removeDrugFromBill($drugID, $storeID, $validTo, $amount, $billId, $comment) {
        $storeDrugs = R::findOne('storedrugs', ' 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);
        }

        $before = 0;

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

        R::store($storedrugsvalidation);

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

#####################################################################################################

    public function drugsselected() {
//check login
        autho::checkautho($this->hosturl . "/../core");
//check authoize
        autho::checkauthoize($this->controllname, $this->hosturl . "/../core", $_SESSION['role_id']);
//check authoize
// all drugs will show in selectbox in add new drugs

        $myids = filter_input(INPUT_POST, 'myid');
        echo $myids;
        $queryString = '';
        if (isset($myids)) {
            $queryString = "id NOT IN ($myids)";

            $allMed1 = R::findAll("phdrugs", $queryString);
            $this->smarty->assign('allMed1', $allMed1);
            $this->smarty->display('buys/addselect.html');
        }
    }

    ## Select all data from drugs table to use in select2 search with json

    public function allmed() {

        $allmed = R::findAll('phdrugs');
        $json = array();
        foreach ($allmed as $row) {
            array_push($json, array($row['id'], $row['drugname']));
        }
        header('Content-Type: application/json');
        echo json_encode($json);
    }

    public function invoice() {

        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //vars here
        //$id = filter_input(INPUT_GET, 'id');
        $id = filter_input(INPUT_POST, 'itemid');
        $billdetails = R::findOne('importbill', 'id = ?', [$id]);
        $drugsinbill = R::findAll('importdetails', 'bill_id = ?', [$id]);
        // get all drugs will show in invoice
        $allmededit = R::findAll('drugs');
        $this->smarty->assign('allmed', $allmededit);
        foreach ($drugsinbill as $durgbill) {
            $infodrug = R::findOne('drugs', 'id = ?', [$durgbill->drug_id]);
            $durgbill->ddetails = $infodrug;
        }
        $this->smarty->assign('billdetails', $billdetails);
        $this->smarty->assign('drugsinbill', $drugsinbill);
        $this->smarty->assign('allmededit', $allmededit);

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

## this function to delete one item when update from button close

    public function delup() {
        //check login
        autho::checkautho($this->hosturl);
        //check authoize
        autho::checkauthoize($this->controllname, $this->hosturl, $_SESSION['role_id']);
        //vars here
        $id = $_REQUEST['itemid'];
        $bill_id = $_REQUEST['bill_id'];
        //$id = filter_input(INPUT_GET, 'id');
        //$bill_id = filter_input(INPUT_GET, 'bill');
        $druginimport = R::findOne('importdetails', 'drug_id = ? AND bill_id = ?', [$id, $bill_id]);
        // delete bill_id details  from tbl importdetails
        $dataloaded = R::load('importdetails', $druginimport->id);


        R::trash($dataloaded);
        //minus the amount from tbl drugs
        $currentvaldelup = R::findOne('drugs', 'id = ?', [$dataloaded->drug_id]);
        $currentvaldelup->currentbalance = $currentvaldelup->currentbalance - $dataloaded->amount;
        R::store($currentvaldelup);
        $phastordelupdate = R::findOne('pharmacystore', 'drug_id = ? order by id desc', [$dataloaded->drug_id]);
        // then store action in tbl pharmacystore
        $phastordelup = R::dispense('pharmacystore');
        $phastordelup->drug_id = $dataloaded->drug_id;
        $phastordelup->amountbefore = $phastordelupdate->amountafter;
        $phastordelup->amountvary = $dataloaded->amount;
        $phastordelup->amountafter = $phastordelupdate->amountafter - $phastordelupdate->amountvary;
        $phastordelup->opdate = date('Y-m-d H:i:s');
        $phastordelup->optype = 3; // this status 0 for delete 1 for update
        R::begin();
        try {
            R::store($phastordelup);
            R::commit();
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=edit&id=' . $bill_id);
        } catch (Exception $e) {
            R::rollback();
            //header('Location:' . $this->hosturl . '/controllers/error.php?ac=notdel&id=' . $this->controllname);
        }
    }

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

}
