<?php

//the global file operation
include("../public/impOpreation.php");

// get the config file
include_once("../public/config.php");

//here the db files that include in the file
include("../public/include_dao.php");

//Billproperty
require_once('../models/dao/BillpropertyDAO.class.php');
require_once('../models/dto/Billproperty.class.php');
require_once('../models/mysql/BillpropertyMySqlDAO.class.php');
require_once('../models/mysql/ext/BillpropertyMySqlExtDAO.class.php');
//Billsetting
require_once('../models/dao/BillsettingsDAO.class.php');
require_once('../models/dto/Billsetting.class.php');
require_once('../models/mysql/BillsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsettingsMySqlExtDAO.class.php');
//Billname
require_once('../models/dao/BillnameDAO.class.php');
require_once('../models/dto/Billname.class.php');
require_once('../models/mysql/BillnameMySqlDAO.class.php');
require_once('../models/mysql/ext/BillnameMySqlExtDAO.class.php');
//Relusergrouppropertie
require_once('../models/dao/RelusergrouppropertiesDAO.class.php');
require_once('../models/dto/Relusergrouppropertie.class.php');
require_once('../models/mysql/RelusergrouppropertiesMySqlDAO.class.php');
require_once('../models/mysql/ext/RelusergrouppropertiesMySqlExtDAO.class.php');
//Bankaccount
require_once('../models/dao/BankaccountDAO.class.php');
require_once('../models/dto/Bankaccount.class.php');
require_once('../models/mysql/BankaccountMySqlDAO.class.php');
require_once('../models/mysql/ext/BankaccountMySqlExtDAO.class.php');

require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');

//get the do the action
$do = $_GET['do'];

$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");

/* ======================

  Controller Name :- clientTypeCTRL

  OPERTATION in Controller

  1-
  2-
  3-
  4-

  ======================== */
$userID = $_SESSION['userid'];

//here the global templates
$smarty->display("header.html");

//here goes the instances and general variables
//Billproperty
$Billproperty = new Billproperty();
$BillpropertyDAO = new BillpropertyMySqlDAO();
$BillpropertyEX = new BillpropertyMySqlExtDAO();

//Billname
$Billname = new Billname();
$BillnameDAO = new BillnameMySqlDAO();
$BillnameEX = new BillnameMySqlExtDAO();

//Billsetting
$Billsetting = new Billsetting();
$BillsettingDAO = new BillsettingsMySqlDAO();
$BillsettingEX = new BillsettingsMySqlExtDAO();

//Relusergrouppropertie
$myRelusergrouppropertie = new Relusergrouppropertie();
$myRelusergrouppropertieRecord = new RelusergrouppropertiesMySqlDAO();
$myRelusergrouppropertieExt = new RelusergrouppropertiesMySqlExtDAO();
//Bankaccount
$bankAccount = new Bankaccount();
$bankAccountDAO = new BankaccountMySqlDAO();
$bankAccountEX = new BankaccountMySqlExtDAO();

$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();
$programSettingDAO = new ProgramsettingsMySqlDAO();

