<?php

require_once("imp/_imp.php");

class Controllers {

//public vars
    public $smarty;
    public $hosturl;
    public $controllname;
    public $shcontrollname;
    public $active;
    public $time;
    public $today;

// 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 = 'detection';
        $this->shcontrollname = 'detection';
        $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] = 'programesetting'; //controller name or tab name
        $active[1] = 'detection'; //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;

        R::ext('xdispense', function ($type) {
            return R::getRedBean()->dispense($type);
        });

        require_once("visits_common.php"); //general functions
//here will call all php pages
        require_once("_header.php");
        require_once("_sidebar.php");
        require_once("_leftsidebar.php");
        require_once("_footer.php");

        //find loading time
        $this->time = microtime(true);
        $this->today = date('Y-m-d');
    }

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

        ####################################################################
        $programesetting = R::findOne('programesetting');
        $this->smarty->assign('programesetting', $programesetting);

        $detections = R::findAll('detections', 'del = 0');
        $this->smarty->assign('detections', $detections);
        if ($programesetting->system_type == 2) {
            $allDocs = R::getAll('SELECT awusers.user_id  , awusers.name    FROM awusers
                                                join  awrole     on awrole.id =  awusers.role_id
                                                WHERE awusers.deleted = 0  and awrole.doctor_show = 1 and awrole.visit_show = 1  ');

            $this->smarty->assign('allDocs', $allDocs);
        }
        #####################################################################
        //call other class with other content
        header::headershow($this->smarty, $this->hosturl);
        sidebar::sidebarshow($this->smarty, $this->hosturl, $this->active);
        $this->smarty->display('detection/show.html');
        leftsidebar::leftsidebarshow($this->smarty, $this->hosturl);
        footer::footershow($this->smarty, $this->hosturl);
    }

    public function addDetectionControl() {
        //check login
        autho::checkautho($this->hosturl);

        $programesetting = R::findOne('programesetting');
        $this->smarty->assign('programesetting', $programesetting);

        $detection = R::dispense('detections');
        $detection->del = 0;
        $detection->detectionval = 0;
        $detection->title = '';
        $detection->create_date = date('Y-m-d');
        try {
            $detection->id = R::store($detection);
            $this->erpProduct($detection);

            if ($programesetting->system_type == 2) {
                $allDocs = R::getAll('SELECT awusers.user_id  , awusers.name    FROM awusers
                                                join  awrole     on awrole.id =  awusers.role_id
                                                WHERE awusers.deleted = 0  and awrole.doctor_show = 1 and awrole.visit_show = 1  ');

                $this->smarty->assign('allDocs', $allDocs);
            }
            $this->smarty->assign('mydata', $detection);
            $this->smarty->display('detection/detection_row.html');
        } catch (Exception $e) {
            echo -1;
        }
    }

    public function update() {

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

        $id = filter_input(INPUT_POST, "id");
        $tablename = filter_input(INPUT_POST, "tableName");
        $colname = filter_input(INPUT_POST, "colName");
        $value = filter_input(INPUT_POST, "value");

        try {
            $obj = R::load($tablename, $id);
            $obj->$colname = $value;
            R::store($obj);
            $this->erpProduct($obj);
        } catch (Exception $e) {

        }
    }

    public function updateajax() {

        //check login
        autho::checkautho($this->hosturl);

        $id = filter_input(INPUT_POST, "id");
        $tablename = filter_input(INPUT_POST, "tableName");
        $colname = filter_input(INPUT_POST, "colName");
        $value = filter_input(INPUT_POST, "value");

        try {
            $obj = R::load($tablename, $id);
            $obj->$colname = $value;
            R::store($obj);
            $this->erpProduct($obj);
        } catch (Exception $e) {

        }
    }

    public function erpProduct($detection) {//detections
        $programesetting = R::load('programesetting', 1);
        if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
            try {
                R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                R::selectDatabase('erpDB');
                if (R::testConnection()) {
                    $productData = R::getRow('select productId from product where obygyDetectionId = ' . $detection->id);
                    if (empty($productData['productId'])) {
                        //here use NULL for new insert
                        //better to add client using erp files it self so use  curl "it is like post requist but in php"
                        $this->curlAddProduct($detection, $programesetting->erpdb);
                    } else {
                        //here use id to update
                        $this->curlupdateProduct($detection, $programesetting->erpdb, $productData['productId']);
                    }
                } else {
                    throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                }
            } catch (Exception $exc) {
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                //echo -1;
            }
            R::selectDatabase('default');
        }
    }

    public function erpProductDel($detection) {//detections
        $programesetting = R::load('programesetting', 1);
        if (!empty($programesetting->erpdb)) {//if exist addDatabase erpDB
            try {
                R::addDatabase('erpDB', 'mysql:host=' . DB_HOST . ';dbname=' . $programesetting->erpdb . '', DB_USER, DB_PASS);
                R::selectDatabase('erpDB');
                if (R::testConnection()) {
                    $productData = R::getRow('select productId from product where obygyDetectionId = ' . $detection->id);
                    $this->curlDelProduct($programesetting->erpdb, $productData['productId']);
                } else {
                    throw new Exception('Unable to connect to erpDB,make sure database name is ok and connected or clear its name in setup');
                }
                R::selectDatabase('default');
            } catch (Exception $exc) {
                //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
                //echo -1;
            }
        }
    }

    //better to add client using erp files it self so use  curl "it is like post requist but in php"
    //category has fixed val = 'services'
    public function curlAddProduct($detection, $erpDB) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'detection_id' => $detection->id,
            'new_cat_id' => 'obygy',
            'level' => 'obygy',
            'obygy_cat_name' => 'Services', //'obygy services'
            'new_productName' => $detection->title,
            'new_parcode' => '',
            'new_productBuyPrice' => 0,
            'new_productbuypricereal' => 0,
            'new_buypricereal_precentage1' => 0,
            'new_productSellAllPrice' => $detection->detectionval,
            'new_buytotal_precentage1' => 0,
            'new_productSellHalfPrice' => $detection->detectionval,
            'new_buyhalf_precentage1' => 0,
            'new_productSellUnitPrice' => $detection->detectionval,
            'new_buypart_precentage1' => 0,
            'new_productquantity' => 0,
            'new_isservice1' => 1,
            'inMenu1' => 1,
            'type1' => 0,
            'new_productDate' => date('Y-m-d'),
            'expireDate' => 0,
            'productunit1' => 1,
            'productnumber1' => 1,
            'unitsItr' => 1,
        ];
        try {
            $ch = curl_init(HOST_URL_ERP . '/controllers/buyBillControllerAjax.php?do=temp&itr=1&tabIndex=-1&billnameid=1');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

            // execute!
            $response = curl_exec($ch);

            // close the connection, release resources used
            curl_close($ch);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }
        // do anything you want with your response
