<?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");
include_once("../library/num_to_ar.php");

//here the db files that include in the file
include("../public/include_dao.php");
//Supplier
require_once('../models/dao/SupplierDAO.class.php');
require_once('../models/dto/Supplier.class.php');
require_once('../models/mysql/SupplierMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierMySqlExtDAO.class.php');
//Supplierdebtchange
require_once('../models/dao/SupplierdebtchangeDAO.class.php');
require_once('../models/dto/Supplierdebtchange.class.php');
require_once('../models/mysql/SupplierdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/SupplierdebtchangeMySqlExtDAO.class.php');
//Save
require_once('../models/dao/SaveDAO.class.php');
require_once('../models/dto/Save.class.php');
require_once('../models/mysql/SaveMySqlDAO.class.php');
require_once('../models/mysql/ext/SaveMySqlExtDAO.class.php');
//Savedaily
require_once('../models/dao/SavedailyDAO.class.php');
require_once('../models/dto/Savedaily.class.php');
require_once('../models/mysql/SavedailyMySqlDAO.class.php');
require_once('../models/mysql/ext/SavedailyMySqlExtDAO.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 :- supplierPayedDeptController

  OPERTATION in Controller

  1- display add form
  2- add row in supplierdebtchange tbl
  3- update supplier dept in supplier tbl
  ======================== */

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

//here goes the instances and general variables
//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();
//Supplier
$newSupplier = new Supplier();
$newSupplierDAO = new SupplierMySqlDAO();
$newSupplierExt = new SupplierMySqlExtDAO();
//Supplierdebtchange
$supplierDeptChange = new Supplierdebtchange();
$supplierDeptChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptChangeExt = new SupplierdebtchangeMySqlExtDAO();
//suppay
$suppay = new Suppay();
$suppayDAO = new SuppayMySqlDAO();
$suppayExt = new SuppayMySqlExtDAO();


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


//save
$Save = new Save();
$SaveDAO = new SaveMySqlDAO();
$SaveExt = new SaveMySqlExtDAO();

$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();

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

//Accountstree
$accountsTree = new Accountstree();
$accountsTreeDAO = new AccountstreeMySqlDAO();
$accountsTreeEX = new AccountstreeMySqlExtDAO();

//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();

$bankDAO = new BankMySqlDAO;
$bank = new Bank;
$bankExtDAO = new BankMySqlExtDAO;

//Bankaccount
$myBankaccount = new Bankaccount();
$myBankaccountRecord = new BankaccountMySqlDAO();
$myBankaccountEx = new BankaccountMySqlExtDAO();

$ProgramsettingDAO = new ProgramsettingsMySqlDAO();

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

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

    $suppliersData = getSuppliers(); //undeleted suppliers
    $smarty->assign("suppliersData", $suppliersData);
    $smarty->assign("today", $today);

    $bank = $bankExtDAO->queryAllExt();
    //print_r($bank);
    $smarty->assign("bank", $bank);

    $smarty->assign("suplliernegative", $_SESSION['suplliernegative']);
    //here the smarty templates
    $smarty->assign("customSupPay", 1);
    $smarty->display("supPayView/add.html");
} elseif ($do == "show") {
    //here the permssion check
    include_once("../public/authentication.php");

    try {
        $supplierData = getSupplierData();
        $smarty->assign('supplierData', $supplierData);

        $suppayData = $suppayDAO->queryAll();
        $smarty->assign('suppayData', $suppayData);

        $startDate = $_POST['from'];
        $endDate = $_REQUEST['to'];
        $supplierId = $_POST['supplierId'];

        if ((isset($supplierId) && $supplierId != "-1") || (!empty($startDate) && !empty($endDate)) || (!empty($startDate) && empty($endDate)) || (empty($startDate) && !empty($endDate))) {
            $messageData = $supplierDAO->load($supplierId);
            $message = " اسم المورد : " . $messageData->suppliername . "التاريخ: من: " . $startDate . " إلى: " . $endDate;
            $smarty->assign("message", $message);
            showx($supplierId, $startDate, $endDate);
        } else {
            //showall();
            show($today, $today);
        }
        /* if(isset($startDate) && isset($endDate) && $startDate !="" && $endDate !="")
          {
          $message = "التاريخ: من: ".$startDate." إلى: ".$endDate;
          $smarty->assign("message",$message);

          show($startDate, $endDate);
          }

          else
          {
          $today=date("Y-m-d");
          show($today, $today);
          } */

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

        $smarty->assign("customSupPay", 1);
        $smarty->display("supPayView/show.html");
    } catch (Exception $ex) {
        print_r($ex);
    }
} elseif ($do == "add") {
    include_once("../public/authentication.php");

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

        $mytransactions->commit();
        header("location:?do=sucess");
    } catch (Exception $e) {
        $mytransactions->rollback();
        header("location:?do=error");
    }
} elseif ($do == "edit") {
    include_once("../public/authentication.php");
    $supplierdebtchangeId = $_GET['id'];

    // one row
    $supplierdebtchangeData = edit($supplierdebtchangeId);
    $smarty->assign("supplierdebtchangeData", $supplierdebtchangeData);

    // all rows
    $suppliersData = getSuppliers(); //undeleted suppliers
    $smarty->assign("suppliersData", $suppliersData);

    $supPayData = supData($supplierdebtchangeId);
    $smarty->assign("supPayData", $supPayData[0]);

//    print_r('<pre>');
//    print_r($supPayData);
//    print_r('<pre>');

    $bankAccount = $myBankaccountEx->queryWithOrder();
    $smarty->assign("bankaccount", $bankAccount);


    $bank = $bankExtDAO->queryAllExt();
    //print_r($bank);
    $smarty->assign("bank", $bank);


    $smarty->assign("suplliernegative", $_SESSION['suplliernegative']);
    //here the smarty templates
    $smarty->assign("customSupPay", 1);

    $smarty->display('supPayView/edit.html');
} elseif ($do == "update") {
    include_once("../public/authentication.php");

    //Transaction
    $mytransactions = new Transaction();
    //update();
    try {
        update();
        $mytransactions->commit();
        header("location:?do=sucess");
    } catch (Exception $e) {
        print_r($e);
        $mytransactions->rollback();
        header("location:?do=error");
    }
} elseif ($do == "editprint") {
    include_once("../public/authentication.php");


    $supplierData = getSupplierData();
    $smarty->assign('supplierData', $supplierData);

    // suppay data
    $supPayData = $suppayDAO->queryAll();
    $smarty->assign('supPayData', $supPayData);

    // bank account
    $accountData = $myBankaccountRecord->queryAll();
    $smarty->assign('accountData', $accountData);

    $alldata = editprint();
    $smarty->assign('alldata', $alldata);

    $programsettingsdata = $ProgramsettingDAO->load(1);
    $smarty->assign('programsettingsdata', $programsettingsdata);

    try {
        $ar_number = new convert_ar($alldata->supplierdebtchangeamount, "male");
        $arabic_num = $ar_number->convert_number();
        $arabic_num .= ' ' . $prog->currancy . ' فقط لاغير';
        $smarty->assign('arabicnum', $arabic_num);
    } catch (Exception $ex) {
        $arabic_num .= ' عفوا العدد خارج النطاق ';
        $smarty->assign('arabicnum', $arabic_num);
    }

    $smarty->assign("customPrint", 1);
    //print_r($alldata);
    $smarty->display("supPayView/editprint.html");
} elseif ($do == "editprint2") { // تقرير لمورد معين
    include_once("../public/authentication.php");

    $supplierdebtchangeId = $_GET['id'];

    $supplierdebtchangeData = edit($supplierdebtchangeId);
    $smarty->assign("supplierdebtchangeData", $supplierdebtchangeData);

    $suppliersData = getSuppliers(); //undeleted suppliers
    $smarty->assign("suppliersData", $suppliersData);

    $smarty->display("supPayView/editpriغغغغnt.html");
} elseif ($do == "remove") {
    include_once("../public/authentication.php");

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

        $mytransactions->commit();
        header("location:?do=sucess");
    } catch (Exception $e) {
        $mytransactions->rollback();
        header("location:?do=error");

        print_r($e);
    }
} 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("customValidation", 1);
//$smarty->assign("customSupPay", 1);
$smarty->display("footer.html");