//check and use the condetion that suite this action
if (empty($do)) {

    $allBillproperty = getallBillproperty();
    $bankAccounts = $bankAccountEX->queryWithOrder2ForVisaPayment();
    $smarty->assign('bankAccounts', $bankAccounts);

    $smarty->assign('allBillproperty', $allBillproperty);
    $smarty->assign('countallBillproperty', count($allBillproperty));
    $smarty->display("billsettingsview/add.html");
} elseif ($do == "add") {
    //    add();
    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "ruturndelete") {
    try {
        $id = $_GET["id"];
        $note = ruturndelete($id);
        if ($note !== "sucess") {
            $url = "billsettingsController.php?do=show";
            $smarty->assign('urldirect', $url);
            $note = $note;
            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($_GET['do'] == "show") {

    show();

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);
    $smarty->display("billsettingsview/show.html");
} elseif ($do == "edit") {
    $programSettingData = $programSettingDAO->load(1);
    $smarty->assign("programSettingData", $programSettingData);

    $billsettingdata = edit();
    $smarty->assign("data", $billsettingdata[0]);

    $smarty->assign("Billsettingdata", $billsettingdata[1]);

    $allBillproperty = getallBillproperty();
    $smarty->assign('allBillproperty', $allBillproperty);
    //var_dump($allBillproperty);

    /* print_r("<pre>");
      print_r($allBillproperty);
      print_r("<pre>"); */
    $smarty->assign('countallBillproperty', count($allBillproperty));

    $bankAccounts = $bankAccountEX->queryWithOrder2ForVisaPayment();
    $smarty->assign('bankAccounts', $bankAccounts);

    $smarty->display("billsettingsview/edit.html");
} elseif ($_GET['do'] == "update") {
    try {
        update();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //header("location:?do=error");
        echo $e;
    }
} elseif ($_GET['do'] == "copy") {
    try {
        $billnameid = (int) $_GET['id'];
        if ($billnameid > 0) {
            copyBillSetting($billnameid);
        } else {
            echo "wrong choice";
        }
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
        //	echo $e;
    }
} elseif ($_GET['do'] == "execute") {
    try {
        execute();
        show();

        $smarty->display("billsettingsview/show.html");
    } catch (Exception $e) {
        $smarty->display("error.html");
    }
} elseif ($_GET['do'] == "delete") {
    try {
        $id = $_GET["id"];
        $note = delete($id);

        if ($note !== "sucess") {
            $url = "billsettingsController.php?do=show";
            $smarty->assign('urldirect', $url);
            $note = $note;

            $smarty->assign('msgnote', $note);
            $smarty->display("notes.html");
        } else {

            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($_GET['do'] == "sucess") {
    $smarty->display("succes.html");
} elseif ($_GET['do'] == "error") {
    $smarty->display("error.html");
}



$smarty->assign("customValidation", 1);
$smarty->display("footer.html");

//******************    Functions    ************************//


function add() {
    global $BillpropertyEX;
    global $BillpropertyDAO;
    global $Billproperty;
    global $BillnameEX;
    global $BillnameDAO;
    global $Billname;
    global $BillsettingDAO;
    global $Billsetting;
    global $BillsettingEX;

    $countallBillproperty = $_POST['countallBillproperty'];
    $name = $_POST['name'];
    $billType = $_POST['billType'];
    $billType2 = $_POST['billType2'];
    $ordertype = $_POST['ordertype'];
    $saveeffect = $_POST['saveeffect'];
    $storeeffect = $_POST['storeeffect'];


    $productAndQuantityOnly = $_POST['productAndQuantityOnly'];


    $posFlag = (int) $_POST['posFlag'];
    $posCode = (int) $_POST['posCode'];
    $posType = (int) $_POST['posType'];
    $posWeightPrice = (int) $_POST['posWeightPrice'];
    $checkDigit = (int) $_POST['checkDigit'];
    $goodsReceiptApproval = $_POST['goodsReceiptApproval'];
    $parcodeType = $_POST['parcodeType'];
    $defVisaAccount = (int) $_POST['defVisaAccount'];
    $defVisaAccountSelect = (int) $_POST['defVisaAccountSelect'];
    $isBankAccountTransfer = (int) $_POST['isBankAccountTransfer'];

    $taxOfDiscountVal = (float) $_POST['taxOfDiscountVal'];
    $taxOfDiscountPrint = (int) $_POST['taxOfDiscountPrint'];
    $extraDiscountPlace = (int) $_POST['extraDiscountPlace'];
    $extraDiscountFixed = (int) $_POST['extraDiscountFixed'];
    $extraDiscountPer = (float) $_POST['extraDiscountPer'];
    $taxname = $_POST['taxname'];


    $Billname->ordertype = $ordertype;
    $Billname->saveeffect = $saveeffect;
    $Billname->storeeffect = $storeeffect;
    $Billname->billnamedate = date("Y-m-d");
    $Billname->conditions = 0;
    $Billname->name = $name;
    $Billname->userid = $_SESSION['userid'];
    $Billname->billtype = $billType;
    $Billname->billtype2 = $billType2;
    $Billname->productAndQuantityOnly = $productAndQuantityOnly;
    $Billname->posFlag = $posFlag;
    $Billname->posCode = $posCode;
    $Billname->posType = $posType;
    $Billname->posWeightPrice = $posWeightPrice;
    $Billname->checkDigit = $checkDigit;
    $Billname->goodsReceiptApproval = $goodsReceiptApproval;
    $Billname->parcodeType = $parcodeType;
    $Billname->defVisaAccount = $defVisaAccount;
    $Billname->defVisaAccountSelect = $defVisaAccountSelect;
    $Billname->isBankAccountTransfer = $isBankAccountTransfer;
    $Billname->taxOfDiscountVal = $taxOfDiscountVal;
    $Billname->taxOfDiscountPrint = $taxOfDiscountPrint;
    $Billname->extraDiscountPlace = $extraDiscountPlace;
    $Billname->extraDiscountFixed = $extraDiscountFixed;
    $Billname->extraDiscountPer = $extraDiscountPer;
    $Billname->taxname = $taxname;


    $billnameid = $BillnameDAO->insert($Billname);

    if ($billnameid) {
        for ($i = 1; $i <= $countallBillproperty; $i++) {
            $settingsvalue = $_POST['settingsvalue' . $i . ''];
            $billpropertyid = $_POST['billpropertyid' . $i . ''];
            //if ($billpropertyid == 82) {
            //var_dump($settingsvalue);
            if (isset($_POST['settingsvalue' . $i . ''])) {
                $Billsetting->billnameid = $billnameid;
                $Billsetting->billpropertyid = $billpropertyid;
                $Billsetting->billsettingsvalue = $settingsvalue;

                $BillsettingDAO->insert($Billsetting);
            }
            //die();
            //            }
        }
    }
}

//show tabel data
function show() {
    global $BillnameEX;
    global $BillnameDAO;
    global $Billname;

    global $smarty;

    $qname = $BillnameEX->queryAllForShow();

    $smarty->assign('name', $qname);
}

// edit row
function edit() {
    global $BillnameEX;
    global $BillnameDAO;
    global $Billname;
    global $BillsettingDAO;
    global $Billsetting;
    global $BillsettingEX;

    $billnameid = $_GET['id'];
    $data = $BillnameDAO->load($billnameid);
    //$Billsettingdata = $BillsettingEX->queryAllbillsettingsNotDeleted($billnameid);
    //fatma
    //as new properities dont appear in old bills as it does not exist in bill setting
    $Billsettingdata = $BillsettingEX->queryAllbillsettingsNotDeleted_f($billnameid);

    return array($data, $Billsettingdata);
}

//update row
function update() {
    global $BillpropertyEX;
    global $BillpropertyDAO;
    global $Billproperty;


    global $BillnameEX;
    global $BillnameDAO;
    global $Billname;

    global $BillsettingDAO;
    global $Billsetting;
    global $BillsettingEX;


    $countallBillproperty = $_POST['countallBillproperty'];
    $name = $_POST['name'];
    $billnameid = $_POST['billnameid'];
    $billType = $_POST['billType'];
    $billType2 = $_POST['billType2'];


    $ordertype = $_POST['ordertype'];
    $saveeffect = $_POST['saveeffect'];
    $storeeffect = $_POST['storeeffect'];
    $productAndQuantityOnly = $_POST['productAndQuantityOnly'];

    $posFlag = (int) $_POST['posFlag'];
    $posCode = (int) $_POST['posCode'];
    $posType = (int) $_POST['posType'];
    $posWeightPrice = (int) $_POST['posWeightPrice'];
    $checkDigit = (int) $_POST['checkDigit'];
    $goodsReceiptApproval = $_POST['goodsReceiptApproval'];
    $parcodeType = $_POST['parcodeType'];
    $defVisaAccount = (int) $_POST['defVisaAccount'];
    $defVisaAccountSelect = (int) $_POST['defVisaAccountSelect'];
    $isBankAccountTransfer = (int) $_POST['isBankAccountTransfer'];

    $taxOfDiscountVal = (float) $_POST['taxOfDiscountVal'];
    $taxOfDiscountPrint = (int) $_POST['taxOfDiscountPrint'];
    $extraDiscountPlace = (int) $_POST['extraDiscountPlace'];
    $extraDiscountFixed = (int) $_POST['extraDiscountFixed'];
    $extraDiscountPer = (float) $_POST['extraDiscountPer'];
    $taxname = $_POST['taxname'];

    $Billname->ordertype = $ordertype;
    $Billname->saveeffect = $saveeffect;
    $Billname->storeeffect = $storeeffect;

    $Billname->billnamedate = date("Y-m-d");
    $Billname->conditions = 0;
    $Billname->name = $name;
    $Billname->billnameid = $billnameid;
    $Billname->userid = $_SESSION['userid'];
    $Billname->billtype = $billType;
    $Billname->billtype2 = $billType2;
    $Billname->productAndQuantityOnly = $productAndQuantityOnly;
    $Billname->posFlag = $posFlag;
    $Billname->posCode = $posCode;
    $Billname->posType = $posType;
    $Billname->posWeightPrice = $posWeightPrice;
    $Billname->checkDigit = $checkDigit;
    $Billname->goodsReceiptApproval = $goodsReceiptApproval;
    $Billname->parcodeType = $parcodeType;
    $Billname->defVisaAccount = $defVisaAccount;
    $Billname->defVisaAccountSelect = $defVisaAccountSelect;
    $Billname->isBankAccountTransfer = $isBankAccountTransfer;
    $Billname->taxOfDiscountVal = $taxOfDiscountVal;
    $Billname->taxOfDiscountPrint = $taxOfDiscountPrint;
    $Billname->extraDiscountPlace = $extraDiscountPlace;
    $Billname->extraDiscountFixed = $extraDiscountFixed;
    $Billname->extraDiscountPer = $extraDiscountPer;
    $Billname->taxname = $taxname;


    $BillnameDAO->update($Billname);

    if ($billnameid > 0) {
        for ($i = 1; $i <= $countallBillproperty; $i++) {
            $settingsvalue = $_POST['settingsvalue' . $i . ''];
            $billpropertyid = $_POST['billpropertyid' . $i . ''];
            $billsettingsid = $_POST['billsettingsid' . $i . ''];

            if (isset($_POST['settingsvalue' . $i . ''])) {

                $Billsetting->billnameid = $billnameid;
                $Billsetting->billsettingsid = $billsettingsid;
                $Billsetting->billpropertyid = $billpropertyid;

                if (isset($billsettingsid) && !empty($billsettingsid)) {
                    // print_r("<br>if".$billsettingsid);
                    $Billsetting->billsettingsvalue = $settingsvalue;
                    $BillsettingDAO->update($Billsetting);
                } else {
                    //print_r("<br>else".$billsettingsid);
                    $BillsettingDAO->insert($Billsetting);
                }
            }
        }
    }
}

// temp delte row

function delete($id) {
    global $BillpropertyEX;
    global $BillpropertyDAO;
    global $Billproperty;


    global $BillsettingDAO;
    global $Billsetting;
    global $BillsettingEX;


    global $BillnameEX;
    global $BillnameDAO;
    global $Billname;

    global $smarty;


    $billnameid = $id; //$_GET['id'];
    //1- check if there are any asset cat  associated with asset
    //$alldata=$BillsettingDAO->queryByBillpropertyid($billpropertyid);
    //if(count($alldata) > 0 )
    //{
    //$note ="لا يمكن حذف هذا النوع لانه مرتبط بفاتوره اخرى";
    //}
    //else
    {
        $Billname->billnameid = $billnameid;


        $Billname->conditions = 1;
        $BillnameEX->updatedel($Billname);

        $note = "sucess";
    }

    return $note;
}

// cancel deleting row
function ruturndelete($id) {
    global $BillpropertyEX;
    global $BillpropertyDAO;
    global $Billproperty;


    global $BillsettingDAO;
    global $Billsetting;
    global $BillsettingEX;
    global $smarty;

    global $BillnameEX;
    global $BillnameDAO;
    global $Billname;



    $billnameid = $id; //$_GET['id'];



    $Billname->conditions = 0;
    $Billname->billnameid = $billnameid;
    if ($BillnameEX->updatedel($Billname)) {
        $note = "sucess";
    } else {

        $note = "لم تتم العمليه بنجاح لان هذا العنصر لم يتم حذف من قبل ";
    }
    return $note;
}

function execute() {
    global $BillpropertyEX;
    global $BillpropertyDAO;
    global $Billproperty;


    global $BillsettingDAO;
    global $Billsetting;
    global $BillsettingEX;

    global $smarty;
    global $outputString;

    $operationType = $_POST['operation'];
    $smarty->assign("operationType", $operationType);

    $choosedItemArr = $_POST['choosedItem'];
    //print_r($choosedItemArr);
    if (count($choosedItemArr) > 0) {
        $i = 1;
        foreach ($choosedItemArr as $billpropertyid) {
            $Billpropertytdata = $BillpropertyDAO->load($billpropertyid);
            //print_r($Billpropertytdata);
            $billpropertyname = $Billpropertytdata->billpropertyname;
            if ($operationType == '1') { //tempdelete
                try {
                    $note = delete($billpropertyid);
                    if ($note != "sucess") {
                        //get product category name

                        if (count($billpropertyid) > 0) {

                            $outputString .= $billpropertyname . ": " . $note . "<br/>";
                        }
                    }
                } catch (Exception $e) {

                }
            } elseif ($operationType == "2") { //returndelete
                try {
                    $note = ruturndelete($billpropertyid);
                    if ($note != "sucess") {
                        //get product category name

                        if (count($billpropertyid) > 0) {

                            $outputString .= $billpropertyname . ": " . $note . "<br/>";
                        }
                    }
                } catch (Exception $e) {
                    $note = "حدث خطأ أثناء إتمام العملية";
                }
            }
            $i++;
        }
        $smarty->assign("outputString", $outputString);

        //print_r($outputString);
    }
}

function getallBillproperty() {
    global $BillpropertyEX;
    global $BillpropertyDAO;
    global $Billproperty;


    $allBillproperty = $BillpropertyDAO->queryByCondition(0);
    return $allBillproperty;
}

function copyBillSetting($billnameid) {
    global $BillnameDAO;
    global $Billname;
    global $BillsettingEX;
    global $Billsetting;
    global $myRelusergrouppropertieExt;

    //get data
    $Billname = $BillnameDAO->load($billnameid);
    $Billsettingdata = $BillsettingEX->queryByBillnameidSimple($billnameid);

    ##1-insert bill name data
    $Billname->billnameid = NULL;
    $Billname->userid = $_SESSION['userid'];
    $Billname->billnamedate = date("Y-m-d");
    $billnameid_new = $BillnameDAO->insert($Billname);
    $Billname->name = $Billname->name . "_" . $billnameid_new;
    $BillnameDAO->update($Billname);

    ##1-insert bill setting data
    $insert_sql = "INSERT INTO billsettings (`billnameid`, `billpropertyid`, `billsettingsvalue`) VALUES ";
    foreach ($Billsettingdata as $value) {
        $insert_sql .= "(" . $billnameid_new . ", " . $value->billpropertyid . ", " . $value->billsettingsvalue . "),";
    }
    $insert_sql = trim($insert_sql, ',');
    $affected_rows = $myRelusergrouppropertieExt->insertBulk($insert_sql);
}
