<?php

class Pages extends CI_controller
{
    public function __construct()
    {
            parent::__construct();

            // Load url helper for redirect to work
            $this->load->helper('url');

            // Load form helper library
            $this->load->helper('form');

            // Load form validation library
            $this->load->library('form_validation');

            // Load session library
            $this->load->library('session');

            // Set timezone to Philippines
            date_default_timezone_set('Asia/Manila');
    }

    
    public function login()
    {
        if($this->isOnScreenTimout())
        {
            $currentTime = $this->currentTime()->format('h:i a');
            $allowedTimeFrom = $this->allowedTimeFrom()->format('h:i a');
            $allowedTimeTo = $this->allowedTimeTo()->format('h:i a');

            $data["currentTime"] = $currentTime;
            $data["allowedTimeFrom"] = $allowedTimeFrom;
            $data["allowedTimeTo"] = $allowedTimeTo;

            $this->load->view('pages/screentimeout', $data);
        }
        else
        {
            $this->load->model("Branch");

            $data["htmlBranchList"] = "";
            $result = $this->Branch->getbrCodeAndDescWithBranchExcempt();

            foreach($result->result() as $row)
                $data["htmlBranchList"] .= '<option value="'.$row->brCode.'">'.$row->brCode.' ['.$row->brDesc.']</option>';

            $this->load->view('pages/login', $data);
        }
    }

    // For ADMIN login only
    public function adminlogin()
    {
        $this->load->model("Branch");

        $data["htmlBranchList"] = "";
        $result = $this->Branch->getbrCodeAndDescWithBranchExcempt();

        foreach($result->result() as $row)
            $data["htmlBranchList"] .= '<option value="'.$row->brCode.'">'.$row->brCode.' ['.$row->brDesc.']</option>';

        $this->load->view('pages/adminlogin', $data);
    }

    public function adminAuthenticateUser()
    {
        $this->form_validation->set_rules('txtUsername', 'Username', 'trim|alpha_dash|required');
        $this->form_validation->set_rules('txtPass', 'Password', 'trim|alpha_dash|required');
        $this->form_validation->set_rules('btnSubmit', 'Submit', 'callback_adminValidateUser');
    
        if($this->form_validation->run() == false)
          $this->login();
        else
          redirect('/', 'refresh');
    }

    public function adminValidateUser()
    {
        if($this->input->post('txtUsername') =="" || $this->input->post('txtPass') == "")
        {
            $this->form_validation->set_message('validateUser', '');
            return false;
        }

        $this->load->model('UserInfo');
        
        $result = $this->UserInfo->verifyUser($this->input->post('txtUsername'), $this->input->post('txtPass'));
    
        if($result == true)
        {
            $this->session->user = array('username' => $this->UserInfo->username, 
            'fullName' => $this->UserInfo->fullName, 
            'userlvl' => $this->UserInfo->userlvl,
            'branch' => $this->input->post('cmbBranches'),
            'sessid' => $this->session->session_id);  

            $this->input->set_cookie("sessid", $this->session->user["sessid"], 60000);
    
            return true;
        }
        else
        {
            $this->form_validation->set_message('validateUser', 'Invalid username or password. ');
            return false;
        }
    }
    // ---END--- For ADMIN login only

    public function isOnScreenTimout()
    {
        $isTimeout = true;
        $currentTime = $this->currentTime();
        $allowedTimeFrom = $this->allowedTimeFrom();
        $allowedTimeTo = $this->allowedTimeTo();

        if($currentTime >= $allowedTimeFrom && $currentTime <= $allowedTimeTo)
            $isTimeout = false;

        return $isTimeout;
    }

    public function currentTime()
    {
        return DateTime::createFromFormat('h:i a', date('h:i a'));
    }

    public function allowedTimeFrom()
    {
        return DateTime::createFromFormat('h:i a', '9:00 am');
    }

    public function allowedTimeTo()
    {
        return DateTime::createFromFormat('h:i a', '10:00 pm');
    }

    public function screentimeout()
    {
        $currentTime = $this->currentTime()->format('h:i a');
        $allowedTimeFrom = $this->allowedTimeFrom()->format('h:i a');
        $allowedTimeTo = $this->allowedTimeTo()->format('h:i a');

        $data["currentTime"] = $currentTime;
        $data["allowedTimeFrom"] = $allowedTimeFrom;
        $data["allowedTimeTo"] = $allowedTimeTo;

        $this->load->view('pages/screentimeout', $data);
    }

    public function logout()
    {
        $this->session->sess_destroy();
        redirect('login', 'refresh');
    }

    public function authenticateUser()
    {
        $this->form_validation->set_rules('txtUsername', 'Username', 'trim|alpha_dash|required');
        $this->form_validation->set_rules('txtPass', 'Password', 'trim|alpha_dash|required');
        $this->form_validation->set_rules('btnSubmit', 'Submit', 'callback_validateUser');
    
        if($this->form_validation->run() == false)
          $this->login();
        else
          redirect('/', 'refresh');
    }

    public function validateUser()
    {
        if($this->input->post('txtUsername') =="" || $this->input->post('txtPass') == "")
        {
            $this->form_validation->set_message('validateUser', '');
            return false;
        }

        $this->load->model('UserInfo');
        
        $result = $this->UserInfo->verifyUser($this->input->post('txtUsername'), $this->input->post('txtPass'));
    
        if($result == true)
        {
            $this->session->user = array('username' => $this->UserInfo->username, 
            'fullName' => $this->UserInfo->fullName, 
            'userlvl' => $this->UserInfo->userlvl,
            'branch' => $this->UserInfo->branch,
            'sessid' => $this->session->session_id);  

            $this->input->set_cookie("sessid", $this->session->user["sessid"], 60000);
    
            return true;
        }
        else
        {
            $this->form_validation->set_message('validateUser', 'Invalid username or password. ');
            return false;
        }
    }

    public function isLogged()
    {
        if(isset($this->session->user) && $this->session->user["sessid"] == $this->input->cookie("sessid"))
            return true;
        else
            return false;
    }