//        var_dump($response);
    }

    //category has fixed val = 'obygy services'
    public function curlupdateProduct($detection, $erpDB, $productId) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'detection_id' => $detection->id,
            'productId' => $productId,
            'productCatId' => 'obygy',
            'level' => 'obygy',
            'obygy_cat_name' => 'Services', //'obygy services'
            'productName1' => $detection->title,
            'parcode1' => '',
            'productBuyPrice1' => 0,
            'productbuypricereal' => 0,
            'buypricereal_precentage1' => 0,
            'productSellAllPrice1' => $detection->detectionval,
            'buytotal_precentage1' => 0,
            'productSellHalfPrice1' => $detection->detectionval,
            'buyhalf_precentage1' => 0,
            'productSellUnitPrice1' => $detection->detectionval,
            'buypart_precentage1' => 0,
            'productquantity1' => 0,
            'isservice1' => 1,
            'inMenu1' => 1,
            'manufacture' => 0,
            'productDate1' => date('Y-m-d'),
            'expireDate1' => 0,
            'productunit1' => 1,
            'productnumber1' => 1,
            'unitsItr1' => 1,
        ];
        try {
            $ch = curl_init(HOST_URL_ERP . '/controllers/productControllerAjax.php?do=update');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

            // execute!
            $response = curl_exec($ch);

            // close the connection, release resources used
            curl_close($ch);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }

        // do anything you want with your response
//        var_dump($response);
    }

    public function curlDelProduct($erpDB, $productId) {
        // set post fields
        $post = [
            'erpDB' => $erpDB,
            'productId' => $productId,
        ];
        try {
            $ch = curl_init(HOST_URL_ERP . '/controllers/productControllerAjax.php?do=deleteFinaly');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

            // execute!
            $response = curl_exec($ch);

            // close the connection, release resources used
            curl_close($ch);
        } catch (Exception $exc) {
            //header('Location:' . $this->hosturl . '/controllers/' . $this->controllname . '.php?ac=show');
            //echo -1;
        }

        // do anything you want with your response
//        var_dump($response);
    }

// at the end of class call
    public function __destruct() {
        //echo "Time Elapsed: ".(microtime(true) - $this->time)."s";
//close connection
        R::close();
    }

}
