<?php

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

//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.php");
include_once("dailyentryfun.php");

//here the db files that include in the file
include("../public/include_dao.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 :- productController

  OPERTATION in Controller

  1- display add form, add supplier cat and supplier with ajax
  2- add in supplier tbl
  2.1- insert into supplier unit tbl
  2.2- insert into storedetail tbl
  2.3- insert new row into storereport tbl
  3- display show and tempdelete
  4- edit supplier
  5- update supplier
  5.1- update supplier tbl with supplierid
  5.2- delete supplier units associated to this supplier from productunit tbl, then insert it again

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

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

//here goes the instances and general variables
//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();

//Supplierdebtchange
$Supplierdebtchange = new Supplierdebtchange();
$SupplierdebtchangeDAO = new SupplierdebtchangeMySqlDAO();
$SupplierdebtchangeEX = new SupplierdebtchangeMySqlExtDAO();

//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();


//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();
$dailyEntryCreditorDAO = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX = new DailyentrycreditorMySqlExtDAO();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();

$today = date("Y-m-d");

$Programsettingdata = $ProgramsettingDAO->load(1);
$smarty->assign("Programsettingdata", $Programsettingdata);


/* * * classes ** */
$rentProducts = new Rentproduct();
$myrentProducts = new RentproductMySqlDAO();
$extrentProducts = new RentproductMySqlExtDAO();

$rentStore = new Rentstore();
$myrentStore = new RentstoreMySqlDAO();
$extrentStore = new RentstoreMySqlExtDAO();

$supplier = new Supplier();
$mysupplier = new SupplierMySqlDAO();
$extsupplier = new SupplierMySqlExtDAO();

$save = new Save();
$mysave = new SaveMySqlDAO();
$extsave = new SaveMySqlExtDAO();

$Savedaily = new Savedaily();
$SavedailyDAO = new SavedailyMySqlDAO();

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

//check and use the condition that suite this action
if (empty($do)) {
    //here the permssion check
    include_once("../public/authentication.php");

    $suppliers = $mysupplier->queryAll();
    $smarty->assign('suppliers', $suppliers);

    //here the smarty templates
    $smarty->display("rent/products/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");

    //get vars
    $name = filter_input(INPUT_POST, 'name');
    $info = filter_input(INPUT_POST, 'info');
    $amount = filter_input(INPUT_POST, 'amount');
    $buyprice = filter_input(INPUT_POST, 'buyprice');
    $totalprice = filter_input(INPUT_POST, 'totalprice');
    $rentprice = filter_input(INPUT_POST, 'rentprice');
    $paytype = filter_input(INPUT_POST, 'paytype');
    $supplierid = filter_input(INPUT_POST, 'supplierid');
    $createdate = date('Y-m-d');

    $checkduplicate = $myrentProducts->queryByName($name);
    if (count($checkduplicate) > 0) {
        $smarty->assign('msg', 'تم ادخال  اسم المنتج  من قبل ');
        $smarty->display("rent/products/add.html");
    } else {

        try {

            $rentProducts->buyprice = $buyprice;
            $rentProducts->createdate = $createdate;
            $rentProducts->name = $name;
            $rentProducts->paytype = $paytype;
            $rentProducts->quantity = $amount;
            $rentProducts->rentprice = $rentprice;
            $rentProducts->supplierid = $supplierid;
            $rentProducts->totalprice = $totalprice;
            $rentProducts->info = $info;
            $rentProducts->isdel = 0;
            $rentProducts->dailyentryid = 0;

            $insertid = $myrentProducts->insert($rentProducts);


            $rentStore->amount = $amount;
            $rentStore->rented = 0;
            $rentStore->rentproductid = $insertid;
            $myrentStore->insert($rentStore);

            //check type
            //if cash or supplier
            if ($paytype == 0) {
                //cash
                #1 decrease save
                $saveinfo = $mysave->load($_SESSION['saveid']);
                $balanceBefore = $saveinfo->savecurrentvalue;
                $balanceAfter = $balanceBefore - $totalprice;

                #2 update save
                $save->savecurrentvalue = $balanceAfter;
                $save->userid = $_SESSION['userid'];
                $save->saveid = $_SESSION['saveid'];
                $extsave->updateSaveValue($save);

                #3 update save report
                $Savedaily->savedailydate = date("Y-m-d");
                $Savedaily->userid = $_SESSION['userid'];
                $Savedaily->savedailysavebefore = $balanceBefore;
                $Savedaily->savedailychangeamount = $totalprice;
                $Savedaily->savedailychangetype = 1;
                $Savedaily->saveid = $_SESSION['saveid'];
                $Savedaily->processname = 'اضافه منتج جديد للايجار';
                $Savedaily->savedailymodelid = $insertid;
                $Savedaily->savedailysaveafter = $balanceAfter;
                $Savedaily->tablename = 'rentproducts.php';

                $SavedailyDAO->insert($Savedaily);

                /* قيد اليومية للكاش */
                $dailyEntry->entryComment = 'تم اضافة منتج فى ادارة منتجات عن طريق  ( الكاش)';
                $dailyEntry->reverseofid = -9;

                //Dailyentrydebtor المشتريات
                $dailyEntryDebtorArray = array();
                $dailyEntryDebtor->value = $totalprice;
                $dailyEntryDebtor->accountstreeid = 12;

                //Dailyentrycreditor الخزنة
                $dailyEntryCreditorArray = array();
                $dailyEntryCreditor->value = $totalprice;
                //save session
                $saveid = $_SESSION['saveid'];
                $dataSave = $mysave->load($saveid);

                $idTreeSave = $dataSave->treeId;
                $dailyEntryCreditor->accountstreeid = $idTreeSave;


                array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

                $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
                $dailyId = $returnedData[1];

                $rentProductsData = $myrentProducts->load($insertid);

                $rentProducts->buyprice = $rentProductsData->buyprice;
                $rentProducts->createdate = $rentProductsData->createdate;
                $rentProducts->name = $rentProductsData->name;
                $rentProducts->paytype = $rentProductsData->paytype;
                $rentProducts->quantity = $rentProductsData->quantity;
                $rentProducts->rentprice = $rentProductsData->rentprice;
                $rentProducts->supplierid = $rentProductsData->supplierid;
                $rentProducts->totalprice = $rentProductsData->totalprice;
                $rentProducts->info = $rentProductsData->info;
                $rentProducts->isdel = $rentProductsData->isdel;
                $rentProducts->dailyentryid = $dailyId;

                $myrentProducts->update($rentProducts);
            } else {
                //supplier
                #1 increase supplier debt
                $supplierinfo = $mysupplier->load($supplierid);
                $debtBefore = $supplierinfo->suppliercurrentDebt;
                $debtAfter = $debtBefore + $totalprice;

                #2 update supplier debt
                $supplier->suppliercurrentDebt = $debtAfter;
                $supplier->userid = $_SESSION['userid'];
                $supplier->supplierdate = date("Y-m-d");
                $supplier->supplierid = $supplierid;
                $extsupplier->updatedept($supplier);

                #3 insert supplier debt change
                $Supplierdebtchange->comment = "";
                $Supplierdebtchange->processname = "إضافة منتجات للايجار تبع مورد ";
                $Supplierdebtchange->supplierdebtchangeafter = $debtAfter;
                $Supplierdebtchange->supplierdebtchangeamount = $totalprice;
                $Supplierdebtchange->supplierdebtchangebefore = $debtBefore;
                $Supplierdebtchange->supplierdebtchangedate = date("Y-m-d");
                $Supplierdebtchange->supplierdebtchangemodelid = $insertid;
                $Supplierdebtchange->supplierid = $supplierid;
                $Supplierdebtchange->supplierdebtchangetype = 0;
                $Supplierdebtchange->tablename = "rentproducts.php";
                $Supplierdebtchange->userid = $_SESSION['userid'];
                $Supplierdebtchange->dailyentryid = 0;

                $SupplierdebtchangeDAO->insert($Supplierdebtchange);

                /* قيد اليومية للاجل */
                $dailyEntry->entryComment = 'تم اضافة منتج فى ادارة منتجات عن طريق  ( الاجل)';
                $dailyEntry->reverseofid = -9;

                //Dailyentrydebtor المشتريات
                $dailyEntryDebtorArray = array();
                $dailyEntryDebtor->value = $totalprice;
                $dailyEntryDebtor->accountstreeid = 12;

                //Dailyentrycreditor الدائنون - المورد
                $dailyEntryCreditorArray = array();
                $dailyEntryCreditor->value = $totalprice;
                //supplier
                $oldSupplier = $mysupplier->load($supplierid);

                $treeId = $oldSupplier->treeId;
                $dailyEntryCreditor->accountstreeid = $treeId;


                array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
                array_push($dailyEntryCreditorArray, $dailyEntryCreditor);


                $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
                $dailyId = $returnedData[1];

                $rentProductsData = $myrentProducts->load($insertid);

                $rentProducts->buyprice = $rentProductsData->buyprice;
                $rentProducts->createdate = $rentProductsData->createdate;
                $rentProducts->name = $rentProductsData->name;
                $rentProducts->paytype = $rentProductsData->paytype;
                $rentProducts->quantity = $rentProductsData->quantity;
                $rentProducts->rentprice = $rentProductsData->rentprice;
                $rentProducts->supplierid = $rentProductsData->supplierid;
                $rentProducts->totalprice = $rentProductsData->totalprice;
                $rentProducts->info = $rentProductsData->info;
                $rentProducts->isdel = $rentProductsData->isdel;
                $rentProducts->dailyentryid = $dailyId;

                $myrentProducts->update($rentProducts);
            }




            header("location:?do=sucess");
        } catch (Exception $exc) {
            header("location:?do=error");
            //   print_r($exc);
        }
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");

    $allproducts = $extrentProducts->queryAllwithnodel();
    $smarty->assign('allproducts', $allproducts);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $smarty->assign('customUsergroup', 1); //for delete model
    $smarty->display("rent/products/show.html");
} elseif ($do == "edit") {
    include_once("../public/authentication.php");
    $id = filter_input(INPUT_GET, 'id');

    $suppliers = $mysupplier->queryAll();
    $smarty->assign('suppliers', $suppliers);

    $product = $myrentProducts->load($id);
    $smarty->assign('product', $product);

    $smarty->display("rent/products/edit.html");
} elseif ($do == "editprint") {
    include_once("../public/authentication.php");
    $id = filter_input(INPUT_GET, 'id');

    $suppliers = $mysupplier->queryAll();
    $smarty->assign('suppliers', $suppliers);

    $product = $myrentProducts->load($id);
    $smarty->assign('product', $product);

    $smarty->display("rent/products/editprint.html");
} elseif ($do == "update") {
    include_once("../public/authentication.php");
    //get vars
    $name = filter_input(INPUT_POST, 'name');
    $info = filter_input(INPUT_POST, 'info');
    $buyprice = filter_input(INPUT_POST, 'buyprice');
    $totalprice = filter_input(INPUT_POST, 'totalprice');
    $rentprice = filter_input(INPUT_POST, 'rentprice');
    $id = filter_input(INPUT_POST, 'id');

    //Transaction
    $mytransactions = new Transaction();
    try {

        $product = $myrentProducts->load($id);

        if ($product->paytype == 0) {
            reverseEntryWithItsID($product->dailyentryid, 1);
            /* قيد اليومية للكاش */
            $dailyEntry->entryComment = 'تم تعديل المنتج فى ادارة منتجات عن طريق  ( الكاش)';
            $dailyEntry->reverseofid = -9;
            //Dailyentrydebtor المشتريات
            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $totalprice;
            $dailyEntryDebtor->accountstreeid = 12;
            //Dailyentrycreditor الخزنة
            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $totalprice;
            //save session
            $saveid = $_SESSION['saveid'];
            $dataSave = $mysave->load($saveid);
            $idTreeSave = $dataSave->treeId;
            $dailyEntryCreditor->accountstreeid = $idTreeSave;
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
            $dailyId = $returnedData[1];
        } else if ($product->paytype == 1) {
            reverseEntryWithItsID($product->dailyentryid, 1);
            /* قيد اليومية للاجل */
            $dailyEntry->entryComment = 'تم تعديل المنتج فى ادارة منتجات عن طريق  ( الاجل)';
            $dailyEntry->reverseofid = -9;
            //Dailyentrydebtor المشتريات
            $dailyEntryDebtorArray = array();
            $dailyEntryDebtor->value = $totalprice;
            $dailyEntryDebtor->accountstreeid = 12;
            //Dailyentrycreditor الدائنون - المورد
            $dailyEntryCreditorArray = array();
            $dailyEntryCreditor->value = $totalprice;
            //supplier
            $oldSupplier = $mysupplier->load($product->supplierid);
            $treeId = $oldSupplier->treeId;
            $dailyEntryCreditor->accountstreeid = $treeId;
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
            array_push($dailyEntryCreditorArray, $dailyEntryCreditor);
            $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
            $dailyId = $returnedData[1];
        }
//    //update it
//    try {
        $rentProducts->buyprice = $buyprice;
        $rentProducts->name = $name;
        $rentProducts->rentprice = $rentprice;
        $rentProducts->totalprice = $totalprice;
        $rentProducts->info = $info;
        $rentProducts->id = $id;
        $rentProducts->dailyentryid = $dailyId;
        $extrentProducts->updateprice($rentProducts);

        $mytransactions->commit();
        header("location:?do=sucess");
    } catch (Exception $exc) {
        $mytransactions->rollback();
        header("location:?do=error");
    }
} elseif ($do == "tempdelete") {//tempdelete
    include_once("../public/authentication.php");

    //Transaction
    $mytransactions = new Transaction();
    try {


        $id = filter_input(INPUT_GET, 'id');
        $dailyentryid = $_GET['dailyentryid'];
        $rentProducts->id = $id;
        $rentProducts->isdel = 1;

        $extrentProducts->tempdelete($rentProducts);
        reverseEntryWithItsID($dailyentryid, 1);

        $mytransactions->commit();
        header("location:?do=sucess");
    } catch (Exception $e) {
        $mytransactions->commit();
        header("location:?do=error");
    }
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}
//here the global templates
$smarty->assign("rentjs", 1);
$smarty->display("footer.html");

/* ===============================
  function in this CONTROLLER
  ================================ */
?>