    public function dashboard()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->view('pages/dashboard');
    }

    public function stockin()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Category");
        $this->load->model("StockIn");

        $data["selectedDate"] = date('m/d/Y');

        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);

        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->StockIn->getStockInByTransID($transID);
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
            $data["htmlTableList"] .= '<tr><td>'.$row->dr.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->qty.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';
        
        $data["htmlCategoryList"] = "";
        $result = $this->Category->getAllCategoryCodeAndDesc();

        foreach($result->result() as $row)
            $data["htmlCategoryList"] .= '<option value="'.$row->catCode.'">'.$row->catCode.' ['.$row->catDesc.']</option>';

        $this->load->view('pages/stockin', $data);
    }

    public function addStockIn()
    {
        $this->load->model("StockIn");

        $this->form_validation->set_rules('txtDRNo', 'DR No.', 'trim|required');
        $this->form_validation->set_rules('txtModelNo', 'Model No', 'trim|required');
        $this->form_validation->set_rules('txtQty', 'Quantity', 'trim|required');

        if($this->form_validation->run() == true)
        {
            $transID = $this->generateTransID($this->input->get("transDate", true));
            $recordID = $this->StockIn->getNextID($transID).$transID;
            
            $this->StockIn->recordID = $recordID;
            $this->StockIn->transID = $transID;
            $this->StockIn->dr = $this->input->post("txtDRNo");
            $this->StockIn->catCode = $this->input->post("cmbCategory");
            $this->StockIn->modelno = $this->input->post("txtModelNo");
            $this->StockIn->qty = $this->input->post("txtQty");
            $this->StockIn->transDate = $this->input->get("transDate", true);
            $this->StockIn->validated = 0;

            $this->StockIn->addStock();
        }

        //redirect('stockin?transDate='.$this->input->get("transDate", true), 'refresh');
        $this->stockin();
    }

    public function stockout()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Category");
        $this->load->model("StockOut");

        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);
            
        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->StockOut->getStockOutByTransID($transID);
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
            $data["htmlTableList"] .= '<tr><td>'.$row->vo.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->qty.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';
        
        $data["htmlCategoryList"] = "";
        $result = $this->Category->getAllCategoryCodeAndDesc();

        foreach($result->result() as $row)
            $data["htmlCategoryList"] .= '<option value="'.$row->catCode.'">'.$row->catCode.' ['.$row->catDesc.']</option>';

        $this->load->view('pages/stockout', $data);
    }

    public function addStockOut()
    {
        $this->load->model("StockOut");

        $this->form_validation->set_rules('txtVONo', 'DR No.', 'trim|required');
        $this->form_validation->set_rules('txtModelNo', 'Model No', 'trim|required');
        $this->form_validation->set_rules('txtQty', 'Quantity', 'trim|required');

        if($this->form_validation->run() == true)
        {
            $transID = $this->generateTransID($this->input->get("transDate", true));
            $recordID = $this->StockOut->getNextID($transID).$transID;
            
            $this->StockOut->recordID = $recordID;
            $this->StockOut->transID = $transID;
            $this->StockOut->vo = $this->input->post("txtVONo");
            $this->StockOut->catCode = $this->input->post("cmbCategory");
            $this->StockOut->modelno = $this->input->post("txtModelNo");
            $this->StockOut->qty = $this->input->post("txtQty");
            $this->StockOut->transDate = $this->input->get("transDate", true);
            $this->StockOut->validated = 0;

            $this->StockOut->addStock();
        }
        $this->stockout();
    }

    public function sales()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Sales");
        $this->load->model("Category");
        
        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);
        
        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->Sales->getSalesByTransID($transID);        
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
            $data["htmlTableList"] .= '<tr><td>'.$row->invoiceNum.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->custName.'</td><td>'.$row->qty.'</td><td>'.$row->price.'</td><td><div style="width:100px;">Cash: '.$row->cash.'<br>Dollar: '.$row->dollar.'<br>C Card: '.$row->creditCard.'<br>Check: '.$row->checque.'</div></td><td><div style="width:100px;">Bank Share: '.$row->bankshare.'<br>Tax Optn: '.$row->wTaxOption.'<br>W/Tax: '.$row->withholdingtax.'</div></td><td>Down: '.$row->layawayDP.'<br>Bal: '.$row->layawayBal.'<br>S Pay:'.$row->layawaySP.'<br>Full: '.$row->layawayFP.'</td><td>'.$row->misc.'</td><td>'.$row->transType.'</td><td>'.$row->remarks.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';

        $data["htmlCategoryList"] = "";
        $result = $this->Category->getAllCategoryCodeAndDesc();

        foreach($result->result() as $row)
            $data["htmlCategoryList"] .= '<option value="'.$row->catCode.'">'.$row->catCode.' ['.$row->catDesc.']</option>';

        $this->load->view('pages/sales', $data);
    }

    public function addSales()
    {
        $this->load->model("Sales");
        
        $this->form_validation->set_rules('txtInvoiceNo', 'Invoice', 'trim|required');
        $this->form_validation->set_rules('txtModelNo', 'Model No', 'trim|required');
        $this->form_validation->set_rules('txtCustomer', 'Customer Name', 'trim|required');

        if($this->form_validation->run() == true)
        {
            $transID = $this->generateTransID($this->input->get("transDate", true));
            $recordID = $this->Sales->getNextID($transID).$transID;
            $tax = 0;

            $taxOptn = intval($this->input->post("cmbWTaxOptn"));

            switch($taxOptn)
            {
                case 0:
                    $tax = floatval($this->input->post("txtCard")) * 0.005;
                    break;
                case 1:
                    $tax = (floatval($this->input->post("txtCard")) / 12) * 0.005;
                    break;
                case 2:
                    $tax = 0;
                    break;
            }
            
            $this->Sales->recordID = $recordID;
            $this->Sales->transID = $transID;
            $this->Sales->brCode = $this->session->user["branch"];
            $this->Sales->invoiceNum = $this->input->post("txtInvoiceNo");
            $this->Sales->catCode = $this->input->post("cmbCategory");
            $this->Sales->modelno = $this->input->post("txtModelNo");
            $this->Sales->custName = $this->input->post("txtCustomer");
            $this->Sales->qty = $this->input->post("txtQty");
            $this->Sales->price = $this->input->post("txtPrice");
            $this->Sales->cash = $this->input->post("txtCash");
            $this->Sales->dollar = $this->input->post("txtDollar");
            $this->Sales->creditCard = $this->input->post("txtCard");
            $this->Sales->bankshare = $this->input->post("txtBankShare");
            $this->Sales->wTaxOption = $this->input->post("cmbWTaxOptn");
            $this->Sales->withholdingtax = $tax;
            $this->Sales->layawayDP = ($this->input->post("cmbTransType") == "layawayDP") ? $this->input->post("txtTotalAmount") : 0.00;
            $this->Sales->layawayBal = ($this->input->post("cmbTransType") == "layawayDP") ? $this->input->post("txtBalance") : 0.00;
            $this->Sales->layawaySP = ($this->input->post("cmbTransType") == "layawaySP") ? $this->input->post("txtTotalAmount") : 0.00;
            $this->Sales->layawayFP = ($this->input->post("cmbTransType") == "layawayFP") ? $this->input->post("txtTotalAmount") : 0.00;
            $this->Sales->checque = $this->input->post("txtCheck");
            $this->Sales->misc = ($this->input->post("cmbTransType") == "others") ? $this->input->post("txtTotalAmount") : 0.00;
            $this->Sales->transType = $this->input->post("cmbTransType");
            $this->Sales->remarks = $this->input->post("txtRemarks");
            $this->Sales->transDate = $this->input->get("transDate", true);
            $this->Sales->validated = 0;

            $this->Sales->addSales();
        }
        $this->sales();
    }

    public function salesmaintenance()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Sales");
        $this->load->model("Category");
        
        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);
        
        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->Sales->getSalesByTransID($transID);        
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
        {
            $valid = "";
            $htmldata = "";

            if($row->validated != 0)
                $valid = "disabled";
            else
            {
                $htmldata = 'data-recordid="'.$row->recordID.'" ';
                $htmldata .= 'data-invoicenum="'.$row->invoiceNum.'" ';
                $htmldata .= 'data-transtype="'.$row->transType.'" ';
                $htmldata .= 'data-custname="'.$row->custName.'" ';
                $htmldata .= 'data-catcode="'.$row->catCode.'" ';
                $htmldata .= 'data-modelno="'.$row->modelno.'" ';
                $htmldata .= 'data-qty="'.$row->qty.'" ';
                $htmldata .= 'data-price="'.$row->price.'" ';
                $htmldata .= 'data-cash="'.$row->cash.'" ';
                $htmldata .= 'data-dollar="'.$row->dollar.'" ';
                $htmldata .= 'data-checque="'.$row->checque.'" ';
                $htmldata .= 'data-creditcard="'.$row->creditCard.'" ';
                $htmldata .= 'data-bankshare="'.$row->bankshare.'" ';
                $htmldata .= 'data-wtaxoption="'.$row->wTaxOption.'" ';
                $htmldata .= 'data-remarks="'.$row->remarks.'" ';
            }
            
            $data["htmlTableList"] .= '<tr><td><button id="btnEditSales" name="btnEditSales" type="button" '.$htmldata.' class="btn btn-xs btn-primary" data-dismiss="modal" data-toggle="modal" data-target="#mdlEditSales" '.$valid.'><span class="glyphicon glyphicon-pencil"></span></button> <button id="btnDeleteSales" name="btnDeleteSales" type="submit" class="btn btn-xs btn-danger" value="'.$row->recordID.'" '.$valid.'><span class="glyphicon glyphicon-remove"></span></button></td><td>'.$row->invoiceNum.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->custName.'</td><td>'.$row->qty.'</td><td>'.$row->price.'</td><td><div style="width:100px;">Cash: '.$row->cash.'<br>Dollar: '.$row->dollar.'<br>C Card: '.$row->creditCard.'<br>Check: '.$row->checque.'</div></td><td><div style="width:100px;">Bank Share: '.$row->bankshare.'<br>Tax Optn: '.$row->wTaxOption.'<br>W/Tax: '.$row->withholdingtax.'</div></td><td>Down: '.$row->layawayDP.'<br>Bal: '.$row->layawayBal.'<br>S Pay:'.$row->layawaySP.'<br>Full: '.$row->layawayFP.'</td><td>'.$row->misc.'</td><td>'.$row->transType.'</td><td>'.$row->remarks.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';
        }

        $data["htmlCategoryList"] = "";
        $result = $this->Category->getAllCategoryCodeAndDesc();

        foreach($result->result() as $row)
            $data["htmlCategoryList"] .= '<option value="'.$row->catCode.'">'.$row->catCode.' ['.$row->catDesc.']</option>';

        $this->load->view('pages/salesmaintenance', $data);
    }

    public function salesmaintenanceedit()
    {
        $this->load->model("Sales");
        
        $this->form_validation->set_rules('txtInvoiceNo', 'Invoice', 'trim|required');
        $this->form_validation->set_rules('txtModelNo', 'Model No', 'trim|required');
        $this->form_validation->set_rules('txtCustomer', 'Customer Name', 'trim|required');

        if($this->form_validation->run() == true)
        {
            //$transID = $this->generateTransID($this->input->get("transDate", true));
            $recordID = $this->input->post("hdnRecordID");
            $tax = 0;

            $taxOptn = intval($this->input->post("cmbWTaxOptn"));

            switch($taxOptn)
            {
                case 0:
                    $tax = floatval($this->input->post("txtCard")) * 0.005;
                    break;
                case 1:
                    $tax = (floatval($this->input->post("txtCard")) / 12) * 0.005;
                    break;
                case 2:
                    $tax = 0;
                    break;
            }
            
            //$this->Sales->recordID = $recordID;
            //$this->Sales->transID = $transID;
            //$this->Sales->brCode = $this->session->user["branch"];
            $updateColumn = array(
                "invoiceNum" => $this->input->post("txtInvoiceNo"),
                "catCode" => $this->input->post("cmbCategory"),
                "modelno" => $this->input->post("txtModelNo"),
                "custName" => $this->input->post("txtCustomer"),
                "qty" => $this->input->post("txtQty"),
                "price" => $this->input->post("txtPrice"),
                "cash" => $this->input->post("txtCash"),
                "dollar" => $this->input->post("txtDollar"),
                "creditCard" => $this->input->post("txtCard"),
                "bankshare" => $this->input->post("txtBankShare"),
                "wTaxOption" => $this->input->post("cmbWTaxOptn"),
                "withholdingtax" => $tax,
                "layawayDP" => ($this->input->post("cmbTransType") == "layawayDP") ? $this->input->post("txtTotalAmount") : 0.00,
                "layawayBal" => ($this->input->post("cmbTransType") == "layawayDP") ? $this->input->post("txtBalance") : 0.00,
                "layawaySP" => ($this->input->post("cmbTransType") == "layawaySP") ? $this->input->post("txtTotalAmount") : 0.00,
                "layawayFP" => ($this->input->post("cmbTransType") == "layawayFP") ? $this->input->post("txtTotalAmount") : 0.00,
                "checque" => $this->input->post("txtCheck"),
                "misc" => ($this->input->post("cmbTransType") == "others") ? $this->input->post("txtTotalAmount") : 0.00,
                "transType" => $this->input->post("cmbTransType"),
                "remarks" => $this->input->post("txtRemarks"),
                "transDate" => $this->input->get("transDate", true),
                "validated" => 0
            );
            

            $this->Sales->editSales($recordID, $updateColumn);
        }
        $this->salesmaintenance();
    }

    public function salesmaintenancedelete()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Sales");

        $this->Sales->deleteSales($this->input->post("btnDeleteSales"));
        
        $this->salesmaintenance();
    }

    public function stockinmaintenance()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("StockIn");
        
        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);
        
        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->StockIn->getStockInByTransID($transID);        
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
            $data["htmlTableList"] .= '<tr><td><button id="btnDeleteStockIn" name="btnDeleteStockIn" type="submit" class="btn btn-primary" value="'.$row->recordID.'">Delete</button></td><td>'.$row->dr.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->qty.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';

        $this->load->view('pages/stockinmaintenance', $data);
    }

    public function stockinmaintenancedelete()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("StockIn");

        $this->StockIn->deleteStockIn($this->input->post("btnDeleteStockIn"));
        
        $this->stockinmaintenance();
    }

    public function stockoutmaintenance()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("StockOut");
        
        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);
        
        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->StockOut->getStockOutByTransID($transID);        
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
            $data["htmlTableList"] .= '<tr><td><button id="btnDeleteStockOut" name="btnDeleteStockOut" type="submit" class="btn btn-primary" value="'.$row->recordID.'">Delete</button></td><td>'.$row->vo.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->qty.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';

        $this->load->view('pages/stockoutmaintenance', $data);
    }

    public function stockoutmaintenancedelete()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("StockOut");

        $this->StockOut->deleteStockOut($this->input->post("btnDeleteStockOut"));
        
        $this->stockoutmaintenance();
    }

    public function categorysettings()
    {
        if(!$this->isLogged())
        redirect('login', 'refresh');

        $this->load->model("Category");
        $this->load->model("CategorySettings");
            
        $data["htmlTableList"] = "";   
        $result = $this->CategorySettings->getCategorysettingsByBrCode($this->session->user["branch"]);

        foreach($result->result() as $row)
            $data["htmlTableList"] .= '<tr><td><input id="categories[]" name="categories[]" value="'.$row->catCode.'" type="checkbox"></td><td>'.$row->orderNo.'</td><td>'.$row->catCode.'</td></tr>';
            
        $data["htmlCategoryList"] = "";
        $result = $this->Category->getAllCategoryCodeAndDesc();

        foreach($result->result() as $row)
            $data["htmlCategoryList"] .= '<option value="'.$row->catCode.'">'.$row->catCode.' ['.$row->catDesc.']</option>';

        $this->load->view('pages/categorysettings', $data);    
    }

    public function addCategorySetting()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("CategorySettings");

        $this->CategorySettings->brCode = $this->session->user["branch"];
        $this->CategorySettings->catCode = $this->input->post("cmbCategory");
        $this->CategorySettings->orderNo = $this->CategorySettings->getNextOrderNo($this->session->user["branch"]);
        
        $this->CategorySettings->addCategorySettings();
        $this->categorysettings();
    }

    public function deleteCategorySetting()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("CategorySettings");

        $catList = $this->input->post("categories");

        foreach($catList as $cat)
            $this->CategorySettings->deleteCategory($this->session->user["branch"], $cat);        

        $this->categorysettings();
    }


    /**
     * Beginning Inventory
     * --- Beginning From Category Settings
     */

    public function beginninginventory()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');
        
        $this->load->model("StoreInventory");
        $this->load->model("CategorySettings");

        $data["btnSave"] = "";
        $data["btnReset"] = "disabled";

        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);

        $transID = $this->generateTransID($data["selectedDate"]);
        $data["transactionID"] = $transID;

        $data["htmlTableList"] = "";   
        $result = $this->StoreInventory->getStoreInventoryByTransID($transID);

        if($result->num_rows() > 0)
        {
            foreach($result->result() as $row)
                $data["htmlTableList"] .= '<tr><td>'.$row->sortOrder.'</td><td>'.$row->catCode.'</td><td>'.$row->bQty.'</td></tr>';
            
            $data["btnSave"] = "disabled";
            $data["btnReset"] = "";
        }
        else
        {
            $result = $this->CategorySettings->getCategorysettingsByBrCode($this->session->user["branch"]);

            foreach($result->result() as $row)
                $data["htmlTableList"] .= '<tr><td>'.$row->orderNo.'</td><td>'.$row->catCode.'</td><td><input type="number" class="form-control" id="txtBQty[]" name="txtBQty[]" value="0" min="0" step="1" ><input type="hidden" id="txtCat[]" name="txtCat[]" value="'.$row->catCode.'"></td></tr>';
        }
        
        $this->load->view('pages/beginninginventory', $data);  
    }

    public function resetBeginninginventory()
    {
        $this->load->model("StoreInventory");
        $this->load->model("StoreTransaction");

        if(!$this->isLogged())
            redirect('login', 'refresh');

        $transid = $this->generateTransID($this->input->get("transDate", true));

        $this->StoreInventory->deleteStoreInventoryByTransId($transid);
        $this->StoreTransaction->deleteStoreTransactionByTransId($transid);

        redirect('beginninginventory', 'refresh');
    }

    public function saveBeginningInventory()
    {
        $this->load->model("StoreInventory");

        $bQtyList = $this->input->post("txtBQty");
        $catList = $this->input->post("txtCat");
        $transID = $this->generateTransID($this->input->get("transDate", true));
        //$nextID = $this->StoreInventory->getNextID($transID);
        $storeInventory = array();

        for($i=0; $i<count($bQtyList); $i++)
        {
            $sInventory = new $this->StoreInventory();
            $sInventory->recordID = ($i + 1).$transID;
            $sInventory->transID = $transID;
            $sInventory->catCode = $catList[$i];
            $sInventory->bQty = $bQtyList[$i];
            $sInventory->eQty = 0;
            $sInventory->transDate = $this->convertToMysqlFormatDate($this->input->get("transDate", true));
            $sInventory->sortOrder = $i+1;

            $storeInventory[] = $sInventory;
            //$this->StoreInventory->addStoreInventory();
        }

        $this->StoreInventory->addStoreInventoryBatch($storeInventory);

        $this->beginninginventory();
    }

    /**
     * End of --- Beginning From Category Settings
     * 
     * Start of Beginning from previous dates
     */

    public function beginninginventoryPrevDate()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');
        
        $this->load->model("StoreInventory");

        $data["btnSave"] = "";
        $data["btnReset"] = "disabled";

        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);

        $transID = $this->generateTransID($data["selectedDate"]);
        $data["transactionID"] = $transID;

        $data["htmlTableList"] = "";   
        $result = $this->StoreInventory->getStoreInventoryByTransID($transID);

        if($result->num_rows() > 0)
        {
            foreach($result->result() as $row)
                $data["htmlTableList"] .= '<tr><td>'.$row->sortOrder.'</td><td>'.$row->catCode.'</td><td>'.$row->bQty.'</td></tr>';
            
            $data["btnSave"] = "disabled";
            $data["btnReset"] = "";
        }
        else
        {
            //$result = $this->CategorySettings->getCategorysettingsByBrCode($this->session->user["branch"]);

            $transIDYesterday = $this->generateTransID($this->subtractOneDay($data["selectedDate"]));
            
            $yesterdayResult = $this->StoreInventory->getStoreInventoryByTransID($transIDYesterday);

            foreach($yesterdayResult->result() as $row)
                $data["htmlTableList"] .= '<tr><td>'.$row->sortOrder.'</td><td>'.$row->catCode.'</td><td><input type="number" class="form-control" id="txtBQty[]" name="txtBQty[]" value="'.$row->eQty.'" min="0" step="1" ><input type="hidden" id="txtCat[]" name="txtCat[]" value="'.$row->catCode.'"></td></tr>';
        }
        
        $this->load->view('pages/beginninginventoryprevdate', $data);  
    }

    public function resetBeginninginventoryPrevDate()
    {
        $this->load->model("StoreInventory");
        $this->load->model("StoreTransaction");

        if(!$this->isLogged())
            redirect('login', 'refresh');

        $transid = $this->generateTransID($this->input->get("transDate", true));

        $this->StoreInventory->deleteStoreInventoryByTransId($transid);
        $this->StoreTransaction->deleteStoreTransactionByTransId($transid);

        redirect('beginninginventoryPrevDate', 'refresh');
    }

    public function saveBeginningInventoryPrevDate()
    {
        $this->load->model("StoreInventory");

        $bQtyList = $this->input->post("txtBQty");
        $catList = $this->input->post("txtCat");
        $transID = $this->generateTransID($this->input->get("transDate", true));

        $storeInventory = array();

        for($i=0; $i<count($bQtyList); $i++)
        {
            $sInventory = new $this->StoreInventory();
            $sInventory->recordID = ($i + 1).$transID;
            $sInventory->transID = $transID;
            $sInventory->catCode = $catList[$i];
            $sInventory->bQty = $bQtyList[$i];
            $sInventory->eQty = 0;
            $sInventory->transDate = $this->convertToMysqlFormatDate($this->input->get("transDate", true));
            $sInventory->sortOrder = $i+1;

            $storeInventory[] = $sInventory;
        }

        $this->StoreInventory->addStoreInventoryBatch($storeInventory);

        $this->beginninginventoryPrevDate();
    }


    /**
     * End of Beginning Inventory
     * 
     * Start if Ending Inventory
     */

    public function endinginventory()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');
        
        $this->load->model("StoreInventory");
        $this->load->model("StoreTransaction");

        $data["btnSave"] = "";

        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);

        $transID = $this->generateTransID($data["selectedDate"]);

        $data["htmlTableList"] = "";   
        $result = $this->StoreInventory->getStoreInventoryByTransID($transID);
        $processedStoreTrans = $this->StoreTransaction->getStoreTransactionByTransID($transID);

        if($result->num_rows() > 0)
        {
            $isReadOnly = ($processedStoreTrans->num_rows() > 0) ? true : false;
            
            foreach($result->result() as $row)
            {
                if($isReadOnly)
                    $data["htmlTableList"] .= '<tr><td>'.$row->sortOrder.'</td><td>'.$row->catCode.'</td><td>'.$row->bQty.'</td><td>'.$row->eQty.'</td></tr>';
                else
                    $data["htmlTableList"] .= '<tr><td>'.$row->sortOrder.'</td><td>'.$row->catCode.'</td><td><input type="number" class="form-control" id="txtBQty[]" name="txtBQty[]" value="'.$row->bQty.'" min="0" step="1" ></td><td><input type="number" class="form-control" id="txtEQty[]" name="txtEQty[]" value="0" min="0" step="1" ><input type="hidden" id="txtRecordID[]" name="txtRecordID[]" value="'.$row->recordID.'"></td></tr>';
            }

            if($isReadOnly) 
            {
                $data["btnSave"] = "disabled";
                $data["htmlStoreTrans"] = $processedStoreTrans->row();
            }
        }
        else
        {
            $data["htmlTableList"] .= '<tr><td colspan="3">Did not performed beginning inventory yet</td></tr>';
            $data["btnSave"] = "disabled";
        }

        $this->load->view('pages/endinginventory', $data);  
    }

    public function saveEndingInventory()
    {
        $this->load->model("StoreInventory");
        $this->load->model("StoreTransaction");
        
        $recordIDList = $this->input->post("txtRecordID");
        $bQtyList = $this->input->post("txtBQty");
        $eQtyList = $this->input->post("txtEQty");

        for($i=0; $i<count($recordIDList); $i++)
        {
            $this->StoreInventory->updateStoreInventory($recordIDList[$i], $bQtyList[$i], $eQtyList[$i]);
        }

        $transID = $this->generateTransID($this->input->get("transDate", true));
        $recordID = $this->StoreTransaction->getNextID($transID).$transID;
        
        $this->StoreTransaction->recordID = $recordID;
        $this->StoreTransaction->transID = $transID;
        $this->StoreTransaction->brCode = $this->session->user["branch"];
        $this->StoreTransaction->cash = $this->input->post("txtCash");
        $this->StoreTransaction->checque = $this->input->post("txtCheck");
        $this->StoreTransaction->dollar = $this->input->post("txtDollar");
        $this->StoreTransaction->ccard = $this->input->post("txtCreditCard");
        $this->StoreTransaction->preparedBy = $this->input->post("txtPreparedBy");
        $this->StoreTransaction->remarks = $this->input->post("txtRemarks");
        $this->StoreTransaction->addStoreTransaction();

        $this->endinginventory();
    }

    /**
     * End of Ending Inventory
     * 
     * Start of Store Transaction
     */

    public function storetransmaintenance()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("StoreTransaction");

        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);

        $transID = $this->generateTransID($data["selectedDate"]);

        $data["htmlTableList"] = "";   
        $processedStoreTrans = $this->StoreTransaction->getStoreTransactionByTransID($transID);

        $data["htmlStoreTrans"] = $processedStoreTrans->row();

        $this->load->view('pages/storetransmaintenance', $data);
        }

        public function updateStoreTransMaintenance()
        {
        $this->load->model("StoreTransaction");

        $this->StoreTransaction->recordID = $this->input->post("hdnRecordID");
        $this->StoreTransaction->cash = $this->input->post("txtCash");
        $this->StoreTransaction->checque = $this->input->post("txtCheck");
        $this->StoreTransaction->dollar = $this->input->post("txtDollar");
        $this->StoreTransaction->ccard = $this->input->post("txtCreditCard");
        $this->StoreTransaction->preparedBy = $this->input->post("txtPreparedBy");
        $this->StoreTransaction->remarks = $this->input->post("txtRemarks");
        $this->StoreTransaction->updateStoreTransaction();

        $this->storetransmaintenance();
    }

    /**
     * End of Store Transaction
    */

    public function emailSending()
    {
        $data["result"] = 2;

        if($this->input->get("transDate", true) != null)
        {
            if(!$this->isLogged())
                redirect('login', 'refresh');

            $transID = $this->generateTransID($this->input->get("transDate", true));

            $config['protocol'] = 'sendmail';
            $config['mailtype'] = 'html';
            $config['wordwrap'] = TRUE;
            $config['charset'] = 'iso-8859-1';

            $this->load->library('email');
            $this->email->initialize($config);
            
            $this->email->from('no-reply@karatworld.net');
            $this->email->to('fsg@karatworld.net, mvg@karatworld.net, amf@karatworld.net, mjb@karatworld.net, igj@karatworld.net, cqg@karatworld.net, eff@karatworld.net, majb@karatworld.net, sbt@karatworld.net');
            // sandrasarabiag@yahoo.com --> removed because of qouta sending to outside email
            //$this->email->to('lbeldia@gmail.com, paulcortez0591@yahoo.com');
            
            $this->email->subject("SR1 Report (Mobile) of " . $this->session->user["branch"] . " branch as of " . $this->input->get("transDate", true));
    
            $msg = "<br />Good Day, <br />" .
                    "<br />Link for <a href=\"http://host2048.temp.domains/~karatwor/applications/webFunctions/cimsReports/inventoryReport.php?keyrequest=4c674b4c417766106df70e7a0b93ef67&transID=" . $transID . "&brCode=" . $this->session->user["branch"] . "&transDate=" . $this->input->get("transDate", true) . "\">SR1 Inventory Report</a><br />" .
                    "<br />Link for <a href=\"http://host2048.temp.domains/~karatwor/applications/webFunctions/cimsReports/salesReport.php?keyrequest=4c674b4c417766106df70e7a0b93ef67&transID=" . $transID . "&brCode=" . $this->session->user["branch"] . "&transDate=" . $this->input->get("transDate", true) . "\">SR1 Sales Report</a> ";

            $this->email->message($msg);
            
            $data["result"] = $this->email->send();
        }
        
        $this->load->view('pages/emailsending', $data);
    }

    public function viewreport()
    {
        $data["SIRLink"] = "";
        $data["SR1Link"] = "";

        if($this->input->get("transDate", true) != null)
        {
            $transID = $this->generateTransID($this->input->get("transDate", true));

            $data["SIRLink"] = "http://host2048.temp.domains/~karatwor/applications/webFunctions/cimsReports/inventoryReport.php?keyrequest=4c674b4c417766106df70e7a0b93ef67&transID=" . $transID . "&brCode=" . $this->session->user["branch"] . "&transDate=" . $this->input->get("transDate", true);
            $data["SR1Link"] = "http://host2048.temp.domains/~karatwor/applications/webFunctions/cimsReports/salesReport.php?keyrequest=4c674b4c417766106df70e7a0b93ef67&transID=" . $transID . "&brCode=" . $this->session->user["branch"] . "&transDate=" . $this->input->get("transDate", true);
        }
        
        $this->load->view('pages/report', $data);
    }

    public function generateTransID($mmddyyDate)
    {
        $dateFormated = DateTime::createFromFormat('m/d/Y', $mmddyyDate);
		return $this->session->user["branch"] . $dateFormated->format('Ymd');
    }

    public function convertToMysqlFormatDate($mmddyyDate)
    {
        $dateFormatedtransDate = DateTime::createFromFormat('m/d/Y', $mmddyyDate);
		return $dateFormatedtransDate->format('Y-m-d');
    }

    public function isDateValid($dateToCheck)
    {
        $dateToCheck = trim($dateToCheck);

        if($dateToCheck == "")
            return false;

        if(!preg_match("/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/i", $dateToCheck))
            return false;

        return true;
    }

    public function subtractOneDay($currentDate)
    {
        return date('m/d/Y', strtotime('-1 day', strtotime($currentDate)));
    }


    /**
     * Karat Card Methods
     */

    public function getLatestUsers()
    {
        $limit = $this->input->post("limit");
        $users = array(
            array("customerid"=>$limit, 
            "lastname"=>"beldia",
            "firstname"=>"leo",
            "dob"=>"1984-1-1",
            "contactinfo"=>"123",
            "emailadd"=>"as@yahoo.com",
            "editdate"=>"2019-11-4",
            "creationdate"=>"2019-11-4"),
            array("customerid"=>"2", 
            "lastname"=>"beldia",
            "firstname"=>"mae",
            "dob"=>"1986-1-1",
            "contactinfo"=>"124",
            "emailadd"=>"hehe@yahoo.com",
            "editdate"=>"2019-11-4",
            "creationdate"=>"2019-11-4")
        );

        echo json_encode($users);
    }

    public function addNewCustomer()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $dob = $this->input->post("dob");

        if(!$this->isDateValid($dob))
            echo json_encode(array("success"=>false, "data" => "Invalid Date Format"));

        $this->load->model("Customer");
        
        $this->Customer->lastname = $this->input->post("lastname");
        $this->Customer->firstname = $this->input->post("firstname");
        $this->Customer->dob = $this->convertToMysqlFormatDate($dob);
        $this->Customer->contactinfo = $this->input->post("contactinfo");
        $this->Customer->emailadd = $this->input->post("emailadd");
        $this->Customer->address = $this->input->post("address");

        echo json_encode($this->Customer->addNewCustomer());
    }

    public function addNewCustomerCard()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $dob = $this->input->post("dob");
        $purchasedate = $this->input->post("purchasedate");
        $expirydate = $this->input->post("expirydate");

        if(!$this->isDateValid($dob))
        {
            echo json_encode(array("success"=>false, "data" => "Invalid Date Format"));
            return;
        }

        if(!$this->isDateValid($purchasedate))
        {
            echo json_encode(array("success"=>false, "data" => "Invalid Date Format"));
            return;
        }

        if(!$this->isDateValid($expirydate))
        {
            echo json_encode(array("success"=>false, "data" => "Invalid Date Format"));
            return;
        }

        $this->load->model("Customer");
        
        $this->Customer->lastname = $this->input->post("lastname");
        $this->Customer->firstname = $this->input->post("firstname");
        $this->Customer->dob = $this->convertToMysqlFormatDate($dob);
        $this->Customer->contactinfo = $this->input->post("contactinfo");
        $this->Customer->emailadd = $this->input->post("emailadd");
        $this->Customer->address = $this->input->post("address");

        $result = $this->Customer->addNewCustomer();

        if($result["success"] == true)
        {
            $this->load->model("Kcardtransaction");

            $this->Kcardtransaction->kcardno = $this->input->post("kcardno");
            $this->Kcardtransaction->customerid = $result["data"];
            $this->Kcardtransaction->invoiceno = $this->input->post("invoiceno");
            $this->Kcardtransaction->purchasedate = $this->convertToMysqlFormatDate($purchasedate);
            $this->Kcardtransaction->expirydate = $this->convertToMysqlFormatDate($expirydate);
            $this->Kcardtransaction->brcode = $this->input->post("brcode");
            $this->Kcardtransaction->isactive = 1;

            echo json_encode($this->Kcardtransaction->addNewCardTransaction());
        }
        else
            echo json_encode(array("success"=>false, "data" => "Failed to add new customer"));
    }

    public function renewCustomerCard()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $purchasedate = $this->input->post("purchasedate");
        $expirydate = $this->input->post("expirydate");

        if(!$this->isDateValid($purchasedate))
        {
            echo json_encode(array("success"=>false, "data" => "Invalid Date Format"));
            return;
        }

        if(!$this->isDateValid($expirydate))
        {
            echo json_encode(array("success"=>false, "data" => "Invalid Date Format"));
            return;
        }

        $this->load->model("Kcardtransaction");
        
        $result = $this->Kcardtransaction->deactivateCard($this->input->post("transid"));

        if($result["success"] == true)
        {
            $this->Kcardtransaction->kcardno = $this->input->post("kcardno");
            $this->Kcardtransaction->customerid = $this->input->post("customerid");
            $this->Kcardtransaction->invoiceno = $this->input->post("invoiceno");
            $this->Kcardtransaction->purchasedate = $this->convertToMysqlFormatDate($purchasedate);
            $this->Kcardtransaction->expirydate = $this->convertToMysqlFormatDate($expirydate);
            $this->Kcardtransaction->brcode = $this->input->post("brcode");
            $this->Kcardtransaction->isactive = 1;

            echo json_encode($this->Kcardtransaction->addNewCardTransaction());
        }
        else
            echo json_encode(array("success"=>false, "data" => "Failed to deactivate current card from transaction ID: ".$this->input->post("transid")));
    }

    public function deactivateCustomerCard()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Kcardtransaction");
        
        echo json_encode($this->Kcardtransaction->deactivateCard($this->input->post("transid")));
    }

    public function kcardStatus()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Kcardtransaction");

        $result = $this->Kcardtransaction->getCardTransactionWithMinCustInfoByKCardNo($this->input->post("kcardno"));

        if($result->num_rows() > 0)
            echo json_encode(array("success"=>true, "data" => $result->row()));
        else
            echo json_encode(array("success"=>false, "data" => "No Record"));
    }

    // End of Karat Card Methods

    /**
 * Karat Card Views
 */

    public function customer()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Customer");
        $result = $this->Customer->getAllCustomerOrderBy("editdate", "DESC");

        $i=1;
        $data["htmlTableList"] = ''; 

        foreach($result->result() as $row)
        {
            $data["htmlTableList"] .= '<tr><td>'.$i.'</td><td>'.$row->customerid.'</td><td>'.$row->lastname.'</td><td>'.$row->firstname.'</td><td>'.$row->dob.'</td><td>'.$row->contactinfo.'</td><td>'.$row->emailadd.'</td><td>'.$row->address.'</td><td>'.$row->creationdate.'</td><td>'.$row->editdate.'</td></tr>'; 
            $i++;
        }

        $this->load->view('pages/customer', $data);
        }

        public function kcardtransaction()
        {
        if(!$this->isLogged())
            redirect('login', 'refresh');
        
        $this->load->model("Kcardtransaction");
        $result = $this->Kcardtransaction->getCardTransactionWithMinCustInfoOrderBy("kcardtransaction.editdate", "DESC", $this->session->user["branch"]);
        
        $i=1;
        $data["htmlTableList"] = ''; 

        foreach($result->result() as $row)
        {
            if(strtotime($row->expirydate) > strtotime(date("Y-m-d H:i:s")))
                $data["htmlTableList"] .= '<tr><td>'.$i.'</td><td>'.$row->customerid.'</td><td>'.$row->lastname.'</td><td>'.$row->firstname.'</td><td>'.$row->kcardno.'</td><td>'.$row->invoiceno.'</td><td>'.$row->purchasedate.'</td><td>'.$row->expirydate.'</td><td>'.$row->editdate.'</td><td><span class="glyphicon glyphicon-pencil"></span></td></tr>'; 
            else
                $data["htmlTableList"] .= '<tr><td>'.$i.'</td><td>'.$row->customerid.'</td><td>'.$row->lastname.'</td><td>'.$row->firstname.'</td><td>'.$row->kcardno.'</td><td>'.$row->invoiceno.'</td><td>'.$row->purchasedate.'</td><td style="background-color:red">'.$row->expirydate.'</td><td>'.$row->editdate.'</td><td><span class="glyphicon glyphicon-pencil"></span></td></tr>'; 
            
            $i++;
        }

        $this->load->view('pages/kcardtransaction', $data);
    }
    // End of Karat Card Views


    /**
     * Store Item Inquiry Methods
    */

    public function getItemInfo()
    {
        if(!$this->isLogged())
        redirect('login', 'refresh');
    
        $this->load->model("Items");
        $this->load->model("BranchItemLedger");
        $this->load->model("ItemLedger");
        $this->load->model("ItemInquiryLog");

        $result = $this->Items->getItemInfoByModelNo($this->input->post("modelno"));
        $row = $result->row();

        $resultBranches = $this->BranchItemLedger->getDataByItemcodeWithBranchExcempt($row->itemcode);

        $resultKWH = $this->ItemLedger->getItemLedgerOfKWHByItemcode($row->itemcode);
        $kwhRow = $resultKWH->row();

        // Log searched item
        $this->ItemInquiryLog->itemcode = $row->itemcode;
        $this->ItemInquiryLog->modelno = $row->modelno;
        $this->ItemInquiryLog->catCode = $row->catCode;
        $this->ItemInquiryLog->brCode = $this->session->user["branch"];
        $this->ItemInquiryLog->searchedBy = $this->session->user["username"];
        $this->ItemInquiryLog->dateSearched = date('m/d/Y');
        $this->ItemInquiryLog->addNewData();
        // --- END --- Log searched item

        $htmlTable = "";

        foreach($resultBranches->result() as $rowBranches )
        {
            $htmlTable .= "<tr><td>" . $rowBranches->itemcode . "</td><td>" . $rowBranches->brCode . "</td><td>" . $rowBranches->endingqty . "</td></tr>";
        }

        if($result->num_rows() > 0)
            echo json_encode(array("success"=>true, "data" => $row, "htmlTable" => $htmlTable, "KWHData" => $kwhRow->endingqty));
        else
            echo json_encode(array("success"=>false, "data" => "No Record"));
    }

    // End of Item Iquiry Methods


    /**
     * Branch Initial Inventory
    */
    
    public function initialbranchinventory()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $data["errorMessage"] = "";

        if($this->input->post("btnUploadData") == "Upload File")
        {
            $newFilename = $this->session->user["branch"] . "_NewInventory";
            $newURLpath = site_url() . "uploads/tempfiles/";

            $config['upload_path']          = './uploads/tempfiles';
            $config['file_name']            = $newFilename;
            $config['allowed_types']        = 'csv|txt';
            $config['overwrite']            = TRUE;

            $this->load->library('upload', $config);

            if (!$this->upload->do_upload('fileUpload'))
            {
                $data["uploadedData"] = array('status' => 'failed', 'upload_data' =>  '', 'sourceFilename' => '');
                $data["errorMessage"] = $this->upload->display_errors();
            }
            else
            {
                $fileURLFullPath = $newURLpath . $this->upload->data("file_name");
                $rawFileContent = file($fileURLFullPath);
                $fileContentInHtml = "";
                $tempNewStoreInventoryList = array();

                $this->load->model("TempNewStoreInventory");
                
                foreach($rawFileContent as $lineData)
                {
                    $tempContent = str_getcsv($lineData);

                    $tempNewStoreInventoryList[] = array("brCode"=>$this->session->user["branch"], "itemcode"=>0, "modelno"=>$tempContent[0], "qty"=>$tempContent[1], "sourceFilename"=>$this->upload->data("file_name"));
                }

                //Prepare TempNewStoreInventory table
                $this->TempNewStoreInventory->deleteByBranch($this->session->user["branch"]);

                //Add record to TempNewStoreInventory and update itemcode
                $this->TempNewStoreInventory->addNewMultipleData($tempNewStoreInventoryList);
                $this->TempNewStoreInventory->updateItemcodeFromItemsByBranchSourceFilename($this->session->user["branch"], $this->upload->data("file_name"));

                $result = $this->TempNewStoreInventory->getDataByBranchSourceFilename($this->session->user["branch"], $this->upload->data("file_name"));

                $i = 0;
                $totalQty = 0;
                $noItemcode = 0;
                $duplicateItem = 0;
                foreach($result->result() as $row)
                {
                    $modelNo = $row->modelno;

                    if(str_contains($fileContentInHtml, "<td>".$modelNo."</td>"))
                    {
                        $duplicateItem++;
                        $modelNo .= "(duplicate)";
                    }

                    $fileContentInHtml .= "<tr><td>".$row->itemcode."</td><td>".$modelNo."</td><td>".$row->qty."</td></tr>";
                    $i++; $totalQty += $row->qty;

                    if($row->itemcode == 0) $noItemcode++;
                }
                
                $fileContentInHtml .= "<tr><td>Missing/Duplicate item: ".$noItemcode."/".$duplicateItem."</td><td>Total records on file: ".count($tempNewStoreInventoryList)." and ".$i." records added.</td><td>Total Qty: ".$totalQty."</td></tr>";

                if($noItemcode > 0 || $duplicateItem > 0)
                {
                    $data["btnDisabled"] = "disabled";
                    $data["errorMessage"] = "Itemcode is required in creating initial inventory. Make suse that your Model Number does not contain addtional space at the end, does not have space in-between dash symbol of Model Number or has a valid Modelo Number. No duplication of item also. Check for any duplicate Model Number in your file. If ptoblrm id occting still, please report to IT department.";
                }

                // Tell the user that it has no record
                if($fileContentInHtml == "")
                    $fileContentInHtml = "<tr><td>No Record</td><td>-</td><td>-</td></tr>";

                $data["uploadedData"] = array('status' => 'success', 'upload_data' => $fileContentInHtml, 'sourceFilename' => $this->upload->data("file_name"));
            }
        }
        
        $this->load->view('pages/initialbranchinventory', $data);
    }

    public function initialBranchInventoryApply()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("TempNewStoreInventory");
        $this->load->model("BranchItemLedger");

        $sourceFilename = $this->input->post("sourceFilename");
        $branchItemLedger = array();

        $result = $this->TempNewStoreInventory->getDataByBranchSourceFilename($this->session->user["branch"], $sourceFilename);

        foreach($result->result() as $row)
        {
            if($row->qty > 0)
                $branchItemLedger[] = array('itemcode'=>$row->itemcode,'brCode'=>$this->session->user["branch"],'beginningqty'=>$row->qty,'inqty'=>0,'outqty'=>0,'sales'=>0,'adjustment'=>0,'endingqty'=>$row->qty,'editDate'=>date('Y-m-d'),'creationDate'=>date('Y-m-d'),'remarks'=>'');
        }

        $this->BranchItemLedger->prepareNewInventory($this->session->user["branch"], $branchItemLedger);

        $this->branchitemledger();
    }

    public function branchitemledger()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("BranchItemLedger");

        $result = $this->BranchItemLedger->getDataViewByBrCode($this->session->user["branch"]);

        $data["htmlTableData"] = "";

        $currentCategory = "";
        $subTotalBQty = 0;
        $subtotalInQty = 0;
        $subtotalOutQty = 0;
        $subtotalSalesQty = 0;
        $subtotalAdjQty = 0;
        $subtotalEQty = 0;
        

        foreach($result->result() as $row)
        {
            if($currentCategory != $row->catCode)
            {
                if($currentCategory != "")
                {
                    $data["htmlTableData"] .= '<tr><td colspan="3"><b>Total:</b></td><td>'.$subTotalBQty.'</td><td>'.$subtotalInQty.'</td><td>'.$subtotalOutQty.'</td><td>'.$subtotalSalesQty.'</td><td>'.$subtotalAdjQty.'</td><td><b>'.$subtotalEQty.'</b></td><td colspan="3">&nbsp;</td></tr>';
                    $subTotalBQty = 0;
                    $subtotalInQty = 0;
                    $subtotalOutQty = 0;
                    $subtotalSalesQty = 0;
                    $subtotalAdjQty = 0;
                    $subtotalEQty = 0;
                }

                $data["htmlTableData"] .= '<tr><td colspan="12" style="background-color:#e6f2ff"><b>Category: <span class="text-light-blue">'.$row->catCode.'</span></b></td></tr>';
            }
            
            $data["htmlTableData"] .= '<tr><td>'.$row->itemcode.'</td><td><a href="/itemmovementhistory?mts='.$row->modelno.'" target="_blank">'.$row->modelno.'</a></td><td>'.$row->catCode.'</td><td>'.$row->beginningqty.'</td><td>'.$row->inqty.'</td><td>'.$row->outqty.'</td><td>'.$row->sales.'</td><td>'.$row->adjustment.'</td><td>'.$row->endingqty.'</td><td>'.date('m/d/Y', strtotime($row->editDate)).'</td><td>'.date('m/d/Y', strtotime($row->creationDate)).'</td><td>'.$row->remarks.'</td></tr>';

            $subTotalBQty += $row->beginningqty;
            $subtotalInQty += $row->inqty;
            $subtotalOutQty += $row->outqty;
            $subtotalSalesQty += $row->sales;
            $subtotalAdjQty += $row->adjustment;
            $subtotalEQty += $row->endingqty;

            $currentCategory = $row->catCode;
        }

        $data["htmlTableData"] .= '<tr><td colspan="3"><b>Total:</b></td><td>'.$subTotalBQty.'</td><td>'.$subtotalInQty.'</td><td>'.$subtotalOutQty.'</td><td>'.$subtotalSalesQty.'</td><td>'.$subtotalAdjQty.'</td><td><b>'.$subtotalEQty.'</b></td><td colspan="3">&nbsp;</td></tr>';
        
        $this->load->view('pages/branchitemledger', $data);
    }


      // End of Branch Initial Inventory


      /**
       * Methods and processes under development phase
       */


    public function stockinnew()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Category");
        $this->load->model("StockIn");
        $this->load->model("BranchDeliveryView");

        $data["htmlBrDeliveryList"] = '<tr><td colspan="5">No Record</td></tr>';
        
        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);

        if($this->input->get("drNo", true) != null)
        {
            $data["drNo"] = $this->input->get("drNo", true);

            $result = $this->BranchDeliveryView->getDataByTransIDBrCode($this->input->get("drNo", true), $this->session->user["branch"]);

            $data["htmlBrDeliveryList"] = "";
            foreach($result->result() as $row)
                $data["htmlBrDeliveryList"] .= '<tr><td>'.$row->itemcode.'</td><td>'.$row->modelno.'</td><td>'.$row->catCode.'</td><td>'.number_format($row->brdsrp, 2).'</td><td>'.$row->qty.'</td></tr>';
        }
        else
            $data["drNo"] = 0;
            
        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->StockIn->getStockInByTransID($transID);
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
            $data["htmlTableList"] .= '<tr><td>'.$row->dr.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->qty.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';
        
        $data["htmlCategoryList"] = "";
        $result = $this->Category->getAllCategoryCodeAndDesc();

        foreach($result->result() as $row)
            $data["htmlCategoryList"] .= '<option value="'.$row->catCode.'">'.$row->catCode.' ['.$row->catDesc.']</option>';

        $this->load->view("pages/stockinnew", $data);
    }

    public function addStockInNew()
    {
        $this->load->model("StockIn");
        $this->load->model("BranchItemLedger");
        $this->load->model("Items");

        $this->form_validation->set_rules('txtModelNo', 'Model No', 'trim|required');
        $this->form_validation->set_rules('txtQty', 'Quantity', 'trim|required');

        $item = $this->Items->getItemByModelNo(trim($this->input->post("txtModelNo")));
        
        if(isset($item))
        {
            if($this->form_validation->run() == true)
            {
                $transID = $this->generateTransID($this->input->get("transDate", true));
                $recordID = $this->StockIn->getNextID($transID).$transID;
                
                $this->StockIn->recordID = $recordID;
                $this->StockIn->transID = $transID;
                $this->StockIn->dr = $this->input->get("drNo");
                $this->StockIn->catCode = $this->input->post("cmbCategory");
                $this->StockIn->modelno = $this->input->post("txtModelNo");
                $this->StockIn->qty = $this->input->post("txtQty");
                $this->StockIn->transDate = $this->input->get("transDate", true);
                $this->StockIn->validated = 0;

                if($this->StockIn->addStock() == true)
                {
                    if($this->BranchItemLedger->brCodeAndItemcodeExist($item->itemcode, $this->session->user["branch"]))
                    {
                        if($this->BranchItemLedger->updateInQty($item->itemcode, $this->session->user["branch"], $this->input->post("txtQty")) == false)
                            $this->StockIn->deleteStockIn($recordID);
                    }
                    else
                    {
                        $this->BranchItemLedger->itemcode = $item->itemcode;
                        $this->BranchItemLedger->brCode = $this->session->user["branch"];
                        $this->BranchItemLedger->beginningqty = 0;
                        $this->BranchItemLedger->inqty = $this->input->post("txtQty");
                        $this->BranchItemLedger->outqty = 0;
                        $this->BranchItemLedger->sales = 0;
                        $this->BranchItemLedger->adjustment = 0;
                        $this->BranchItemLedger->endingqty = $this->input->post("txtQty");
                        
                        if($this->BranchItemLedger->addNewData() == false)
                            $this->StockIn->deleteStockIn($recordID);
                    }
                }
            }
        }

        $this->stockinnew();
    }

    public function addStockInNewFromDelivery()
    {
        $this->load->model("StockIn");
        $this->load->model("BranchItemLedger");
        $this->load->model("BranchDeliveryView");

        $drNo = $this->input->get("drNo", true);
        $transID = $this->generateTransID($this->input->get("transDate", true));
        
        $result = $this->BranchDeliveryView->getDataByTransIDBrCode($drNo, $this->session->user["branch"]);
        
        foreach($result->result() as $row)
        {
            $recordID = $this->StockIn->getNextID($transID).$transID;
            
            $this->StockIn->recordID = $recordID;
            $this->StockIn->transID = $transID;
            $this->StockIn->dr = $drNo;
            $this->StockIn->catCode = $row->catCode;
            $this->StockIn->modelno = $row->modelno;
            $this->StockIn->qty = $row->qty;
            $this->StockIn->transDate = $this->input->get("transDate", true);
            $this->StockIn->validated = 0;

            if($this->StockIn->addStock() == true)
            {
                if($this->BranchItemLedger->brCodeAndItemcodeExist($row->itemcode, $this->session->user["branch"]))
                {
                    if($this->BranchItemLedger->updateInQty($row->itemcode, $this->session->user["branch"], $row->qty) == false)
                        $this->StockIn->deleteStockIn($recordID);
                }
                else
                {
                    $this->BranchItemLedger->itemcode = $row->itemcode;
                    $this->BranchItemLedger->brCode = $this->session->user["branch"];
                    $this->BranchItemLedger->beginningqty = 0;
                    $this->BranchItemLedger->inqty = $row->qty;
                    $this->BranchItemLedger->outqty = 0;
                    $this->BranchItemLedger->sales = 0;
                    $this->BranchItemLedger->adjustment = 0;
                    $this->BranchItemLedger->endingqty = $row->qty;
                    
                    if($this->BranchItemLedger->addNewData() == false)
                        $this->StockIn->deleteStockIn($recordID);
                }
            }
        }

        redirect('/stockinnew/transDate?transDate='.$this->input->get("transDate", true), 'refresh');
    }

    public function stockinmaintenancenew()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("StockIn");
        
        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);
        
        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->StockIn->getStockInByTransID($transID);        
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
        {
            if($row->validated == 1)
                $data["htmlTableList"] .= '<tr><td><div class="btn btn-primary" disabled>No Delete</div></td><td>'.$row->dr.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->qty.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';
            else
                $data["htmlTableList"] .= '<tr><td><button id="btnDeleteStockIn" name="btnDeleteStockIn" type="submit" class="btn btn-primary" value="'.$row->recordID.'">Delete</button></td><td>'.$row->dr.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->qty.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';
        }

        $this->load->view('pages/stockinmaintenancenew', $data);
    }

    public function stockinmaintenancenewdelete()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("StockIn");
        $this->load->model("BranchItemLedger");
        $this->load->model("Items");

        $recordID = $this->input->post("btnDeleteStockIn");
        $stockIn = $this->StockIn->getStockInByRecordID($recordID);
        $item = $this->Items->getItemByModelNo($stockIn->modelno);

        if(isset($item))
        {
            if($this->BranchItemLedger->brCodeAndItemcodeExist($item->itemcode, $this->session->user["branch"]))
            {
                if($this->BranchItemLedger->updateAdjustmentQty($item->itemcode, $this->session->user["branch"], $stockIn->qty, "Stock in deleted by ".$this->session->user["fullName"].". Qty:".$stockIn->qty, false) == true)
                    $this->StockIn->deleteStockIn($recordID);
            }
            else
            {
                $this->BranchItemLedger->itemcode = $item->itemcode;
                $this->BranchItemLedger->brCode = $this->session->user["branch"];
                $this->BranchItemLedger->beginningqty = 0;
                $this->BranchItemLedger->inqty = 0;
                $this->BranchItemLedger->outqty = 0;
                $this->BranchItemLedger->sales = 0;
                $this->BranchItemLedger->adjustment = 0-$stockIn->qty;
                $this->BranchItemLedger->endingqty = 0-$stockIn->qty;
                $this->BranchItemLedger->remarks = "Stock in deleted by ".$this->session->user["fullName"].". QTY:".$stockIn->qty." DATE:".date("m/d/Y h:i:s A");

                if($this->BranchItemLedger->addNewData() == true)
                    $this->StockIn->deleteStockIn($recordID);
            }
        }
        
        $this->stockinmaintenancenew();
    }



    public function stockoutnew()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Category");
        $this->load->model("StockOut");

        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);

        if($this->input->get("voNo", true) != null)
            $data["voNo"] = $this->input->get("voNo", true);
        else
            $data["voNo"] = 0;
            
        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->StockOut->getStockOutByTransID($transID);
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
            $data["htmlTableList"] .= '<tr><td>'.$row->vo.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->qty.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';
        
        $data["htmlCategoryList"] = "";
        $result = $this->Category->getAllCategoryCodeAndDesc();

        foreach($result->result() as $row)
            $data["htmlCategoryList"] .= '<option value="'.$row->catCode.'">'.$row->catCode.' ['.$row->catDesc.']</option>';
        
        $this->load->view('pages/stockoutnew', $data);
    }

    public function addStockOutNew()
    {
        $this->load->model("StockOut");
        $this->load->model("BranchItemLedger");
        $this->load->model("Items");

        //$this->form_validation->set_rules('txtVONo', 'DR No.', 'trim|required');
        $this->form_validation->set_rules('txtModelNo', 'Model No', 'trim|required');
        $this->form_validation->set_rules('txtQty', 'Quantity', 'trim|required');

        $item = $this->Items->getItemByModelNo(trim($this->input->post("txtModelNo")));

        if(isset($item))
        {
            if($this->form_validation->run() == true)
            {
                $transID = $this->generateTransID($this->input->get("transDate", true));
                $recordID = $this->StockOut->getNextID($transID).$transID;
                
                $this->StockOut->recordID = $recordID;
                $this->StockOut->transID = $transID;
                $this->StockOut->vo = $this->input->get("voNo");
                $this->StockOut->catCode = $this->input->post("cmbCategory");
                $this->StockOut->modelno = $this->input->post("txtModelNo");
                $this->StockOut->qty = $this->input->post("txtQty");
                $this->StockOut->transDate = $this->input->get("transDate", true);
                $this->StockOut->validated = 0;

                if($this->StockOut->addStock() == true)
                {
                    if($this->BranchItemLedger->brCodeAndItemcodeExist($item->itemcode, $this->session->user["branch"]))
                    {
                        if($this->BranchItemLedger->updateOutQty($item->itemcode, $this->session->user["branch"], $this->input->post("txtQty")) == false)
                            $this->StockOut->deleteStockOut($recordID);
                    }
                    else
                    {
                        $this->BranchItemLedger->itemcode = $item->itemcode;
                        $this->BranchItemLedger->brCode = $this->session->user["branch"];
                        $this->BranchItemLedger->beginningqty = 0;
                        $this->BranchItemLedger->inqty = 0;
                        $this->BranchItemLedger->outqty = $this->input->post("txtQty");
                        $this->BranchItemLedger->sales = 0;
                        $this->BranchItemLedger->adjustment = 0;
                        $this->BranchItemLedger->endingqty = 0-$this->input->post("txtQty");
                        
                        if($this->BranchItemLedger->addNewData() == false)
                            $this->StockOut->deleteStockOut($recordID);
                    }
                }
            }
        }

        $this->stockoutnew();
    }


    public function stockoutmaintenancenew()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("StockOut");
        
        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);
        
        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->StockOut->getStockOutByTransID($transID);        
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
        {
            if($row->validated == 1)
                $data["htmlTableList"] .= '<tr><td><div class="btn btn-primary">No Delete</div></td><td>'.$row->vo.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->qty.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';
            else
                $data["htmlTableList"] .= '<tr><td><button id="btnDeleteStockOut" name="btnDeleteStockOut" type="submit" class="btn btn-primary" value="'.$row->recordID.'">Delete</button></td><td>'.$row->vo.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->qty.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';
        }    

        $this->load->view('pages/stockoutmaintenancenew', $data);
    }


    public function stockoutmaintenancedeletenew()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("StockOut");
        $this->load->model("BranchItemLedger");
        $this->load->model("Items");

        $recordID = $this->input->post("btnDeleteStockOut");
        $stockOut = $this->StockOut->getStockOutByRecordID($recordID);
        $item = $this->Items->getItemByModelNo($stockOut->modelno);

        if(isset($item))
        {
            if($this->BranchItemLedger->brCodeAndItemcodeExist($item->itemcode, $this->session->user["branch"]))
            {
                if($this->BranchItemLedger->updateAdjustmentQty($item->itemcode, $this->session->user["branch"], $stockOut->qty, "Stock out deleted by ".$this->session->user["fullName"].". Qty:".$stockOut->qty, true) == true)
                    $this->StockOut->deleteStockOut($recordID);
            }
            else
            {
                $this->BranchItemLedger->itemcode = $item->itemcode;
                $this->BranchItemLedger->brCode = $this->session->user["branch"];
                $this->BranchItemLedger->beginningqty = 0;
                $this->BranchItemLedger->inqty = 0;
                $this->BranchItemLedger->outqty = 0;
                $this->BranchItemLedger->sales = 0;
                $this->BranchItemLedger->adjustment = $stockOut->qty;
                $this->BranchItemLedger->endingqty = $stockOut->qty;
                $this->BranchItemLedger->remarks = "Stock out deleted by ".$this->session->user["fullName"].". QTY:".$stockOut->qty." DATE:".date("m/d/Y h:i:s A");

                if($this->BranchItemLedger->addNewData() == true)
                    $this->StockOut->deleteStockOut($recordID);
            }
        }

        $this->stockoutmaintenancenew();
    }


    public function salesnew()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Sales");
        $this->load->model("Category");
        
        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);
        
        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->Sales->getSalesByTransID($transID);        
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
            $data["htmlTableList"] .= '<tr><td>'.$row->invoiceNum.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->custName.'</td><td>'.$row->qty.'</td><td>'.$row->price.'</td><td><div style="width:100px;">Cash: '.$row->cash.'<br>Dollar: '.$row->dollar.'<br>C Card: '.$row->creditCard.'<br>Check: '.$row->checque.'</div></td><td><div style="width:100px;">Bank Share: '.$row->bankshare.'<br>Tax Optn: '.$row->wTaxOption.'<br>W/Tax: '.$row->withholdingtax.'</div></td><td>Down: '.$row->layawayDP.'<br>Bal: '.$row->layawayBal.'<br>S Pay:'.$row->layawaySP.'<br>Full: '.$row->layawayFP.'</td><td>'.$row->misc.'</td><td>'.$row->transType.'</td><td>'.$row->remarks.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';

        $data["htmlCategoryList"] = "";
        $result = $this->Category->getAllCategoryCodeAndDesc();

        foreach($result->result() as $row)
            $data["htmlCategoryList"] .= '<option value="'.$row->catCode.'">'.$row->catCode.' ['.$row->catDesc.']</option>';

        $this->load->view('pages/salesnew', $data);
    }

    public function salesNewWithCustomer()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Category");

        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);

        $data["htmlCategoryList"] = "";
            $result = $this->Category->getAllCategoryCodeAndDesc();

        foreach($result->result() as $row)
            $data["htmlCategoryList"] .= '<option value="'.$row->catCode.'">'.$row->catCode.' ['.$row->catDesc.']</option>';

        $this->load->view('pages/salesnewwithcustomer', $data);
    }

    public function addSalesNew()
    {
        $this->load->model("Sales");
        $this->load->model("BranchItemLedger");
        $this->load->model("Items");
        
        $this->form_validation->set_rules('txtInvoiceNo', 'Invoice', 'trim|required');
        $this->form_validation->set_rules('txtModelNo', 'Model No', 'trim|required');
        $this->form_validation->set_rules('txtCustomer', 'Customer Name', 'trim|required');

        if($this->form_validation->run() == true)
        {
            $item = $this->Items->getItemByModelNo(trim($this->input->post("txtModelNo")));
            $transID = $this->generateTransID($this->input->get("transDate", true));
            $recordID = $this->Sales->getNextID($transID).$transID;
            $tax = 0;

            $taxOptn = intval($this->input->post("cmbWTaxOptn"));

            switch($taxOptn)
            {
                case 0:
                    $tax = floatval($this->input->post("txtCard")) * 0.005;
                    break;
                case 1:
                    $tax = (floatval($this->input->post("txtCard")) / 12) * 0.005;
                    break;
                case 2:
                    $tax = 0;
                    break;
            }
            
            $this->Sales->recordID = $recordID;
            $this->Sales->transID = $transID;
            $this->Sales->brCode = $this->session->user["branch"];
            $this->Sales->invoiceNum = $this->input->post("txtInvoiceNo");
            $this->Sales->catCode = $this->input->post("cmbCategory");
            $this->Sales->modelno = $this->input->post("txtModelNo");
            $this->Sales->custName = $this->input->post("txtCustomer");
            $this->Sales->qty = $this->input->post("txtQty");
            $this->Sales->price = $this->input->post("txtPrice");
            $this->Sales->cash = $this->input->post("txtCash");
            $this->Sales->dollar = $this->input->post("txtDollar");
            $this->Sales->creditCard = $this->input->post("txtCard");
            $this->Sales->bankshare = $this->input->post("txtBankShare");
            $this->Sales->wTaxOption = $this->input->post("cmbWTaxOptn");
            $this->Sales->withholdingtax = $tax;
            $this->Sales->layawayDP = ($this->input->post("cmbTransType") == "layawayDP") ? $this->input->post("txtTotalAmount") : 0.00;
            $this->Sales->layawayBal = ($this->input->post("cmbTransType") == "layawayDP") ? $this->input->post("txtBalance") : 0.00;
            $this->Sales->layawaySP = ($this->input->post("cmbTransType") == "layawaySP") ? $this->input->post("txtTotalAmount") : 0.00;
            $this->Sales->layawayFP = ($this->input->post("cmbTransType") == "layawayFP") ? $this->input->post("txtTotalAmount") : 0.00;
            $this->Sales->checque = $this->input->post("txtCheck");
            $this->Sales->misc = ($this->input->post("cmbTransType") == "others") ? $this->input->post("txtTotalAmount") : 0.00;
            $this->Sales->transType = $this->input->post("cmbTransType");
            $this->Sales->remarks = $this->input->post("txtRemarks");
            $this->Sales->transDate = $this->input->get("transDate", true);
            $this->Sales->validated = 0;

            if($this->Sales->addSales() == true && isset($item))
            {
                if($this->BranchItemLedger->brCodeAndItemcodeExist($item->itemcode, $this->session->user["branch"]))
                {
                    if($this->BranchItemLedger->updateSalesQty($item->itemcode, $this->session->user["branch"], $this->input->post("txtQty")) == false)
                        $this->Sales->deleteSales($recordID);
                }
                else
                {
                    $this->BranchItemLedger->itemcode = $item->itemcode;
                    $this->BranchItemLedger->brCode = $this->session->user["branch"];
                    $this->BranchItemLedger->beginningqty = 0;
                    $this->BranchItemLedger->inqty = 0;
                    $this->BranchItemLedger->outqty = 0;
                    $this->BranchItemLedger->sales = $this->input->post("txtQty");
                    $this->BranchItemLedger->adjustment = 0;
                    $this->BranchItemLedger->endingqty = 0-$this->input->post("txtQty");
                    
                    if($this->BranchItemLedger->addNewData() == false)
                        $this->Sales->deleteSales($recordID);
                }
            }
        }

        $this->salesnew();
    }


    public function salesmaintenancenew()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Sales");
        $this->load->model("Category");
        
        $data["selectedDate"] = date('m/d/Y');
        if($this->input->get("transDate", true) != null)
            $data["selectedDate"] = $this->input->get("transDate", true);
        
        $transID = $this->generateTransID($data["selectedDate"]);
        $result = $this->Sales->getSalesByTransID($transID);        
        $data["htmlTableList"] = "";

        foreach($result->result() as $row)
        {
            $valid = "";
            $htmldata = "";

            if($row->validated != 0)
                $valid = "disabled";
            else
            {
                $htmldata = 'data-recordid="'.$row->recordID.'" ';
                $htmldata .= 'data-invoicenum="'.$row->invoiceNum.'" ';
                $htmldata .= 'data-transtype="'.$row->transType.'" ';
                $htmldata .= 'data-custname="'.$row->custName.'" ';
                $htmldata .= 'data-catcode="'.$row->catCode.'" ';
                $htmldata .= 'data-modelno="'.$row->modelno.'" ';
                $htmldata .= 'data-qty="'.$row->qty.'" ';
                $htmldata .= 'data-price="'.$row->price.'" ';
                $htmldata .= 'data-cash="'.$row->cash.'" ';
                $htmldata .= 'data-dollar="'.$row->dollar.'" ';
                $htmldata .= 'data-checque="'.$row->checque.'" ';
                $htmldata .= 'data-creditcard="'.$row->creditCard.'" ';
                $htmldata .= 'data-bankshare="'.$row->bankshare.'" ';
                $htmldata .= 'data-wtaxoption="'.$row->wTaxOption.'" ';
                $htmldata .= 'data-remarks="'.$row->remarks.'" ';
            }
            
            $data["htmlTableList"] .= '<tr><td><button id="btnEditSales" name="btnEditSales" type="button" '.$htmldata.' class="btn btn-xs btn-primary" data-dismiss="modal" data-toggle="modal" data-target="#mdlEditSales" '.$valid.'><span class="glyphicon glyphicon-pencil"></span></button> <button id="btnDeleteSales" name="btnDeleteSales" type="submit" class="btn btn-xs btn-danger" value="'.$row->recordID.'" '.$valid.'><span class="glyphicon glyphicon-remove"></span></button></td><td>'.$row->invoiceNum.'</td><td>'.$row->catCode.'</td><td>'.$row->modelno.'</td><td>'.$row->custName.'</td><td>'.$row->qty.'</td><td>'.$row->price.'</td><td><div style="width:100px;">Cash: '.$row->cash.'<br>Dollar: '.$row->dollar.'<br>C Card: '.$row->creditCard.'<br>Check: '.$row->checque.'</div></td><td><div style="width:100px;">Bank Share: '.$row->bankshare.'<br>Tax Optn: '.$row->wTaxOption.'<br>W/Tax: '.$row->withholdingtax.'</div></td><td>Down: '.$row->layawayDP.'<br>Bal: '.$row->layawayBal.'<br>S Pay:'.$row->layawaySP.'<br>Full: '.$row->layawayFP.'</td><td>'.$row->misc.'</td><td>'.$row->transType.'</td><td>'.$row->remarks.'</td><td>'.$row->transDate.'</td><td>'.$row->validated.'</td></tr>';
        }

        $data["htmlCategoryList"] = "";
        $result = $this->Category->getAllCategoryCodeAndDesc();

        foreach($result->result() as $row)
            $data["htmlCategoryList"] .= '<option value="'.$row->catCode.'">'.$row->catCode.' ['.$row->catDesc.']</option>';

        $this->load->view('pages/salesmaintenancenew', $data);
    }

    public function salesmaintenanceeditnew()
    {
        $this->load->model("Sales");
        
        $this->form_validation->set_rules('txtInvoiceNo', 'Invoice', 'trim|required');
        $this->form_validation->set_rules('txtModelNo', 'Model No', 'trim|required');
        $this->form_validation->set_rules('txtCustomer', 'Customer Name', 'trim|required');

        if($this->form_validation->run() == true)
        {
            //$transID = $this->generateTransID($this->input->get("transDate", true));
            $recordID = $this->input->post("hdnRecordID");
            $tax = 0;

            $taxOptn = intval($this->input->post("cmbWTaxOptn"));

            switch($taxOptn)
            {
                case 0:
                    $tax = floatval($this->input->post("txtCard")) * 0.005;
                    break;
                case 1:
                    $tax = (floatval($this->input->post("txtCard")) / 12) * 0.005;
                    break;
                case 2:
                    $tax = 0;
                    break;
            }
            
            //$this->Sales->recordID = $recordID;
            //$this->Sales->transID = $transID;
            //$this->Sales->brCode = $this->session->user["branch"];
            $updateColumn = array(
                "invoiceNum" => $this->input->post("txtInvoiceNo"),
                "catCode" => $this->input->post("cmbCategory"),
                "modelno" => $this->input->post("txtModelNo"),
                "custName" => $this->input->post("txtCustomer"),
                "qty" => $this->input->post("txtQty"),
                "price" => $this->input->post("txtPrice"),
                "cash" => $this->input->post("txtCash"),
                "dollar" => $this->input->post("txtDollar"),
                "creditCard" => $this->input->post("txtCard"),
                "bankshare" => $this->input->post("txtBankShare"),
                "wTaxOption" => $this->input->post("cmbWTaxOptn"),
                "withholdingtax" => $tax,
                "layawayDP" => ($this->input->post("cmbTransType") == "layawayDP") ? $this->input->post("txtTotalAmount") : 0.00,
                "layawayBal" => ($this->input->post("cmbTransType") == "layawayDP") ? $this->input->post("txtBalance") : 0.00,
                "layawaySP" => ($this->input->post("cmbTransType") == "layawaySP") ? $this->input->post("txtTotalAmount") : 0.00,
                "layawayFP" => ($this->input->post("cmbTransType") == "layawayFP") ? $this->input->post("txtTotalAmount") : 0.00,
                "checque" => $this->input->post("txtCheck"),
                "misc" => ($this->input->post("cmbTransType") == "others") ? $this->input->post("txtTotalAmount") : 0.00,
                "transType" => $this->input->post("cmbTransType"),
                "remarks" => $this->input->post("txtRemarks"),
                "transDate" => $this->input->get("transDate", true),
                "validated" => 0
            );
            

            $this->Sales->editSales($recordID, $updateColumn);
        }
        $this->salesmaintenancenew();
    }

    public function salesmaintenancedeletenew()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("Sales");
        $this->load->model("BranchItemLedger");
        $this->load->model("Items");

        $recordID = $this->input->post("btnDeleteSales");
        $sales = $this->Sales->getSalesByRecordID($recordID);
        $item = $this->Items->getItemByModelNo($sales->modelno);

        if(isset($item) && $sales->qty > 0)
        {
            if($this->BranchItemLedger->brCodeAndItemcodeExist($item->itemcode, $this->session->user["branch"]))
                $this->BranchItemLedger->updateAdjustmentQty($item->itemcode, $this->session->user["branch"], $sales->qty, "Sales deleted by ".$this->session->user["fullName"].". Qty:".$sales->qty, true);
            else
            {
                $this->BranchItemLedger->itemcode = $item->itemcode;
                $this->BranchItemLedger->brCode = $this->session->user["branch"];
                $this->BranchItemLedger->beginningqty = 0;
                $this->BranchItemLedger->inqty = 0;
                $this->BranchItemLedger->outqty = 0;
                $this->BranchItemLedger->sales = 0;
                $this->BranchItemLedger->adjustment = $sales->qty;
                $this->BranchItemLedger->endingqty = $sales->qty;
                $this->BranchItemLedger->remarks = "Sales deleted by ".$this->session->user["fullName"].". QTY:".$sales->qty." DATE:".date("m/d/Y h:i:s A");

                $this->BranchItemLedger->addNewData();
            }
        }        

        $this->Sales->deleteSales($recordID);
        
        $this->salesmaintenancenew();
    }

    public function setmaintenancenewsetqtyto0()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $success = false;
        $data = -1;
        $this->load->model("Sales");
        $this->load->model("BranchItemLedger");
        $this->load->model("Items");

        $recordID = $this->input->post("recordID");
        $sales = $this->Sales->getSalesByRecordID($recordID);
        $item = $this->Items->getItemByModelNo($sales->modelno);

        if(isset($item) && $sales->qty > 0)
        {
            if($this->BranchItemLedger->brCodeAndItemcodeExist($item->itemcode, $this->session->user["branch"]))
            {
                if($this->BranchItemLedger->updateAdjustmentQty($item->itemcode, $this->session->user["branch"], $sales->qty, "Sales set by ".$this->session->user["fullName"]." but retained the record. Qty:".$sales->qty, true))
                {
                    if($this->Sales->editSalesSetQtyToZero($recordID))
                    {
                        $sales = $this->Sales->getSalesByRecordID($recordID);
                        $success = true;
                        $data = $sales->qty;
                    }
                }
            }
            else
            {
                $this->BranchItemLedger->itemcode = $item->itemcode;
                $this->BranchItemLedger->brCode = $this->session->user["branch"];
                $this->BranchItemLedger->beginningqty = 0;
                $this->BranchItemLedger->inqty = 0;
                $this->BranchItemLedger->outqty = 0;
                $this->BranchItemLedger->sales = 0;
                $this->BranchItemLedger->adjustment = $sales->qty;
                $this->BranchItemLedger->endingqty = $sales->qty;
                $this->BranchItemLedger->remarks = "Sales set by ".$this->session->user["fullName"]." but retained the record. QTY:".$sales->qty." DATE:".date("m/d/Y h:i:s A");

                if($this->BranchItemLedger->addNewData())
                {
                    if($this->Sales->editSalesSetQtyToZero($recordID))
                    {
                        $sales = $this->Sales->getSalesByRecordID($recordID);
                        $success = true;
                        $data = $sales->qty;
                    }
                }
            }
        }  

        echo json_encode(array("success"=>$success, "data"=>$data)); 
    }

    public function itemmovementhistory()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');
        
        $data["htmlTableList"] = "";

        if($this->input->get("mts") != "")
        {
            $this->load->model("BranchItemLedger");

            $data["mts"] = $this->input->get("mts");

            $result = $this->BranchItemLedger->getItemTransactionHistory($this->input->get("mts"), $this->session->user["branch"]);

            foreach($result->result() as $row)
                $data["htmlTableList"] .= '<tr><td>'.$row->transID.'</td><td>'.$row->modelno.'</td><td>'.$row->InQty.'</td><td>'.$row->OutQty.'</td><td>'.$row->SalesQty.'</td><td>'.$row->transType.'</td><td>'.$row->transDate.'</td></tr>';
        }

        $this->load->view('pages/itemmovementhistory', $data);
    }

    // End of Methods and processes under development phase

    public function iteminquirycountsummary()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $data["htmlTableList"] = "";

        $data["selectedDateFrom"] = date('m/d/Y');
        $data["selectedDateTo"] = date('m/d/Y');

        if($this->input->get("transDateFrom", true) != null)
            $data["selectedDateFrom"] = $this->input->get("transDateFrom", true);

        if($this->input->get("transDateTo", true) != null)
            $data["selectedDateTo"] = $this->input->get("transDateTo", true);

        if($this->input->get("transDateFrom", true) != null && $this->input->get("transDateTo", true) != null)
        {
            $this->load->model("ItemInquiryLog");

            $result = $this->ItemInquiryLog->getSummaryPerCategory($this->session->user["branch"], $this->input->get("transDateFrom", true), $this->input->get("transDateTo", true));
            
            foreach($result->result() as $row)
                $data["htmlTableList"] .= '<tr><td>'.$row->catCode.'</td><td>'.$row->SearchCount.'</td></tr>';
        }
        
        $this->load->view('pages/iteminquirycountsummary', $data);
    }

    public function iteminquirycountsummaryreport()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $this->load->model("ItemInquiryLog");
        
        $data["htmlTableList"] = "";
        $data["currDate"] = date('m/d/Y h:i:s a');

        $result = $this->ItemInquiryLog->getSummaryPerCategory($this->session->user["branch"], $this->input->get("transDateFrom", true), $this->input->get("transDateTo", true));
            
        foreach($result->result() as $row)
        {
            $data["htmlTableList"] .= '<tr><td colspan="4"><b>'.$row->catCode.'</b></td></tr>';

            $detailedResult = $this->ItemInquiryLog->getSummaryPerItemcodeCategory($this->session->user["branch"], $row->catCode, $this->input->get("transDateFrom", true), $this->input->get("transDateTo", true));

            foreach($detailedResult->result() as $rowForDetails)
                $data["htmlTableList"] .= '<tr><td>&nbsp;</td><td>'.$rowForDetails->itemcode.'</td><td>'.$rowForDetails->modelno.'</td><td>'.$rowForDetails->SearchCount.'</td></tr>';

            $data["htmlTableList"] .= '<tr><td colspan="3" style="text-align: right">Total:</td><td><b>'.$row->SearchCount.'</b></td></tr>';
        }

        $this->load->view('pages/iteminquirycountsummaryreport', $data);
    }


    
    // ------- ADMIN -> Item Ledger Editor ----------
    
    public function adminitemledgereditor()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        $data["itemledger"] = null;

        if($this->input->get("mts") != "")
        {
            $this->load->model("BranchItemLedger");
            $this->load->model("Items");

            $item = $this->Items->getItemByModelNo($this->input->get("mts"));
            $itemLedger = $this->BranchItemLedger->getDataByBrCodeItemcode($this->session->user["branch"], $item->itemcode);

            $data["mts"] = $this->input->get("mts");
            $data["modelno"] = $item->modelno;
            $data["itemledger"] = $itemLedger;
        }

        $this->load->view('pages/adminitemledgereditor', $data);
    }

    public function editAdminitemLedgerEditor()
    {
        if(!$this->isLogged())
            redirect('login', 'refresh');

        if($isset($this->input->post("btnSave")) && $this->input->post("btnSave") == "Save Changes")
        {
            $this->load->model("BranchItemLedger");

            $this->BranchItemLedger->itemcode = $this->input->post("txtItemcode");
            $this->BranchItemLedger->brCode = $this->session->user["branch"];
            $this->BranchItemLedger->beginningqty = $this->input->post("txtBQty");
            $this->BranchItemLedger->inqty = $this->input->post("txtInQty");
            $this->BranchItemLedger->outqty = $this->input->post("txtOutQty");
            $this->BranchItemLedger->sales = $this->input->post("txtSales");
            $this->BranchItemLedger->adjustment = $this->input->post("txtAdjQty");
            $this->BranchItemLedger->endingqty = $this->input->post("txtEndingQty");
            $this->BranchItemLedger->remarks = $this->input->post("txtRemarks");

            $this->BranchItemLedger->updateAllQtyAndRemarks();
        }
        
        redirect('adminitemledgereditor?mts='.$this->input->post("txtModelno"), 'refresh');
    }
}