<?php

/////////////////////    تسوية عجز مورد
//the global file operation
include("../public/impOpreation.php");
include_once("dailyentryfun.php");

//global varable
global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file
include_once("../public/config.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');

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 :- supplierDeficitController

  OPERTATION in Controller

  1- display add form
  2- add in supplierdebtchange tbl (subtracting or adding supplier debt)
  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();
//Supplierdebtchange
$supplierDeptChange = new Supplierdebtchange();
$supplierDeptChangeDAO = new SupplierdebtchangeMySqlDAO();
$supplierDeptChangeExt = new SupplierdebtchangeMySqlExtDAO();

//Dailyentry
$dailyEntry = new Dailyentry();

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

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

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

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

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

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


    //here the smarty templates
    $smarty->assign("customSupplierDificit", 1);
    $smarty->display("supplierDeficitview/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");
    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");

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

    $supplierSearchData = getSuppliers();
    $smarty->assign("supplierSearchData", $supplierSearchData);

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

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

        showBySupplier($supplierId);
    } elseif (isset($startDate) && $startDate != "" && isset($endDate) && $endDate != "") {
        $message = "التاريخ: من: " . $startDate . " إلى: " . $endDate;
        $smarty->assign("message", $message);

        showByDate($startDate, $endDate);
    } else {
        $today_search = date("Y-m-d");
        //showAll();
        showByDate($today_search, $today_search);
    }

    $smarty->display("supplierDeficitview/show.html");
} elseif ($do == "editprint") {
    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("supplierDeficitview/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");
}
//here the global templates
$smarty->assign("customValidation", 1);
$smarty->display("footer.html");

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

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

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

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    //Transaction
    $mytransactions = new Transaction();
    try {

        $currentDate = date("Y-m-d H:i:s");

        $supplierid = $_POST["supplierid"];
//        $debtbefore = $_POST["supplierdebtchangebefore"];
        $debtchangetype = $_POST["supplierdebtchangetype"];
        $debtamount = $_POST["supplierdebtchangeamount"];
        $comment = $_POST["comment"];

        $currencyId = (isset($_POST['currencyId']) && !empty($_POST['currencyId'])) ? (int) $_POST['currencyId'] : 1;
        $cFactor = (isset($_POST['cFactor']) && !empty($_POST['cFactor'])) ? (float) $_POST['cFactor'] : 1;
        $debtamountCurr = (isset($_POST['debtamountCurr']) && !empty($_POST['debtamountCurr'])) ? (float) $_POST['debtamountCurr'] : $debtamount;
        

        // $supplier = $supplierDAO->load($supplierid);
        
        $supplier = getSupplierDataFromSupplierInUseSP($supplierid);
        $debtbefore = $supplier->suppliercurrentDebt;
        if (isset($debtchangetype) && $debtchangetype == 1) {
            $supplierDeptChange->processname = "تسوية عجز مورد بالخصم";
            $debtAfter = $debtbefore - $debtamount;
            //$type = 1;
        } else if (isset($debtchangetype) && $debtchangetype == 0) {
            $supplierDeptChange->processname = "تسوية عجز مورد بالزيادة";
            $debtAfter = $debtbefore + $debtamount;
            //$type = 0;
        }

        $supplierDeptChange->comment = $comment;
        $supplierDeptChange->supplierdebtchangeafter = $debtAfter;
        $supplierDeptChange->supplierdebtchangeamount = $debtamount;
        $supplierDeptChange->supplierdebtchangebefore = $debtbefore;
        $supplierDeptChange->supplierdebtchangedate = $currentDate;
        $supplierDeptChange->supplierdebtchangemodelid = -1;
        $supplierDeptChange->supplierdebtchangetype = $debtchangetype;
        $supplierDeptChange->tablename = "supplierDeficitController.php";
        $supplierDeptChange->userid = $_SESSION['userid'];
        $supplierDeptChange->currencyId = $currencyId;
        $supplierDeptChange->conversionFactor = $cFactor;
        $supplierDeptChange->payedInCurrency = $debtamount;
        $supplierDeptChange->supplierid = $supplierid;


        $loadSupplier = $supplierDAO->load($supplierid);

        $supplier->suppliername = $loadSupplier->suppliername;
        $supplier->supplieraddress = $loadSupplier->supplieraddress;
        $supplier->supplierphone = $loadSupplier->supplierphone;
        $supplier->supplierdetails = $loadSupplier->supplierdetails;
        $supplier->conditions = $loadSupplier->conditions;
        $supplier->suppliercurrentDebt = $debtAfter;
        $supplier->suppliercurrentDebtInCurrency = $debtAfter;
        $supplier->userid = $_SESSION['userid'];
        $supplier->supplierdate = $today;
        $supplier->supplierid = $supplierid;
        
        //update current dept in supplier tbl
        $supplierExt->updatedept($supplier);
        markSupplierAsNOTInUse($supplierid);

        $dailyEntryDebtorArray = array();
        $dailyEntryCreditorArray = array();

        $dailyEntry->dDateTime = date('Y-m-d H:i:s');

        $oldSupplier = $supplierDAO->load($supplierid);
        $treeId = $oldSupplier->treeId;

        if (isset($debtchangetype) && $debtchangetype == 1) {
            //من حساب الدائنون
            //الي حساب معالجة عجز موردين
            $dailyEntry->entryComment = "تسوية عجز مورد بالخصم";
            $dailyEntryDebtor->value = $debtamount;
            $dailyEntryDebtor->accountstreeid = $treeId;
            $dailyEntryCreditor->value = $debtamount;
            $dailyEntryCreditor->accountstreeid = 146; //ايرادات الخصم المكتسب
        } else if (isset($debtchangetype) && $debtchangetype == 0) {
            $dailyEntry->entryComment = "تسوية عجز مورد بالزيادة";
            //من معالجة عجز موردين
            //الي حساب الدائنون
            $dailyEntryDebtor->value = $debtamount;
            $dailyEntryDebtor->accountstreeid = 398; //خصم مسموح به
            $dailyEntryCreditor->value = $debtamount;
            $dailyEntryCreditor->accountstreeid = $treeId;
        }
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);




        //Insert
        $returnDaily = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
        $supplierDeptChange->dailyentryid = $returnDaily[1];

        $supplierDeptChangeId = $supplierDeptChangeDAO->insert($supplierDeptChange);
        $saveConversionFactor = 0;
        if (isset($supplierDeptChangeId)) {
            $loadSupplier = $supplierDAO->load($supplierid);
            $payedInSuppCurr = $debtamount;
            if ($loadSupplier->sullpierCurrencyid > 1) {
                if ($currencyId == $loadSupplier->sullpierCurrencyid) {
                    $payedInSuppCurr = $debtamountCurr;
                } else {
                    $conversionFactorSupp = R::getCell('select conversionFactor from currency where id=' . $loadSupplier->sullpierCurrencyid);
                    $payedInSuppCurr = $debtamount / $conversionFactorSupp;
                }

                if ($debtchangetype == 0) {
                    $supplier->suppliercurrentDebtInCurrency = $loadSupplier->suppliercurrentDebtInCurrency + $payedInSuppCurr;
                } else {
                    $supplier->suppliercurrentDebtInCurrency = $loadSupplier->suppliercurrentDebtInCurrency - $payedInSuppCurr;
                }
            }
            $supplierDeptChange->debtchangbeforeInSupplierCurrency = $loadSupplier->suppliercurrentDebtInCurrency;
            $supplierDeptChange->debtchangamountInSupplierCurrency = $payedInSuppCurr;
            $supplierDeptChange->debtchangafterInSupplierCurrency = $supplier->suppliercurrentDebtInCurrency;
            $supplierDeptChangeDAO->update($supplierDeptChange);
        }



        $mytransactions->commit();

        $message = 'تمت العملية بنجاح';
    } catch (Exception $ex) {
        $mytransactions->rollback($ex);
        $message = 'عفوا لقد حدث خطأ';
    }
}

