<?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");
//Client
require_once('../models/dao/ClientDAO.class.php');
require_once('../models/dto/Client.class.php');
require_once('../models/mysql/ClientMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientMySqlExtDAO.class.php');

//Clientdebtchange
require_once('../models/dao/ClientdebtchangeDAO.class.php');
require_once('../models/dto/Clientdebtchange.class.php');
require_once('../models/mysql/ClientdebtchangeMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientdebtchangeMySqlExtDAO.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 :- clientDeficitController

  OPERTATION in Controller

  1- display add form
  2- add in clientdebtchange tbl (subtracting or adding client debt)
  3- update client dept in client tbl
  ======================== */

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

//here goes the instances and general variables
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();
//Clientdebtchange
$clientDeptChange = new Clientdebtchange();
$clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();

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

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

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

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

    $clientsData = getClients(); //undeleted clients
    $smarty->assign("clientsData", $clientsData);

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

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

    liveBackupComment("-- clientDeficitController add - with clientid =" . $_POST["clientid"]);
    //Transaction
    $mytransactions = new Transaction();
    try {
        $id = add();

        $mytransactions->commit();
        header("location:?do=sucess");
    } catch (Exception $e) {
        // print_r($e);
        $mytransactions->rollback();
        header("location:?do=error");
    }
    liveBackupComment("-- clientDeficitController add end- with clientid =" . $_POST["clientid"] . " ,id=$id");
} elseif ($do == "show") {
    include_once("../public/authentication.php");

    $startDate = $_REQUEST['from'];
    $endDate = $_REQUEST['to'];
    $clientid = $_REQUEST['clientid'];

    if ($startDate == NULL && $endDate == NULL && $clientid == NULL) {
        $startDate = $endDate = date('Y-m-d');
    }


    if (!empty($clientid)) {
        $clientData = $clientDAO->load($clientid);
    }
    $queryString = '';
    if (isset($clientid) && $clientid != -1) {
        if ($clientid != -2) {

            $message = ' <br/> اسم العميل: ' . $clientData->clientname . '';
            $smarty->assign("message", $message);
            $queryString = $queryString . 'AND clientdebtchange.clientid = ' . $clientid . '';

            show($queryString);
        } else {

            show($queryString);
        }
    }

    if (isset($startDate) && isset($endDate) && $startDate != "" && $endDate != "") {
        $message = "التاريخ: من: " . $startDate . " إلى: " . $endDate;
        $smarty->assign("message", $message);
        $queryString = $queryString . ' AND DATE(clientdebtchange.clientdebtchangedate)
                    >=  "' . $startDate . '"  AND  DATE(clientdebtchange.clientdebtchangedate) <= "' . $endDate . '"';
        show($queryString);
    } elseif (isset($startDate) && $startDate != "") {
        $message = "التاريخ: من: " . $startDate . '';
        $smarty->assign("message", $message);
        $queryString = $queryString . ' AND DATE(clientdebtchange.clientdebtchangedate)
                     > "' . $startDate . '"';

        show($queryString);
    } elseif (isset($endDate) && $endDate != "") {
        $message = "التاريخ: إلى: " . $endDate . '';
        $smarty->assign("message", $message);
        $queryString = $queryString . ' AND DATE(clientdebtchange.clientdebtchangedate)
                     < "' . $endDate . '"';

        show($queryString);
    }

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

    $clientsData = getClients(); //undeleted clients
    $smarty->assign("clientsData", $clientsData);
    $smarty->display("clientDeficitview/show.html");
} elseif ($do == "editprint") {
    include_once("../public/authentication.php");

    $clientdebtchangeId = $_GET['id'];

    $clientdebtchangeData = edit($clientdebtchangeId);
    $smarty->assign("clientdebtchangeData", $clientdebtchangeData);

    $clientsData = getClients(); //undeleted clients
    $smarty->assign("clientsData", $clientsData);

    $smarty->display("clientDeficitview/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("customValidation", 1);
//here the global templates
$smarty->display("footer.html");

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

function getClients() {
    global $clientDAO;
    $clientsData = $clientDAO->queryAll();
    return $clientsData;
}

// add in clientdebtchange tbl
function add() {
    global $clientExt;
    global $clientDAO;
    global $client;
    global $clientDeptChange;
    global $clientDeptChangeDAO;
    global $today;


    //tree
    global $accountsTreeDAO;
    global $accountsTree;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

    //Dailyentrycreditor دائن
    global $dailyEntryCreditor;
    global $dailyEntryCreditorDAO;

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor;
    global $dailyEntryDebtorDAO;

    $clientid = $_POST["clientid"];
    //$debtbefore = $_POST["clientdebtchangebefore"];
    $debtchangetype = $_POST["clientdebtchangetype"];
    $debtamount = $_POST["clientdebtchangeamount"];
    $comment = $_POST["comment"];

    $clientdataSP = getClientDataFromClientInUseSP($clientid);
    $client = $clientDAO->load($clientid);
    $debtbefore = $clientdataSP->clientdebt;

    $clientDeptChange->comment = $comment;
    if (isset($debtchangetype) && $debtchangetype == 1) {
        $clientDeptChange->processname = "تسوية عجز عميل بالخصم";
        $debtAfter = $debtbefore - $debtamount;
    } elseif (isset($debtchangetype) && $debtchangetype == 0) {
        $clientDeptChange->processname = "تسوية عجز عميل بالزيادة";
        $debtAfter = $debtbefore + $debtamount;
    }



    $clientDeptChange->clientdebtchangeafter = $debtAfter;
    $clientDeptChange->clientdebtchangeamount = $debtamount;
    $clientDeptChange->totalOperationCost = $debtamount;
    $clientDeptChange->clientdebtchangebefore = $debtbefore;
    $clientDeptChange->clientdebtchangedate = date('Y-m-d H:i:s');
    $clientDeptChange->clientdebtchangemodelid = -1;
    $clientDeptChange->clientdebtchangetype = $debtchangetype;
    $clientDeptChange->tablename = "clientDeficitController.php";
    $clientDeptChange->userid = $_SESSION['userid'];
    $clientDeptChange->clientid = $clientid;
    $clientDeptChange->dailyentryid = 0;



    //Insert
    $clientdebtchangeId = $clientDeptChangeDAO->insert($clientDeptChange);

    //update current dept in client tbl
    $client->clientdebt = $debtAfter;
    $client->userid = $_SESSION['userid'];
    $client->clientdate = $today;
    $client->clientid = $clientid;

    $clientExt->updatedept($client);
    markClientAsNOTInUse($clientid);

    if ($debtchangetype == 0) {
        $clientData = $clientDAO->load($clientid);

        $dailyEntry->entryComment = 'تم اضافة معالجة عجز للعميل ' . $clientData->clientname . '(تسوية بالاضافة)';

        //////////////// start العميل

        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $debtamount;

        $dataClient = $clientDAO->load($clientid);

        $idTreeClient = $dataClient->treeId;
        $dailyEntryDebtor->accountstreeid = $idTreeClient;

        //end  العميل
        //معالجة عجز عملاء

        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $debtamount;
        $dailyEntryCreditor->accountstreeid = 146; //ايرادات الخصم المكتسب

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

        insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
    } else {
        $clientData = $clientDAO->load($clientid);

        $dailyEntry->entryComment = 'تم اضافة معالجة عجز للعميل ' . $clientData->clientname . '(تسوية بالخصم)';

        ////////////////  معالجة عجز عملاء

        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $debtamount;
        $dailyEntryDebtor->accountstreeid = 398; //خصم مسموح به
        ////////////////  العميل

        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $debtamount;

        $dataClient = $clientDAO->load($clientid);

        $idTreeClient = $dataClient->treeId;
        $dailyEntryCreditor->accountstreeid = $idTreeClient;

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

        insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
    }
    return $clientdebtchangeId;
}

function show($queryString) {
    global $clientDeptChangeExt;
    global $smarty;



    $shownData = $clientDeptChangeExt->queryWithQueryString($queryString, "clientDeficitController.php");

    //$shownData = $clientDeptChangeExt->queryWithTableName($startDate, $endDate, "clientDeficitController.php");
    // assign db results to the template
    $smarty->assign('shownData', $shownData);
}

function edit($clientdebtchangeid) {
    global $clientDeptChangeDAO;

    $clientdebtchangeData = $clientDeptChangeDAO->load($clientdebtchangeid);

    return $clientdebtchangeData;
}

function getClientDataFromClientInUseSP($clientid) {
    global $clientExt;
    global $clientDAO;

    if ($clientid == 1) {
        $client_data = $clientDAO->load($clientid);
    } elseif ($clientid > 1) {
        $noOfTries = 0;
        $client_data = $clientExt->callClientInUseSP($clientid);
        while ($client_data->clientdebt == '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 client=$clientid with redbean");
                R::exec('UPDATE client SET  inUse = 0 where clientid = ' . $clientid);
            }
            $client_data = $clientExt->callClientInUseSP($clientid);
        }
    }
    return $client_data;
}

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

function liveBackupComment($txt) {
    $myfile = fopen("backup/" . date("Y-m-d") . ".txt", "a+") or die("Unable to open file!");
    $toWrite = "\r\n-- ----------------------------------------------------------------------------------------------------\r\n";
    $toWrite .= $txt;
    $toWrite .= "\r\n-- ----------------------------------------------------------------------------------------------------\r\n\r\n";
    fwrite($myfile, $toWrite);
}

?>