/* ===============================
  function in this CONTROLLER
  ================================ */

function getSuppliers() {
    global $supplierDAO;
    $suppliersData = $supplierDAO->queryByCondition(0);
    return $suppliersData;
}

function getSupplierData() {
    global $supplierDAO;
    global $supplierExt;

    $alldata = $supplierDAO->queryAll();
    return $alldata;
}

// add in supplierdebtchange tbl
function add() {
    global $supplierExt;
    global $supplierDAO;
    global $supplier;
    global $supplierDeptChange;
    global $supplierDeptChangeDAO;
    global $today;

    global $mySave;
    global $mySaveRecord;
    //bankaccount
    global $myBankaccount;
    global $myBankaccountRecord;
    //suppay
    global $suppay;
    global $suppayDAO;
    //Dailyentry
    global $dailyEntry;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;

    global $accountsTreeDAO;
    global $accountsTree;

    $supplierid = $_POST["supplierid"];
    $payedDept = $_POST["payedDept"];
    $paytype = $_POST['paytype'];

    $bankid = $_POST['ddBank']; // bank id
    print_r($bankid . 'aaaaaaaaaaaaaa');
    $accountid = $_POST["accountid"]; //account number
    $chckNo = $_POST['txtcheckNum']; // check number
    $txtUser = $_POST['txtUser']; // user text
    $chckDate = $_POST['chckDate']; // check date
    $oldLogo = $_POST['logo']; // logo image name
    $sendBank = $_POST['sendBank']; // sender bank
    $textNote = $_POST['textNote']; // other details


    $supplierdata = $supplierDAO->load($supplierid);
    $debtBefore = $supplierdata->suppliercurrentDebt;
    $debtAfter = $debtBefore - $payedDept;


    //insert into supplierdeptchange tbl
    $supplierDeptChange->comment = "";
    $supplierDeptChange->processname = "سداد ديون مورد معين";
    $supplierDeptChange->supplierdebtchangeafter = $debtAfter;
    $supplierDeptChange->supplierdebtchangeamount = $payedDept;
    $supplierDeptChange->supplierdebtchangebefore = $debtBefore;
    $supplierDeptChange->supplierdebtchangedate = date("Y-m-d H:i:s");
    $supplierDeptChange->supplierdebtchangemodelid = -1;
    $supplierDeptChange->supplierdebtchangetype = 1;
    $supplierDeptChange->tablename = "supplierPayedDeptController.php";
    $supplierDeptChange->userid = $_SESSION['userid'];
    $supplierDeptChange->supplierid = $supplierid;
    $supplierDeptChange->dailyentryid = 0;
    //Insert
    $supplierDeptChangeId = $supplierDeptChangeDAO->insert($supplierDeptChange);

    //insert into suppay tbl
    $suppay->idsupdeptchange = $supplierDeptChangeId;
    $suppay->paytype = $paytype;
    if (isset($accountid)) {
        $suppay->accountid = $accountid;
        $suppay->bankid = $bankid;
        $suppay->checkno = $chckNo;
        $suppay->beneficiaryname = $txtUser;
        $suppay->chckdate = $chckDate;
        $suppay->chckimage = $oldLogo;
        $suppay->senderbank = $sendBank;
        $suppay->details = $textNote;
    }
    $suppay->del = 0;

    //Insert
    $suppayDAO->insert($suppay);

    if (isset($supplierDeptChangeId)) {
        //update current dept in supplier tbl
        $supplier->suppliercurrentDebt = $debtAfter;
        $supplier->userid = $_SESSION['userid'];
        $supplier->supplierdate = $today;
        $supplier->supplierid = $supplierid;

        $supplierExt->updatedept($supplier);

        //update save's current value
        //get saveVsalue before and saveValue after mins payedDept
        $valueData = getSaveValueAndMins($payedDept);
        if (count($valueData) > 0) {
            $saveId = $valueData[0];
            $saveValuebefore = $valueData[1];
            $saveValueafter = $valueData[2];

            //update save value after payedDept
            updateSave($saveId, $saveValueafter);
            //insert into savedaily tbl
            insertSavedaily($saveValuebefore, $payedDept, 1, $saveId, "سداد ديون مورد", $supplierDeptChangeId, $saveValueafter, "supplierPayedDeptController.php");
        }
    }

    if ($paytype == 0) {
        $dailyEntry->entryComment = 'اضافة ايصال للمورد( ' . $supplierdata->suppliername . ' ) عن طريق الخزنة ';

        // start 7saaab L da2noon
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $payedDept;
        $oldSupplier = $supplierDAO->load($supplierid);

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


        /// end 7saaab L da2noon
        //start Save
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $payedDept;
        //save session
        $saveid = $_SESSION['saveid'];
        $dataSave = $mySaveRecord->load($saveid);

        $idTreeSave = $dataSave->treeId;
        $dailyEntryCreditor->accountstreeid = $idTreeSave;
        /// end Save

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

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

        $rowData = $supplierDeptChangeDAO->load($supplierDeptChangeId);

        $supplierDeptChange->comment = $rowData->comment;
        $supplierDeptChange->processname = $rowData->processname;
        $supplierDeptChange->supplierdebtchangeafter = $rowData->supplierdebtchangeafter;
        $supplierDeptChange->supplierdebtchangeamount = $rowData->supplierdebtchangeamount;
        $supplierDeptChange->supplierdebtchangebefore = $rowData->supplierdebtchangebefore;
        $supplierDeptChange->supplierdebtchangedate = $rowData->supplierdebtchangedate;
        $supplierDeptChange->supplierdebtchangemodelid = $rowData->supplierdebtchangemodelid;
        $supplierDeptChange->supplierdebtchangetype = $rowData->supplierdebtchangetype;
        $supplierDeptChange->tablename = $rowData->tablename;
        $supplierDeptChange->userid = $rowData->userid;
        $supplierDeptChange->supplierid = $rowData->supplierid;
        $supplierDeptChange->dailyentryid = $did;

        $supplierDeptChangeDAO->update($supplierDeptChange);
    } else {
        $dailyEntry->entryComment = 'سداد ديون للمورد ( ' . $supplierdata->suppliername . ' ) عن طريق الشيك ';

        // start 7saaab L da2noon
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $payedDept;
        $oldSupplier = $supplierDAO->load($supplierid);

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


        /// end 7saaab L da2noon
        //start Save
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $payedDept;
        $dataBankAccount = $myBankaccountRecord->load($accountid);

        $myBankaccount->accountbeginingbalance = ($dataBankAccount->accountbeginingbalance) - $payedDept;
        $myBankaccount->accountcurrencytype = $dataBankAccount->accountcurrencytype;
        $myBankaccount->accountdate = $dataBankAccount->accountdate;
        $myBankaccount->accountid = $dataBankAccount->accountid;
        $myBankaccount->accountname = $dataBankAccount->accountname;
        $myBankaccount->accountnumber = $dataBankAccount->accountnumber;
        $myBankaccount->bankid = $dataBankAccount->bankid;
        $myBankaccount->bankname = $dataBankAccount->bankname;
        $myBankaccount->comment = $dataBankAccount->comment;
        $myBankaccount->conditions = $dataBankAccount->conditions;
        $myBankaccount->userid = $dataBankAccount->userid;

        $myBankaccountRecord->update($myBankaccount, $comment);

        $idTreeBankAccount = $dataBankAccount->treeId;
        $dailyEntryCreditor->accountstreeid = $idTreeBankAccount;
        /// end Save

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


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

        $rowData = $supplierDeptChangeDAO->load($supplierDeptChangeId);

        $supplierDeptChange->comment = $rowData->comment;
        $supplierDeptChange->processname = $rowData->processname;
        $supplierDeptChange->supplierdebtchangeafter = $rowData->supplierdebtchangeafter;
        $supplierDeptChange->supplierdebtchangeamount = $rowData->supplierdebtchangeamount;
        $supplierDeptChange->supplierdebtchangebefore = $rowData->supplierdebtchangebefore;
        $supplierDeptChange->supplierdebtchangedate = $rowData->supplierdebtchangedate;
        $supplierDeptChange->supplierdebtchangemodelid = $rowData->supplierdebtchangemodelid;
        $supplierDeptChange->supplierdebtchangetype = $rowData->supplierdebtchangetype;
        $supplierDeptChange->tablename = $rowData->tablename;
        $supplierDeptChange->userid = $rowData->userid;
        $supplierDeptChange->supplierid = $rowData->supplierid;
        $supplierDeptChange->dailyentryid = $did;



        $supplierDeptChangeDAO->update($supplierDeptChange);
    }
}