function edit($supplierDeptChangeId) {
    global $supplierDeptChangeDAO;

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

// show the form
function showBySupplier($supplierId) {
    global $supplierDeptChangeExt;
    global $smarty;

    $supplierdebtchangeData = $supplierDeptChangeExt->queryWithSupplierIdAndTableName($supplierId, "supplierDeficitController.php");

    foreach ($supplierdebtchangeData as $supplierdebtchange) {
        $supplierdebtchange->supplierdebtchangedate = date('Y-m-d, g:i A', strtotime($supplierdebtchange->supplierdebtchangedate));
    }

    $smarty->assign('supplierdebtchangeData', $supplierdebtchangeData);
}

// show the form
function showByDate($startDate, $endDate) {
    global $supplierDeptChangeExt;

    global $smarty;

    $supplierdebtchangeData = $supplierDeptChangeExt->queryWithDateAndTableName($startDate, $endDate, "supplierDeficitController.php");


    foreach ($supplierdebtchangeData as $supplierdebtchange) {
        $supplierdebtchange->supplierdebtchangedate = date('Y-m-d, g:i A', strtotime($supplierdebtchange->supplierdebtchangedate));
    }

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

// show the form
function showAll() {
    global $supplierDeptChangeExt;

    global $smarty;

    $supplierdebtchangeData = $supplierDeptChangeExt->queryWithTableName("supplierDeficitController.php");

    foreach ($supplierdebtchangeData as $supplierdebtchange) {
        $supplierdebtchange->supplierdebtchangedate = date('Y-m-d, g:i A', strtotime($supplierdebtchange->supplierdebtchangedate));
    }

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

function getSupplierDataFromSupplierInUseSP($supplier) {
    global $supplierExt;
    global $supplierDAO;
    if ($supplier == 1) {
        $supplier_data = $supplierDAO->load($supplier);
    } elseif ($supplier > 1) {
        $noOfTries = 0;
        $supplier_data = $supplierExt->callSupplierInUseSP($supplier);
        while ($supplier_data->suppliercurrentDebt == 'in_use') {
            sleep(1);
            $noOfTries++;
            if ($noOfTries > 15) { // mean 15 sec as sleep is 1 sec her
                //markClientAsNOTInUse -- using redbeans to instantly execute in database as we are in transaction now "means affecting row is done @end of execution or comit"
                liveBackupComment("-- force free supplier=$supplier with redbean");
                R::exec('UPDATE supplier SET  inUse = 0 where supplierid = ' . $supplier);
            }
            $supplier_data = $supplierExt->callSupplierInUseSP($supplier);
        }
    }
    return $supplier_data;
}

function markSupplierAsNOTInUse($supplier) { //mark as not in use "free him to be able to change debt again"
    global $supplierExt;
    if ($supplier == 1) {
        //do no thing. we didnot mark it as in use at begining
    } else {
        $supplierExt->markSupplierAsNOTInUse($supplier);
    }
}
?>