<?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
// GOES HERE ....................
include("../public/include_dao.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');

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

//AccountmovementkindDAO
require_once('../models/dao/TypesimpotencetreatmentDAO.class.php');
require_once('../models/dto/Typesimpotencetreatment.class.php');
require_once('../models/mysql/TypesimpotencetreatmentMySqlDAO.class.php');
require_once('../models/mysql/ext/TypesimpotencetreatmentMySqlExtDAO.class.php');

//Impotencetreatmentsuppliersave
require_once('../models/dao/ImpotencetreatmentsuppliersaveDAO.class.php');
require_once('../models/dto/Impotencetreatmentsuppliersave.class.php');
require_once('../models/mysql/ImpotencetreatmentsuppliersaveMySqlDAO.class.php');
require_once('../models/mysql/ext/ImpotencetreatmentsuppliersaveMySqlExtDAO.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');

//Breadcrumb
require_once("../library/breadcrumb.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 :- settlementsaveCTRL  تسوية خزنة بالخصم والاإضافة

  OPERTATION in Controller

  1-display add form
  3-update save value (-) or (+)
  4-insert into savedaily tbl
  5-display sucess or error
  6-display show form

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


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


//here goes the instances and general variables
//save
$mySave = new Save();
$mySaveRecord = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();


//Supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierExt = new SupplierMySqlExtDAO();

//Supplierdebtchange
$supplierDeptChange = new Supplierdebtchange();
$supplierDeptChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptChangeExt = new SupplierdebtchangeMySqlExtDAO();

//AccountmovementkindDAO
$myTypesimpotencetreatment = new Typesimpotencetreatment();
$myTypesimpotencetreatmentRecord = new TypesimpotencetreatmentMySqlDAO();
$myTypesimpotencetreatmentEx = new TypesimpotencetreatmentMySqlExtDAO();

//Impotencetreatmentsuppliersave
$myImpotencetreatmentsuppliersave = new Impotencetreatmentsuppliersave();
$myImpotencetreatmentsuppliersaveRecord = new ImpotencetreatmentsuppliersaveMySqlDAO();
$myImpotencetreatmentsuppliersaveEx = new ImpotencetreatmentsuppliersaveMySqlExtDAO();


//savedaily
$mySavedaily = new Savedaily();
$mySavedailyRecord = new SavedailyMySqlDAO();
$mySavedailyEx = new SavedailyMySqlExtDAO();


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

//Breadcrumb
$breadcrumbObject = new Breadcrumb();


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


//Dailyentry
$dailyEntry = new Dailyentry();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();


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



    $smarty->assign('searchinonesave', $_SESSION['searchinonesave']);
    if ($_SESSION['searchinonesave'] == 0) {
        if ($_SESSION['saveids'] == 0) {
            $saves = $mySaveRecord->queryByConditions(0);
        } else {
            $queryString = ' and saveid in (' . $_SESSION['saveids'] . ')';
            $saves = $mySaveEx->queryWithConditionWithQueryString($queryString);
        }
        $smarty->assign("saveData", $saves);

        $queryString = ' and saveid = ' . $_SESSION['saveid'] . ' ';
        $save = $mySaveEx->queryAllEXOne2($queryString);



        $smarty->assign('save', $save);
        $smarty->assign("saveid", $_SESSION['saveid']);
    } else {
        $queryString = ' and saveid = ' . $_SESSION['saveid'] . ' ';
        $save = $mySaveEx->queryAllEXOne2($queryString);
        $smarty->assign('save', $save);
        $smarty->assign('saveid', $_SESSION['saveid']);
    }
    // // here the function that do the action
    // $saveData = loadSave();
    // $smarty->assign("saveData", $saveData);

    $supplierData = getSupplierData();
    $smarty->assign('supplierData', $supplierData);
    $typesimpotencetreatmentData = getTypesImpotenceTreatmentData();
    $smarty->assign('typesimpotencetreatmentData', $typesimpotencetreatmentData);
    $loaddata = $supplierDeptChangeDAO->queryAll();
    $load_last_row = end($loaddata);
    $todayx = (int) $load_last_row->supplierdebtchangemodelid;
    $todayx = $todayx + 1;
    $smarty->assign("todayx", $todayx);

    //breadcrumb
    $breadcrumbObject->add('الحسابات><a href="settlementsaveController.php?do=show">تسوية الخزن</a> > اضافة تسوية لخزنة', 'settlementsaveController.php', 0);
    //Now output the navigation.
    $breadCrumb = $breadcrumbObject->output();
    $smarty->assign("breadCrumb", $breadCrumb);


    //here the smarty templates
    $smarty->display("settlementsaveview/add.html");

    $smarty->assign("customSettlementsave", 1);
} elseif ($do == "add") {

    //here the permssion check
    include_once("../public/authentication.php");

    // here the function that do the action
    $saveValuebeforeValid = add();
    if ($saveValuebeforeValid == "1") {


        header("location:?do=sucess");
    } else {
        $url = "settlementsaveController.php";
        $smarty->assign('urldirect', $url);
        $note = "لا يوجد بالخزنة المبلغ الكافى لتسوية خزنة";

        $smarty->assign('msgnote', $note);
        $smarty->display("notes.html");
    }
} elseif ($do == "show") {

    //here the permssion check
    include_once("../public/authentication.php");

    $smarty->assign('searchinonesave', $_SESSION['searchinonesave']);
    if ($_SESSION['searchinonesave'] == 0) {
        if ($_SESSION['saveids'] == 0) {
            $saves = $mySaveRecord->queryByConditions(0);
        } else {
            $queryString = ' and saveid in (' . $_SESSION['saveids'] . ')';
            $saves = $mySaveEx->queryWithConditionWithQueryString($queryString);
        }
        $smarty->assign("saveData", $saves);
    } else {
        $smarty->assign('saveid', $_SESSION['saveid']);
    }


    // $saveData = loadSave();
    // $smarty->assign("saveData", $saveData);


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

    $typesimpotencetreatmentData = getTypesImpotenceTreatmentData();
    $smarty->assign('typesimpotencetreatmentData', $typesimpotencetreatmentData);


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


    $saveId = $_REQUEST['saveid'];
    $supplierid = $_REQUEST['supplierid'];
    $typesimpotencetreatmentid = $_REQUEST['typesimpotencetreatmentid'];
    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];


    $searchQuery = " ";
    $message  = "";

    if ($saveId > 0) {
        $mysavedata = $mySaveRecord->load($saveId);
        $message .= " عرض معالجه عجز  للخزنه:" . $mysavedata->savename;
        $searchQuery .= " and impotencetreatmentsuppliersave.saveid = " . $saveId . " ";
    } else if ($_SESSION['searchinonesave'] == 0) {
        if ($_SESSION['saveids'] != 0) {
            $searchQuery .= ' and impotencetreatmentsuppliersave.saveid in (' . $_SESSION['saveids'] . ')';
        }
    } else {
        $searchQuery .= ' and impotencetreatmentsuppliersave.saveid = ' . $_SESSION['saveid'] . ' ';
    }


    if ($supplierid > '-1') {
        $supplierdata = $supplierDAO->load($supplierid);
        $message .= " عرض معالجه عجز  للمورد:" . $supplierdata->suppliername;
        $searchQuery .= " and impotencetreatmentsuppliersave.supplierid = " . $supplierid . " ";
    }

    if ($typesimpotencetreatmentid > 0) {
        $message .= " عرض معالجه عجز رقم:" . $typesimpotencetreatmentid;
        $searchQuery .= " and impotencetreatmentsuppliersave.typesimpotencetreatmentid = " . $typesimpotencetreatmentid . " ";
    }

    if ($startDate != '' && $endDate != '') {
        $message .= " عرض معالجه عجز الخزن من تاريخ :" . $startDate . "الى تاريخ:" . $endDate;

        $searchQuery .= 'and  impotencetreatmentsuppliersave.impotencetreatmentsuppliersavedate  >= "' . $startDate . ' 00-00-00" and impotencetreatmentsuppliersave.impotencetreatmentsuppliersavedate <= "' . $endDate . ' 23-59-55" ';
    }




    $savedaily = R::getAll('SELECT impotencetreatmentsuppliersave.*, suppliername, savename, typesimpotencetreatmentname FROM `impotencetreatmentsuppliersave`
            left join supplier on impotencetreatmentsuppliersave.supplierid = supplier.supplierid
            left join save on impotencetreatmentsuppliersave.saveid = save.saveid
            left join typesimpotencetreatment on impotencetreatmentsuppliersave.typesimpotencetreatmentid = typesimpotencetreatment.typesimpotencetreatmentid
              WHERE 1 and impotencetreatmentsuppliersave.conditions = 0 ' . $searchQuery . ' ');
    $smarty->assign('savedailyData', $savedaily);
    $smarty->assign('message', $message);



    $smarty->display("settlementsaveview/show.html");

    // $smarty->assign("customCheck", 1);
} elseif ($do == "editprint") {
    include_once("../public/authentication.php");

    $savedailyId = $_GET['id'];

    $loadData = loadSaveDaily($savedailyId);
    $smarty->assign("loadData", $loadData);


    $saveData = loadSave();
    $smarty->assign("saveData", $saveData);

    $smarty->display("settlementsaveview/editprint.html");

    $smarty->assign("customPrint", 1);
} elseif ($do == "sucess") {

    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {

    //here the smarty templates
    $smarty->display("error.html");
}



$smarty->assign("customSettlementsave", 1);

$smarty->assign("customValidation", 1);

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

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

function getTypesImpotenceTreatmentData()
{
    global $myTypesimpotencetreatment;
    global $myTypesimpotencetreatmentRecord;
    global $myTypesimpotencetreatmentEx;

    $alldata = $myTypesimpotencetreatmentEx->queryAllConditions();
    return $alldata;
}

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

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

//select all save data
function loadSave()
{

    //to use the variable out side the funcion
    global $mySaveRecord;

    //load all save data
    $saveData = $mySaveRecord->queryByConditions(0);

    return $saveData;
}

// add in savedaily tbl
function add()
{

    global $accountsTree;
    global $accountsTreeDAO;
    global $mySave;
    global $mySaveRecord;

    global $myImpotencetreatmentsuppliersave;
    global $myImpotencetreatmentsuppliersaveRecord;
    global $supplier;
    global $supplierDAO;
    global $supplierExt;


    //Dailyentry
    global $dailyEntry;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;

    global $supplierDeptChange;
    global $supplierDeptChangeDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;

    //to use the variable out side the funcion

    $saveId = $_POST['saveid'];
    $savedailychangeType = $_POST['savedailychangetype'];
    $savedailysaveBefore = $_POST['savedailysavebefore'];
    $savedailychangeAmount = $_POST['savedailychangeamount'];
    $savedailysaveAfter = $_POST['savedailysaveafter'];
    $supplierid = $_POST['supplierid'];
    $typesimpotencetreatmentid = $_POST['typesimpotencetreatmentid'];
    $note = $_POST['note'];


    $myImpotencetreatmentsuppliersave->typesimpotencetreatmentid = $typesimpotencetreatmentid;
    $myImpotencetreatmentsuppliersave->saveid = $saveId;
    $myImpotencetreatmentsuppliersave->supplierid = $supplierid;
    $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersavetype = $savedailychangeType;
    $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersavebefore = $savedailysaveBefore;
    $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersavetamount = $savedailychangeAmount;
    $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersaveafter = $savedailysaveAfter;
    $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersavecomment = $note;
    $myImpotencetreatmentsuppliersave->conditions = 0;
    $myImpotencetreatmentsuppliersave->impotencetreatmentsuppliersavedate = date("Y-m-d H:i:s");
    $myImpotencetreatmentsuppliersave->userid = $_SESSION['userid'];
    $myImpotencetreatmentsuppliersave->tablename = "settlementsaveController.php";
    $impotencetreatmentsuppliersaveId = $myImpotencetreatmentsuppliersaveRecord->insert($myImpotencetreatmentsuppliersave);




    $saveValuebeforeValid = 1;

    if (isset($saveId) && !empty($saveId)) {

        $supplierdata = $supplierDAO->load($supplierid);
        $debtBefore = $supplierdata->suppliercurrentDebt;
        if ($savedailychangeType == 1) {
            $debtAfter = $debtBefore + $savedailychangeAmount;
            $supplierdebtchangetype = 0;
            $processname = "اضافة معالجة عجز";
            $texts = "اضافة معالجة عج ";
        } else {
            $debtAfter = $debtBefore - $savedailychangeAmount;
            $processname = " خصم معالجة عجز ";
            $texts = " خصم معالجة عجز ";
            $supplierdebtchangetype = 1;
        }


        $supplierdebtchangemodelid = $_POST['voucher'];

        $supplierDeptChange->comment = $note;
        $supplierDeptChange->processname = $processname . " / " . $note;
        $supplierDeptChange->supplierdebtchangeafter = $debtAfter;
        $supplierDeptChange->supplierdebtchangeamount = $savedailychangeAmount;
        $supplierDeptChange->supplierdebtchangebefore = $debtBefore;
        $supplierDeptChange->supplierdebtchangedate = date('Y-m-d');
        $supplierDeptChange->supplierdebtchangemodelid = $supplierdebtchangemodelid;
        $supplierDeptChange->supplierdebtchangetype = $supplierdebtchangetype;
        $supplierDeptChange->tablename = "supplierPayedDeptController.php";
        $supplierDeptChange->userid = $_SESSION['userid'];
        $supplierDeptChange->supplierid = $supplierid;
        $supplierDeptChange->dailyentryid = 0;
        $supplierDeptChange->saveid = $saveId;
        $supplierDeptChange->costcenterid = $costcenterid;

        //Insert
        $supplierDeptChangeId = $supplierDeptChangeDAO->insert($supplierDeptChange);
        if (isset($supplierDeptChangeId)) {
            //update current dept in supplier tbl
            $supplier->suppliercurrentDebt = $debtAfter;
            $supplier->userid = $_SESSION['userid'];
            $supplier->supplierdate = date('Y-m-d');
            $supplier->supplierid = $supplierid;
            $supplierExt->updatedept($supplier);

            if (count($valueData) > 0) {
                $saveId = $valueData[0];
                $saveValuebefore = $valueData[1];
                $saveValueafter = $valueData[2];

                //insert into savedaily tbl
                insertSavedaily($saveValuebefore, $payedDept, 1, $saveId, $texts, $supplierDeptChangeId, $saveValueafter, "supplierPayedDeptController.php");
            }
        }

        $supName = $supplierdata->suppliername;
        $dailyEntry->entryComment = $texts . ' ( ' . $supName . ' ) ';
        $dailyEntry->fromFlag = 1;

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

        if ($oldSupplier->treeId > 0) {
            $treeId = $oldSupplier->treeId;
        } else {
            $supplierTypeForTree = 0;
            if ($supplierTypeForTree == 0)
                $parent = 81;
            elseif ($supplierTypeForTree == 1)
                $parent = 87;

            $treeId = addTreeElement($oldSupplier->suppliername, $parent, 1, 0, 1, '', $oldSupplier->suppliercurrentDebt, 0);
        }
        $dailyEntryDebtor->accountstreeid = $treeId;


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

        $dataSave = $mySaveRecord->load($saveId);

        if ($dataSave->treeId > 0) {
            $idTreeSave = $dataSave->treeId;
        } else {
            $idTreeSave = addTreeElement($dataSave->savename, 40, 3, 0, 1, '', $dataSave->savecurrentvalue, 0);
        }
        $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->saveid = $rowData->saveid;
        $supplierDeptChange->dailyentryid = $did;

        $supplierDeptChangeDAO->update($supplierDeptChange);
    }




    if ($savedailychangeAmount > 0 && $savedailychangeType == 1) {

        //get saveValue before and saveValue after mins changeAmount
        $saveData = getSaveValueAndMins($saveId, $savedailychangeAmount);
        $saveId = $saveData[0];
        $saveValuebefore = $saveData[1];
        $saveValueafter = $saveData[2];

        //update saveFrom value after add settlement
        updateSave($saveId, $saveValueafter);

        //insert into savedaily tbl
        $savedailyId = insertSavedaily($saveValuebefore, $savedailychangeAmount, 1, $saveId, "تسوية خزنة بالنقص", -1, $saveValueafter, "settlementsaveController.php", $note);


        //update savedailymodelid
        updateSavedailyModelId($savedailyId, $savedailyId);
    } elseif ($savedailychangeAmount > 0 && $savedailychangeType == 0) {
        //get saveValue before and saveValue after Plus changeAmount
        $saveData = getSaveValueAndPlus($saveId, $savedailychangeAmount);
        $saveId = $saveData[0];
        $saveValuebefore = $saveData[1];
        $saveValueafter = $saveData[2];

        //update saveTo value after add settlement
        updateSave($saveId, $saveValueafter);

        //insert into savedaily tbl
        $savedailyId = insertSavedaily($saveValuebefore, $savedailychangeAmount, 0, $saveId, "تسوية خزنة بالإضافة", -1, $saveValueafter, "settlementsaveController.php", $note);

        //update savedailymodelid
        updateSavedailyModelId($savedailyId, $savedailyId);
    }

    // اضافة
    if ($savedailychangeType == 0) {


        $dailyEntry->dDateTime = date('Y-m-d H:i:s');
        $dailyEntry->entryComment = 'اضافة معالجة عجز ( بالاضافة )';

        // الخزنة
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $savedailychangeAmount;
        //save session
        //$saveid = $_SESSION['saveid'];
        $dataSave = $mySaveRecord->load($saveId);

        $idTreeSave = $dataSave->treeId;

        $dailyEntryDebtor->accountstreeid = $idTreeSave;

        // عجز وزيادة الخزينة
        $dailyEntryCreditorArray = array();

        $dailyEntryCreditor->value = $savedailychangeAmount;
        $dailyEntryCreditor->accountstreeid = 41;


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

        insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
    } else {

        $dailyEntry->dDateTime = date('Y-m-d H:i:s');
        $dailyEntry->entryComment = 'اضافة معالجة عجز ( بالخصم )';

        // عجز وزيادة الخزينة
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $savedailychangeAmount;
        $dailyEntryDebtor->accountstreeid = 41;

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

        $idTreeSave = $dataSave->treeId;

        $dailyEntryCreditor->accountstreeid = $idTreeSave;
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

        $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
        
        if ($returnedData[0] == 1) {
            R::exec('update impotencetreatmentsuppliersave set dailyentryid = ' . $returnedData[1] . ' where impotencetreatmentsuppliersaveid = ' . $impotencetreatmentsuppliersaveId);
        }
    }
    return $saveValuebeforeValid;
}

// function showAll() {
//     //to use the variable out side the funcion
//     global $mySavedailyEx;
//     global $mySaveRecord;
//     $saveId = $_REQUEST['saveid'];
//     $supplierid = $_REQUEST['supplierid'];
//     $typesimpotencetreatmentid = $_REQUEST['typesimpotencetreatmentid'];
//     $startDate = $_REQUEST['from'];
//     $endDate = $_REQUEST['to'];
//     global $smarty;
//     global $queryString;
//     $queryString = ' ';
//     $message = "";
//     if ((isset($saveId) && $saveId != '-1')) {
//         $mysavedata = $mySaveRecord->load($saveId);
//         $message = $message . '<br>' . "اسم الخزنه  " . $mysavedata->savename;
//         $queryString .= ' savedaily.saveid = ' . $saveId . ' AND';
//     }
//     if (!empty($startDate) && !empty($endDate)) {
//         $message = $message . '<br>' . "من تاريخ   " . $startDate . "  الى " . $endDate;
//         $smarty->assign('message', $message);
//         $queryString .= ' savedaily.savedailydate >= "' . $startDate . '" AND savedaily.savedailydate <= "' . $endDate . '" AND';
//         //	$sumValue=sumCredit();
//         //print_r($sumValue);
//     } elseif (empty($startDate) && empty($endDate) && !isset($saveId) && $saveId = '-1') {
//         $today = date("Y-m-d");
//         $message = $message . '<br>' . "من تاريخ   " . $today . "  الى " . $today;
//         $smarty->assign('message', $message);
//         $queryString .= ' date(savedaily.savedailydate) >= "' . $today . '" AND date(savedaily.savedailydate) <= "' . $today . '" AND';
//         //	$sumValue=sumCredit();
//         //print_r($sumValue);
//     } elseif (!empty($startDate) && empty($endDate) && $saveId = '-1') {
//         $message = $message . '<br>' . "من تاريخ   " . $startDate;
//         $smarty->assign('message', $message);
//         $queryString .= ' savedaily.savedailydate >= "' . $startDate . '"';
//     } elseif (empty($startDate) && !empty($endDate) && $saveId = '-1') {
//         $message = $message . '<br>' . "الى تاريخ   " . $endDate;
//         $smarty->assign('message', $message);
//         $queryString .= ' savedaily.savedailydate <= "' . $endDate . '"';
//     } elseif (!empty($startDate) && empty($endDate) && isset($saveId) && $saveId = '-1') {
//         $mysavedata = $mySaveRecord->load($saveId);
//         $message = $message . '<br>' . "اسم الخزنه  " . $mysavedata->savename;
//         $queryString .= ' savedaily.saveid = ' . $saveId . ' AND';
//         $message = $message . '<br>' . "من  تاريخ   " . $startDate;
//         $smarty->assign('message', $message);
//         $queryString .= ' savedaily.savedailydate >= "' . $startDate . '"';
//     } elseif (empty($startDate) && !empty($endDate) && isset($saveId) && $saveId = '-1') {
//         $mysavedata = $mySaveRecord->load($saveId);
//         $message = $message . '<br>' . "اسم الخزنه  " . $mysavedata->savename;
//         $queryString .= ' savedaily.saveid = ' . $saveId . ' AND';
//         $message = $message . '<br>' . "الى تاريخ   " . $endDate;
//         $smarty->assign('message', $message);
//         $queryString .= ' savedaily.savedailydate <= "' . $endDate . '"';
//     } elseif (!empty($startDate) && !empty($endDate) && isset($saveId) && $saveId = '-1') {
//         $mysavedata = $mySaveRecord->load($saveId);
//         $message = $message . '<br>' . "اسم الخزنه  " . $mysavedata->savename;
//         $queryString .= ' savedaily.saveid = ' . $saveId . ' AND';
//         $message = $message . '<br>' . "من تاريخ   " . $startDate . "  الى " . $endDate;
//         $smarty->assign('message', $message);
//         $queryString .= ' date(savedaily.savedailydate) >= "' . $startDate . '" AND date(savedaily.savedailydate) <= "' . $endDate . '" AND';
//         //	$sumValue=sumCredit();
//         //print_r($sumValue);
//     }
//     $smarty->assign("message", $message);
//     $arr = explode(' ', $queryString);
//     //print_r($arr);
//     if (isset($arr) && count($arr) > 0) {
//         $lastWord = end($arr);
//         if ($lastWord == 'AND') {//remove it
//             array_pop($arr);
//             //form the string again
//             $queryString = implode(' ', $arr);
//         }
//         if ($lastWord == 'WHERE') {//remove it
//             array_pop($arr);
//             //form the string again
//             $queryString = implode(' ', $arr);
//         }
//         //print("<br>queryString: ".$queryString."<br>");
//     }
//     //$savedailyData=$mySavedailyEx->queryWithTablename("settlementsaveController.php");
//     $savedailyData = $mySavedailyEx->querybyqueryString($queryString);
//     $smarty->assign("savedailyData", $savedailyData);
//     //return $savedailyData;
// }
//show by date
function showByDate($startDate, $endDate)
{
    //to use the variable out side the funcion
    global $mySavedailyEx;

    $savedailyData = $mySavedailyEx->queryWithTablenameAndDate($startDate, $endDate, "settlementsaveController.php");

    return $savedailyData;
}

//show by saveid
function showBySaveId($SaveId)
{
    //to use the variable out side the funcion
    global $mySavedailyEx;

    $savedailyData = $mySavedailyEx->queryWithTablenameAndSave($SaveId, "settlementsaveController.php");

    return $savedailyData;
}

function loadSaveDaily($savedailyid)
{

    //to use the variable out side the funcion
    global $mySavedailyRecord;


    $loadData = $mySavedailyRecord->load($savedailyid);

    return $loadData;
}

// get savecurrentvalue from save tbl
function getSaveValueBefore($saveid)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

    $saveData = $mySaveRecord->load($saveid);
    $saveValuebefore = $saveData->savecurrentvalue;

    return $saveValuebefore;
}

// get initialvalue and plus from save tbl
function getSaveValueAndPlus($saveid, $savevaluechanged)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

    $saveData = $mySaveRecord->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore + $savevaluechanged;

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

// get initialvalue and mins from save tbl
function getSaveValueAndMins($saveid, $savevaluechanged)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveRecord;

    $saveData = $mySaveRecord->load($saveid);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore - $savevaluechanged;

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

// update in Save tbl
function updateSave($saveid, $savevalueafter)
{

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveEx;

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

    $mySaveEx->updateSaveValue($mySave);
}

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

    //to use the variable out side the funcion
    global $mySavedaily;
    global $mySavedailyRecord;

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

    $savedailyId = $mySavedailyRecord->insert($mySavedaily);

    return $savedailyId;
}

// insert in Savedaily tbl
function updateSavedailyModelId($savedailyid, $savedailymodelid)
{

    //to use the variable out side the funcion
    global $mySavedaily;
    global $mySavedailyEx;

    //insert in Savedaily tbl
    $mySavedaily->savedailyid = $savedailyid;
    $mySavedaily->savedailymodelid = $savedailymodelid;


    $mySavedailyEx->updateSavedailymodelid($mySavedaily);
}