function update() {
    global $supplierExt;
    global $supplierDAO;
    global $supplier;
    global $newSupplier;
    global $newSupplierDAO;
    global $supplierDeptChange;
    global $supplierDeptChangeDAO;
    global $today;

    global $mySave;
    global $mySaveRecord;
    //bankaccount
    global $myBankaccount;
    global $myBankaccountRecord;
    //suppay
    global $suppay;
    global $suppayDAO;
    //Dailyentry
    global $dailyEntry;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;

    global $accountsTreeDAO;
    global $accountsTree;



    $payedDept = $_POST["payedDept"];
    $paytype = $_POST['paytype'];
    $accountid = $_POST["accountid"];
    $supPayId = $_POST['supPayId'];
    $supplierid = $_POST["supplierid"];
    $debtBefore_2 = $_POST["debtBefore"];

    $supplierdata = $supplierDAO->load($supplierid);
    $debtBefore = $supplierdata->suppliercurrentDebt;
    $debtAfter = $debtBefore - $payedDept;

    $oldSupplierId = $_POST['oldSupplierId'];
    $oldSupplierAmount = $_POST['oldSupplierAmount'];
    $oldSupplierAfter = $_POST['oldSupplierAfter'];

    $bankid = $_POST['ddlBank']; // bank id
    print_r($bankid . 'aaaaaaaaaaaaaa');

    $chckNo = $_POST['txtcheckNum']; // check number
    $txtUser = $_POST['txtUser']; // user text
    $chckDate = $_POST['chckDate']; // check date
    $Logo = $_POST['logo']; // logo image name
    $oldLogo = $_POST['oldlogo']; // logo image name
    $sendBank = $_POST['sendBank']; // sender bank
    $textNote = $_POST['textNote']; // other details
    //reset suppliercurrentDebt of old supplier and update suppliercurrentDebt of new supplier
    if ($oldSupplierId != $supplierid) {
        $oldSupplier = $supplierDAO->load($oldSupplierId);
        $supplier->conditions = $oldSupplier->conditions;
        $supplier->dailyentryid = $oldSupplier->dailyentryid;
        $supplier->supplieraddress = $oldSupplier->supplieraddress;
        $supplier->supplierdate = $oldSupplier->supplierdate;
        $supplier->supplierdetails = $oldSupplier->supplierdetails;
        $supplier->supplierid = $oldSupplier->supplierid;
        $supplier->suppliername = $oldSupplier->suppliername;
        $supplier->supplierphone = $oldSupplier->supplierphone;
        $supplier->userid = $oldSupplier->userid;
        $supplier->suppliercurrentDebt = $oldSupplierAmount + $oldSupplierAfter;


        $supplierDAO->update($supplier);

        // update new supplier
        $newSupplierData = $supplierDAO->load($supplierid);
        $newSupplier->conditions = $newSupplierData->conditions;
        $newSupplier->dailyentryid = $newSupplierData->dailyentryid;
        $newSupplier->supplieraddress = $newSupplierData->supplieraddress;
        $newSupplier->supplierdate = $newSupplierData->supplierdate;
        $newSupplier->supplierdetails = $newSupplierData->supplierdetails;
        $newSupplier->supplierid = $newSupplierData->supplierid;
        $newSupplier->suppliername = $newSupplierData->suppliername;
        $newSupplier->supplierphone = $newSupplierData->supplierphone;
        $newSupplier->userid = $newSupplierData->userid;
        $newSupplier->suppliercurrentDebt = $debtAfter;

        $supplierDAO->update($newSupplier);

        $supplierdebtchangeid = filter_input(INPUT_POST, 'supplierdebtchangeid');
        $supplierDebtChangeData = $supplierDeptChangeDAO->load($supplierdebtchangeid);
        //Update into supplierdeptchange tbl
        $supplierDeptChange->comment = "";
        $supplierDeptChange->processname = "سداد ديون مورد معين";
        $supplierDeptChange->supplierdebtchangeafter = $debtAfter;
        $supplierDeptChange->supplierdebtchangeamount = $payedDept;
        $supplierDeptChange->supplierdebtchangebefore = $debtBefore;
        $supplierDeptChange->supplierdebtchangedate = date("Y-m-d H:i:s");
        $supplierDeptChange->supplierdebtchangemodelid = -1;
        $supplierDeptChange->supplierdebtchangetype = 1;
        $supplierDeptChange->tablename = "supplierPayedDeptController.php";
        $supplierDeptChange->userid = $_SESSION['userid'];
        $supplierDeptChange->supplierid = $supplierid;
        $supplierDeptChange->dailyentryid = $supplierDebtChangeData->dailyentryid;
        $supplierDeptChange->supplierdebtchangeid = $supplierdebtchangeid;

        //Update
        $supplierDeptChangeDAO->update($supplierDeptChange);
        $id = $supplierDebtChangeData->dailyentryid;
        reverseEntryWithItsID($id, 1);
    } else {

        $debtAfter = $debtBefore_2 - $payedDept;

        // update new supplier
        $newSupplierData = $supplierDAO->load($supplierid);
        $newSupplier->conditions = $newSupplierData->conditions;
        $newSupplier->dailyentryid = $newSupplierData->dailyentryid;
        $newSupplier->supplieraddress = $newSupplierData->supplieraddress;
        $newSupplier->supplierdate = $newSupplierData->supplierdate;
        $newSupplier->supplierdetails = $newSupplierData->supplierdetails;
        $newSupplier->supplierid = $newSupplierData->supplierid;
        $newSupplier->suppliername = $newSupplierData->suppliername;
        $newSupplier->supplierphone = $newSupplierData->supplierphone;
        $newSupplier->userid = $newSupplierData->userid;
        $newSupplier->suppliercurrentDebt = $debtAfter;

        $supplierDAO->update($newSupplier);

        $supplierdebtchangeid = filter_input(INPUT_POST, 'supplierdebtchangeid');
        $supplierDebtChangeData = $supplierDeptChangeDAO->load($supplierdebtchangeid);
        //Update into supplierdeptchange tbl
        $supplierDeptChange->comment = "";
        $supplierDeptChange->processname = "سداد ديون مورد معين";
        $supplierDeptChange->supplierdebtchangeafter = $debtAfter;
        $supplierDeptChange->supplierdebtchangeamount = $payedDept;
        $supplierDeptChange->supplierdebtchangebefore = $debtBefore_2;
        $supplierDeptChange->supplierdebtchangedate = date("Y-m-d H:i:s");
        $supplierDeptChange->supplierdebtchangemodelid = -1;
        $supplierDeptChange->supplierdebtchangetype = 1;
        $supplierDeptChange->tablename = "supplierPayedDeptController.php";
        $supplierDeptChange->userid = $_SESSION['userid'];
        $supplierDeptChange->supplierid = $supplierid;
        $supplierDeptChange->dailyentryid = $supplierDebtChangeData->dailyentryid;
        $supplierDeptChange->supplierdebtchangeid = $supplierdebtchangeid;

        //Update
        $supplierDeptChangeDAO->update($supplierDeptChange);
        $id = $supplierDebtChangeData->dailyentryid;
        reverseEntryWithItsID($id, 1);
    }




    $supPayData = $suppayDAO->load($supPayId);

    //update into suppay tbl
    $suppay->id = $supPayData->id;
    $suppay->idsupdeptchange = $supplierdebtchangeid;
    // print_r($paytype . 'aaaaaaa' . $accountid . 'bbbbb' . $bankid . 'cccc' . $chckNo . 'dddd' . $txtUser . 'eeeeeee' . $chckDate . 'fffff' . $oldLogo . 'ggggg' . $sendBank . 'qqqq' . $textNote);
    $suppay->paytype = $paytype;
    if (isset($accountid)) {
        $suppay->accountid = $accountid;
        $suppay->bankid = $bankid;
        $suppay->checkno = $chckNo;
        $suppay->beneficiaryname = $txtUser;
        $suppay->chckdate = $chckDate;
        if (!empty($Logo))
            $suppay->chckimage = $Logo;
        else
            $suppay->chckimage = $oldLogo;
        $suppay->senderbank = $sendBank;
        $suppay->details = $textNote;
    }
    $suppay->del = 0;
//    print_r('<pre>');
//    print_r($suppay);
//    print_r('<pre>');
    //update
    $suppayDAO->update($suppay);



    if ($paytype == 0) {
        $dailyEntry->entryComment = 'اضافة ايصال للمورد( ' . $supplierdata->suppliername . ' ) عن طريق الخزنة ';
        $dailyEntry->reverseofid = 0;
        // start 7saaab L da2noon
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $payedDept;
        $oldSupplier = $supplierDAO->load($supplierid);

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


        /// end 7saaab L da2noon
        //start Save
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $payedDept;
        //save session
        $saveid = $_SESSION['saveid'];
        $dataSave = $mySaveRecord->load($saveid);

        $idTreeSave = $dataSave->treeId;
        $dailyEntryCreditor->accountstreeid = $idTreeSave;
        /// end Save

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

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

        $rowData = $supplierDeptChangeDAO->load($supplierdebtchangeid);

        $supplierDeptChange->comment = $rowData->comment;
        $supplierDeptChange->processname = $rowData->processname;
        $supplierDeptChange->supplierdebtchangeafter = $rowData->supplierdebtchangeafter;
        $supplierDeptChange->supplierdebtchangeamount = $rowData->supplierdebtchangeamount;
        $supplierDeptChange->supplierdebtchangebefore = $rowData->supplierdebtchangebefore;
        $supplierDeptChange->supplierdebtchangedate = $rowData->supplierdebtchangedate;
        $supplierDeptChange->supplierdebtchangemodelid = $rowData->supplierdebtchangemodelid;
        $supplierDeptChange->supplierdebtchangetype = $rowData->supplierdebtchangetype;
        $supplierDeptChange->tablename = $rowData->tablename;
        $supplierDeptChange->userid = $rowData->userid;
        $supplierDeptChange->supplierid = $rowData->supplierid;
        $supplierDeptChange->dailyentryid = $did;

        $supplierDeptChangeDAO->update($supplierDeptChange);
    } else {
        $dailyEntry->entryComment = 'سداد ديون للمورد ( ' . $supplierdata->suppliername . ' ) عن طريق الشيك ';
        $dailyEntry->reverseofid = 0;

        // start 7saaab L da2noon
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $payedDept;
        $oldSupplier = $supplierDAO->load($supplierid);

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


        /// end 7saaab L da2noon
        //start bank account
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $payedDept;
        $dataBankAccount = $myBankaccountRecord->load($accountid);


        $idTreeBankAccount = $dataBankAccount->treeId;
        $dailyEntryCreditor->accountstreeid = $idTreeBankAccount;
        /// end bank account

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


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

        $rowData = $supplierDeptChangeDAO->load($supplierdebtchangeid);

        $supplierDeptChange->comment = $rowData->comment;
        $supplierDeptChange->processname = $rowData->processname;
        $supplierDeptChange->supplierdebtchangeafter = $rowData->supplierdebtchangeafter;
        $supplierDeptChange->supplierdebtchangeamount = $rowData->supplierdebtchangeamount;
        $supplierDeptChange->supplierdebtchangebefore = $rowData->supplierdebtchangebefore;
        $supplierDeptChange->supplierdebtchangedate = $rowData->supplierdebtchangedate;
        $supplierDeptChange->supplierdebtchangemodelid = $rowData->supplierdebtchangemodelid;
        $supplierDeptChange->supplierdebtchangetype = $rowData->supplierdebtchangetype;
        $supplierDeptChange->tablename = $rowData->tablename;
        $supplierDeptChange->userid = $rowData->userid;
        $supplierDeptChange->supplierid = $rowData->supplierid;
        $supplierDeptChange->dailyentryid = $did;



        $supplierDeptChangeDAO->update($supplierDeptChange);
    }
}

