<?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 = 'stuff';
        $this->shcontrollname = 'Stuff';
        $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

        $allUsers = R::getAll('SELECT * FROM awusers');
        $this->smarty->assign('allusers', $allUsers);

        $headuser = R::findOne('councilstaff', 'status = 0');
        if (!empty($headuser)) {
            $headUserName = R::getRow('select * from awusers where user_id=' . $headuser->userid);
            $headuser->namehead = $headUserName['user_name'];
        }


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

    public function addnew() {
        $user_id = filter_input(INPUT_POST, 'user_id');
        $status = filter_input(INPUT_POST, 'status');
        $head = R::dispense('councilstaff');
        $head->userid = $user_id;
        $head->status = $status;
        $inInserted = R::store($head);
        if (!empty($inInserted)) {

            $username = R::getRow('SELECT * FROM awusers WHERE user_id = ' . $user_id);
            $this->smarty->assign('headinfo', $username);
            $this->smarty->display('newdatashow.html');
        }
    }

    public function edit() {
        $id = filter_input(INPUT_POST, 'idItem');
        $userid = filter_input(INPUT_POST, 'iduserold');
        $allUsers = R::getAll('SELECT * FROM awusers');

        $this->smarty->assign('useroldid', $userid);
        $this->smarty->assign('userID', $id);
        $this->smarty->assign('allusers', $allUsers);

        $this->smarty->display('newdatashownew.html');
    }

    public function update() {
        $id = filter_input(INPUT_POST, 'userold');
        $user_id = filter_input(INPUT_POST, 'usernew');
        $update = R::load('councilstaff', $id);
        $update->userid = $user_id;
        echo $updated = R::store($update);
    }

    public function updategg() {

        //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
        $id = filter_input(INPUT_POST, 'billID');
        $invoicenumup = filter_input(INPUT_POST, 'invoicenumberup');
        $invoicedateup = filter_input(INPUT_POST, 'invoicedateup');
        $suppliesup = filter_input(INPUT_POST, 'suppliernameup');
        ## --step 2 -- ##
        ##make update in importbill tbl
        $updatebill = R::load('importbill', $id);
        $updatebill->invoicenum = $invoicenumup;
        $updatebill->invoicedate = $invoicedateup;
        $updatebill->suppliers = $suppliesup;

        R::begin();
        try {
            $billIdUp = R::store($updatebill);
            ## --step 3 -- ##
            ##  loop to retrive all drugs in One bill to update it
            $mycount = filter_input(INPUT_POST, 'mycounter');
            for ($i = 1; $i <= $mycount; $i++) {
                ## --step 4 -- ##
                ##  get vars from loop
                $billIDn = filter_input(INPUT_POST, 'billId' . $i);
                $drug_id = filter_input(INPUT_POST, 'medicinenameitr' . $i);
                $drug_amount = filter_input(INPUT_POST, 'medicineamount' . $i);
                $currentvalupdate = R::findOne('drugs', 'id = ?', [$drug_id]);
                ## --step 5 -- ##
                ##  Make update in importdetails using drug_id And bill_id
                $drug_up = R::findOne('importdetails', 'drug_id = ? AND bill_id = ?', [$billIDn, $billIdUp]);
                if (!isset($drug_id)) {
                    continue;
                }
                $drug_up->drug_id = $drug_id;
                $drug_up->amount = $drug_amount;
                R::store($drug_up);
                ## --step 6 -- ##
                ## if update true in importdetails there two condition
                // First if drug_id in  importdetails not equal drug_id comming from form
                // change value in store tbl, drugs tbl and pharmacystore then add new drug

                if ($billIDn != $drug_id) {
                    $drrn = R::findOne('pharmacystore', 'drug_id = ? order by id desc ', [$billIDn]);
                    $drrt = R::load('pharmacystore', $drrn->id);

                    $durgsnewup1 = R::load('drugs', $billIDn);
                    $durgsnewup1->currentbalance = $durgsnewup1->currentbalance - $drrt->amountvary;
                    $newdrugs = R::store($durgsnewup1);
                    if ($newdrugs) {
                        $pharstorenew = R::dispense('pharmacystore');
                        $pharstorenew->drug_id = $drrt->drug_id;
                        $pharstorenew->amountbefore = $drrt->amountafter;
                        $pharstorenew->amountvary = $drrt->amountvary;
                        $pharstorenew->amountafter = $drrt->amountbefore;
                        $pharstorenew->opdate = date('Y-m-d H:i:s');
                        $pharstorenew->optype = 2;
                        $drugSaveAndStore = R::store($pharstorenew);
                        if ($drugSaveAndStore) {
                            $drrnn = R::findOne('pharmacystore', 'drug_id = ? AND bill_id = ?', [$drug_id, $billIdUp]);
                            $drrtt = R::load('pharmacystore', $drrnn->id);
                            $drrtt->drug_id = $drug_up->drug_id;
                            $drrtt->amountvary = $drug_up->amount;
                            $drrtt->amountbefore = $currentvalupdate->currentbalance;
                            $drrtt->amountafter = $drrtt->amountbefore + $drrtt->amountvary;
                            $drrtt->opdate = date('Y-m-d H:i:s');
                            $drrtt->optype = 2;
                            R::store($drrtt);

                            $durgsnewup = R::load('drugs', $currentvalupdate->id);
                            $durgsnewup->currentbalance = $drrtt->amountafter;
                            R::store($durgsnewup);
                        }
                    }
                    ## --step 7 -- ##
                    ## if update true in importdetails there two condition
                    // Second if drug_id in  importdetails equal drug_id comming from form
                    // change value in store tbl, drugs tbl and pharmacystore
                } elseif ($billIDn == $drug_id) {

                    $drrn = R::findOne('pharmacystore', 'drug_id = ? order by id desc ', [$drug_id]);
                    $drrt = R::load('pharmacystore', $drrn->id);
                    if ($drrt->amountvary <= $drug_up->amount) {
                        continue;
                    }
                    $durgsnewup1 = R::load('drugs', $currentvalupdate->id);
                    $durgsnewup1->currentbalance = $durgsnewup1->currentbalance - $drrt->amountvary;
                    $updatenewdrugs = R::store($durgsnewup1);
                    if ($updatenewdrugs) {
                        $pharstorenew = R::dispense('pharmacystore');
                        $pharstorenew->drug_id = $drrt->drug_id;
                        $pharstorenew->amountbefore = $durgsnewup1->currentbalance;
                        $pharstorenew->amountvary = $drug_up->amount;
                        $pharstorenew->amountafter = $pharstorenew->amountbefore + $pharstorenew->amountvary;
                        $pharstorenew->opdate = date('Y-m-d H:i:s');
                        $pharstorenew->optype = 2;
                        R::store($pharstorenew);

                        $durgsnewup = R::load('drugs', $currentvalupdate->id);
                        $durgsnewup->currentbalance = $pharstorenew->amountafter;
                        R::store($durgsnewup);
                    }
                }
            }
            R::commit();
            header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
        } catch (Exception $e) {
            print_r($e);
        }
    }