function edit($supplierDeptChangeId) {
    global $supplierDeptChangeDAO;

    $supplierdebtchangeData = $supplierDeptChangeDAO->load($supplierDeptChangeId);

    return $supplierdebtchangeData;
}

function supData($supplierDeptChangeId) {
    global $suppayDAO;

    $suppayData = $suppayDAO->queryByIdsupdeptchange($supplierDeptChangeId);

    return $suppayData;
}

// get savecurrentvalue and mins from save tbl
function getSaveValueAndMins($savevaluechanged) {
    global $Save;
    global $SaveDAO;

    $saveData = $SaveDAO->load($_SESSION['saveid']);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// update Save tbl
function updateSave($saveid, $savevalueafter) {
    global $Save;
    global $SaveExt;

    //update savecurrentvalue in Save tbl
    $Save->savecurrentvalue = $savevalueafter;
    $Save->userid = $_SESSION['userid'];
    $Save->saveid = $saveid;

    $SaveExt->updateSaveValue($Save);
}

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {

    //to use the variable out side the funcion
    global $Savedaily;
    global $SavedailyDAO;

    //insert in Savedaily tbl
    $Savedaily->savedailydate = date("Y-m-d H:i:s");
    $Savedaily->userid = $_SESSION['userid'];
    $Savedaily->savedailysavebefore = $savedailysavebefore;
    $Savedaily->savedailychangeamount = $savedailychangeamount;
    $Savedaily->savedailychangetype = $savedailychangetype;
    $Savedaily->saveid = $saveid;
    $Savedaily->processname = $processname;
    $Savedaily->savedailymodelid = $savedailymodelid;
    $Savedaily->savedailysaveafter = $savedailysaveafter;
    $Savedaily->tablename = $tablename;

    $SavedailyDAO->insert($Savedaily);
}

//show
function show($startDate, $endDate) {
    global $supplierDeptChangeExt;
    global $smarty;


    // get the all colums number
    $shownData = $supplierDeptChangeExt->queryPayedDeptOnly($startDate, $endDate);

    $sum;
    foreach ($shownData as $data) {
        if ($data->del == 0) {
            $sum += $data->supplierdebtchangeamount;
        }
    }
    $smarty->assign('sum', $sum);

    // assign db results to the template
    $smarty->assign('shownData', $shownData);
}

function delete() {
    global $supplier;
    global $supplierExt;
    global $supplierDeptChange;
    global $supplierDeptChangeDAO;
    global $supplierDeptChangeExt;
    //suppay
    global $suppay;
    global $suppayDAO;

    $dailyentry = $_GET['dailyentry'];
    $suppayId = $_GET['suppayId'];


    $supplierDebtChangeId = $_GET['id'];
//    print_r('<pre>');
//    print_r($supplierDebtChangeId . 'aaaaaaaaaaaaaaaaa');
//    print_r('<pre>');
    $suppayData = $suppayDAO->load($suppayId);
    $suppay->id = $suppayData->id;
    $suppay->idsupdeptchange = $suppayData->idsupdeptchange;
    $suppay->paytype = $suppayData->paytype;
    $suppay->del = 1;

    $suppayDAO->update($suppay);

    $supplierData = $supplierDeptChangeDAO->load($supplierDebtChangeId);
    $supplierId = $supplierData->supplierid;
    $supplierDebtAfter = $supplierData->supplierdebtchangeafter;
    $supplierDebtBefore = $supplierData->supplierdebtchangebefore;
    $payedDebt = $supplierData->supplierdebtchangeamount;
    $supplierDate = $supplierData->supplierdebtchangedate;

    $supplierDebtAfterTotal = $supplierDebtAfter + $payedDebt;

    $supplier->suppliercurrentDebt = $supplierDebtAfterTotal;
    $supplier->userid = $_SESSION['userid'];
    $supplier->supplierdate = $supplierDate;
    $supplier->supplierid = $supplierId;

    $supplierExt->updatedept($supplier);

    //insert into supplierdeptchange tbl

    $supplierDeptChange->comment = "";
    $supplierDeptChange->processname = "الغاء سداد ديون مورد معين";
    $supplierDeptChange->supplierdebtchangeafter = $supplierDebtAfterTotal;
    $supplierDeptChange->supplierdebtchangeamount = $payedDebt;
    $supplierDeptChange->supplierdebtchangebefore = $supplierDebtAfter;
    $supplierDeptChange->supplierdebtchangedate = $supplierDate;
    $supplierDeptChange->supplierdebtchangemodelid = -1;
    $supplierDeptChange->supplierdebtchangetype = 1;
    $supplierDeptChange->tablename = "supplierPayedDeptController.php";
    $supplierDeptChange->userid = $_SESSION['userid'];
    $supplierDeptChange->del = 1;
    $supplierDeptChange->supplierid = $supplierId;
    $supplierDeptChange->dailyentryid = $supplierData->dailyentryid;
    $supplierDeptChange->supplierdebtchangeid = $supplierDebtChangeId;
//    print_r('<pre>');
//    print_r($supplierDeptChange);
//    print_r('<pre>');

    $supplierDeptChangeExt->updateDebt($supplierDeptChange);


    reverseEntryWithItsID($dailyentry, 1);
}

//editprint
function editprint() {
    global $supplierDeptChangeExt;
    global $supplierDeptChangeDAO;

    $id = $_GET["id"];
    $alldata = $supplierDeptChangeDAO->load($id);


    return $alldata;
}

function convertNumber() {
    try {
        $ar_number = new convert_ar($updatevalue, "male");
        $arabic_num = $ar_number->convert_number();
        $arabic_num .= ' ' . $prog->currancy . ' فقط لاغير';
    } catch (Exception $ex) {
        $arabic_num .= ' عفوا العدد خارج النطاق ';
    }
}

function showx($supplierId, $startDate, $endDate) {
    global $supplierDeptChangeExt;
    global $supplierdebtchange;
    global $supplierDAO;
    global $smarty;
    global $queryString;
    $queryString = ' WHERE';

    if (isset($supplierId) && $supplierId != "-1" && $supplierId != "-2") {
        $messageData = $supplierDAO->load($supplierId);
        $message = "إسم المورد: " . $messageData->suppliername;
        $smarty->assign("message", $message);

        $queryString .= ' supplierdebtchange.supplierid =' . $supplierId . ' AND';
    }

    if (isset($supplierId) && $supplierId != "-1" && $supplierId == "-2") {

        $message = " كل الموردين ";
        $smarty->assign("message", $message);

        $queryString .= ' supplierdebtchange.supplierid > 0 AND';
    }


    if (!empty($startDate) && !empty($endDate) && $supplierId = -1) {

        // print_r($startDate . 'aaaaaaaaaaaa' . $endDate . 'bbbbbbbbbbb' . $supplierId);

        $message = "  عرض ايصالات الدفع من تاريخ " . $startDate . "  الى تاريخ " . $endDate;
        $smarty->assign('message', $message);


        $queryString .= ' supplierdebtchange.supplierdebtchangedate  >= "' . $startDate . ' 00:00:00" AND supplierdebtchange.supplierdebtchangedate <= "' . $endDate . ' 23:59:59" AND';
    }

    if (!empty($startDate) && empty($endDate) && $supplierId = -1) {
        $message = "  عرض ايصالات الدفع من تاريخ " . $startDate;
        $smarty->assign('message', $message);
        $queryString .= ' supplierdebtchange.supplierdebtchangedate >= "' . $startDate . ' 00:00:00" AND';
    }
    // print_r($startDate . 'aaaaaaaaaaaa' . $endDate . 'bbbbbbbbbbb' . $supplierId);
    if (empty($startDate) && !empty($endDate) && $supplierId = -1) {
        $message = "  عرض ايصالات الدفع الى تاريخ " . $endDate;
        $smarty->assign('message', $message);
        $queryString .= ' supplierdebtchange.supplierdebtchangedate <= "' . $endDate . ' 23:59:59" AND';
    }
    $arr = explode(' ', $queryString);
    if (isset($arr) && count($arr) > 0) {
        $lastWord = end($arr);
        if ($lastWord == 'AND') {//remove it
            array_pop($arr);
            //form the string again
            $queryString = implode(' ', $arr);
        } else if ($lastWord == 'WHERE') {//remove it
            array_pop($arr);
            $queryString = ' ';
        }
        // print("<br>queryString: " . $queryString . "<br>");
    }

    $shownData = $supplierDeptChangeExt->searchPayedDeptOnly($queryString);

    $sum;
    foreach ($shownData as $data) {
        if ($data->del == 0) {

            $sum += $data->supplierdebtchangeamount;
        }
    }
    $smarty->assign('sum', $sum);

    // assign db results to the template
    $smarty->assign('shownData', $shownData);
}

?>