## 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
        $id = filter_input(INPUT_GET, 'id');
        $invoiceData = R::load('importbill', $id);
        $relatedbill = R::findAll('importdetails', 'bill_id = ? ', [$id]);
        R::begin();

        try {
            // Delete invoice from tbl importbill
            R::trash($invoiceData);
            foreach ($relatedbill as $delrow) {
                // delete bill_id details  from tbl importdetails
                $delrelated = R::load('importdetails', $delrow->id);
                R::trash($delrelated);
                //minus the amount from tbl drugs
                $currentvalreceipt = R::findOne('drugs', 'id = ?', [$delrelated->drug_id]);
                $currentvalreceipt->currentbalance = $currentvalreceipt->currentbalance - $delrelated->amount;
                R::store($currentvalreceipt);
                $phastor = R::findOne('pharmacystore', 'drug_id = ? order by id desc', [$delrelated->drug_id]);
                // then store action in tbl pharmacystore
                $pharstorecash = R::dispense('pharmacystore');
                $pharstorecash->drug_id = $delrelated->drug_id;
                $pharstorecash->amountbefore = $phastor->amountafter;
                $pharstorecash->amountvary = $delrelated->amount;
                $pharstorecash->amountafter = $phastor->amountafter - $phastor->amountvary;
                $pharstorecash->opdate = date('Y-m-d H:i:s');
                $pharstorecash->optype = 3; // this status 0 for delete 1 for update

                R::store($pharstorecash);
            }
            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);
        }
    }

## 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();
    }

}
