<?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");

//here the db files that include in the file
include("../public/include_dao.php");


//MFinishingpayed
require_once('../models/dao/MFinishingpayedDAO.class.php');
require_once('../models/dto/MFinishingpayed.class.php');
require_once('../models/mysql/MFinishingpayedMySqlDAO.class.php');
require_once('../models/mysql/ext/MFinishingpayedMySqlExtDAO.class.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');

//MComreceipt
require_once('../models/dao/MComreceiptDAO.class.php');
require_once('../models/dto/MComreceipt.class.php');
require_once('../models/mysql/MComreceiptMySqlDAO.class.php');
require_once('../models/mysql/ext/MComreceiptMySqlExtDAO.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 :- supplierPayedDeptController

  OPERTATION in Controller

  1- display add form
  2- add row in supplierdebtchange tbl
  3- update supplier dept in supplier tbl
  ======================== */
$smarty->assign("userid", $_SESSION['userid']);
$smarty->assign("username", $_SESSION['username']);
//here the global templates
$smarty->display("header.html");

//here goes the instances and general variables
//MFinishingpayed
$MFinishingpayed = new MFinishingpayed();
$MFinishingpayedDAO = new MFinishingpayedMySqlDAO();
$MFinishingpayedEX = new MFinishingpayedMySqlExtDAO();

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

//Clientdebtchange
$Clientdebtchange = new Clientdebtchange();
$ClientdebtchangeDAO = new ClientdebtchangeMySqlDAO();
$ClientdebtchangeEX = new ClientdebtchangeMySqlExtDAO();

//Client
$Client = new Client();
$ClientDAO = new ClientMySqlDAO();
$ClientEX = new ClientMySqlExtDAO();

//MComreceipt
$MComreceipt = new MComreceipt();
$MComreceiptDAO = new MComreceiptMySqlDAO();
$MComreceiptEx = new MComreceiptMySqlExtDAO();

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

    //get all client
    $allclient = getclient();
    $smarty->assign("allclient", $allclient);

    $smarty->assign("title1", 'صيانه');
    $smarty->assign("title2", 'الاستقبال');
    $smarty->assign("title3", 'اضافة ايصال استلام');
    $smarty->assign("link", 'clientController.php?do=show');
    $smarty->display("maintennanceHeader.html");

    $smarty->display("receiptview/add.html");
} elseif ($do == "add") {
    include_once("../public/authentication.php");
    //add();
    try {
        add();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "show") {
    include_once("../public/authentication.php");

    $clientsData = getclient();
    $smarty->assign("clientsData", $clientsData);

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

    if ((!empty($clientname)) || (!empty($startDate) && !empty($endDate))) {
        $message = " اسم العميل " . $clientname . "التاريخ: من: " . $startDate . " إلى: " . $endDate;
        $smarty->assign("message", $message);

        show($clientname, $startDate, $endDate);
    } else {
        //showall();
        $today = date("Y-m-d");
        show($clientname, $today, $today);
    }

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

    $smarty->assign("title1", 'صيانه');
    $smarty->assign("title2", 'الاستقبال');
    $smarty->assign("title3", 'تقرير استلام');
    $smarty->assign("link", 'clientPayedDeptController.php?do=show');
    $smarty->display("maintennanceHeader.html");

    $smarty->display("receiptview/show.html");
} elseif ($do == "edit") {

    include_once("../public/authentication.php");

    //get all client
    $allclient = getclient();
    $smarty->assign("allclient", $allclient);

    $alldata = getreceiptdata();
    $smarty->assign("alldata", $alldata);

    $clientdebtchangeId = $_GET['id'];

    $clientdebtchangeData = edit($clientdebtchangeId);

    $discount = $clientdebtchangeData->discount;
    $debtafter = $clientdebtchangeData->clientdebtchangeafter;

    $debtremain = $discount + $debtafter;
    $smarty->assign("clientdebtchangeData", $clientdebtchangeData);
    $smarty->assign("debtremain", $debtremain);


    $smarty->assign("title1", 'صيانه');
    $smarty->assign("title2", 'الاستقبال');
    $smarty->assign("title3", 'تعديل  ايصال استلام');
    $smarty->assign("link", 'clientController.php?do=show');
    $smarty->display("maintennanceHeader.html");


    $smarty->display("receiptview/edit.html");
} elseif ($do == "editprint") {

    include_once("../public/authentication.php");

    $allclient = getclient();
    $smarty->assign("allclient", $allclient);


    $alldata = getreceiptdata();
    $smarty->assign("alldata", $alldata);

    $clientdebtchangeId = $_GET['id'];

    $clientdebtchangeData = edit($clientdebtchangeId);

    $discount = $clientdebtchangeData->discount;
    $debtafter = $clientdebtchangeData->clientdebtchangeafter;

    $debtremain = $discount + $debtafter;
    $smarty->assign("clientdebtchangeData", $clientdebtchangeData);
    $smarty->assign("debtremain", $debtremain);

    $smarty->display("receiptview/editprint.html");
} elseif ($do == "update") {
    include_once("../public/authentication.php");
    //update();
    try {
        update();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == "delete") {
    include_once("../public/authentication.php");
    //delete();
    try {
        delete();
        header("location:?do=sucess");
    } catch (Exception $e) {
        header("location:?do=error");
    }
} elseif ($do == 'addrecept') {
    //here the permssion check
    include_once("../public/authentication.php");

    $receptdata = $MComreceiptEx->queryAllMComreceipt();
    $ID = $receptdata->id;

    $id = $ID + 1;


    $alldata = getreceiptdata();
    $smarty->assign("alldata", $alldata);

    $receptid = $_GET['receptid'];
    $smarty->assign("receptid", $receptid);

    $allrecept = $MComreceiptDAO->load($receptid);
    $clintid = $allrecept->clientid;
    $shipcost = $allrecept->shipcost;
    $smarty->assign("allrecept", $allrecept);

    $totalclientdata = $ClientDAO->load($clintid);
    $totaldebt = $totalclientdata->clientdebt;
    $smarty->assign("totaldebt", $totaldebt);


    //get all client
    $allclient = getclient();
    $smarty->assign("allclient", $allclient);

    $smarty->assign("title1", 'صيانه');
    $smarty->assign("title2", 'الاستقبال');
    $smarty->assign("title3", 'اضافة ايصال استلام');
    $smarty->assign("link", 'clientController.php?do=show');
    $smarty->display("maintennanceHeader.html");

    $smarty->display("receiptview/addrecept.html");
} 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("customreceipt", 1);
$smarty->assign("GeneralSearch", 1);
$smarty->display("footer.html");

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

function getclient() {
    global $ClientDAO;

    $allclient = $ClientDAO->queryByCondition(0);

    return $allclient;
}

function getreceiptdata() {
    global $MComreceiptDAO;

    $alldata = $MComreceiptDAO->queryByDel(0);


    return $alldata;
}

function add() {
    global $MFinishingpayed;
    global $MFinishingpayedDAO;
    global $MMaintenancereceipt;
    global $MMaintenancereceiptDAO;
    global $Clientdebtchange;
    global $ClientdebtchangeDAO;
    global $Client;
    global $ClientEX;


    //variable
    $clientid = $_POST['clientid'];
    $totaldebt = $_POST['totaldebt'];
    $payed = $_POST['payed'];
    //$debtafter = $_POST['debtafter'];
    $discount = $_POST['discount'];
    //$remain = $_POST['remain'];
    $textDetails = $_POST['textDetails'];
    $receiptid = $_POST['receiptid'];

    if ($payed) {
        if ($payed <= $totaldebt) {
            $debtafter = $totaldebt - $payed;
            $Clientdebtchange->clientdebtchangeafter = $debtafter;
            $Client->clientdebt = $debtafter;
        }
    } else {
        $Clientdebtchange->clientdebtchangeafter = $totaldebt;
        $Client->clientdebt = $totaldebt;
    }


    if ($discount) {
        if ($discount <= $debtafter) {
            $remain = $debtafter - $discount;
        }
        $Clientdebtchange->clientdebtchangeafter = $remain;
        $Client->clientdebt = $remain;
        $Clientdebtchange->discount = $discount;
    } else {
        if ($payed) {
            if ($payed <= $totaldebt) {
                $debtafter = $totaldebt - $payed;
                $Clientdebtchange->clientdebtchangeafter = $debtafter;
                $Client->clientdebt = $debtafter;
            }
        } else {
            $Clientdebtchange->clientdebtchangeafter = $totaldebt;
            $Client->clientdebt = $totaldebt;
        }
    }

    if ($receiptid == -1) {
        $Clientdebtchange->reciptid = 0;
    } else {
        $Clientdebtchange->reciptid = $receiptid;
    }

    if (isset($clientid) && $clientid != '-1') {
        //insert into clientdebtchange
        $Clientdebtchange->clientid = $clientid;
        $Clientdebtchange->clientdebtchangedate = date("Y-m-d");
        $Clientdebtchange->clientdebtchangeamount = $payed;
        $Clientdebtchange->clientdebtchangebefore = $totaldebt;
        $Clientdebtchange->userid = $_SESSION['userid'];
        $Clientdebtchange->processname = "اضافه ايصال استلام";
        $Clientdebtchange->tablename = "receiptController.php";
        $Clientdebtchange->clientdebtchangemodelid = -1;
        $Clientdebtchange->clientdebtchangetype = 1;
        $Clientdebtchange->comment = $textDetails;
        $Clientdebtchange->totalOperationCost = $payed;


        $ClientdebtchangeId = $ClientdebtchangeDAO->insert($Clientdebtchange);

        //update client
        $Client->userid = $_SESSION['userid'];
        $Client->clientdate = date("Y-m-d");
        $Client->clientid = $clientid;

        $ClientEX->updatedept($Client);


        $MFinishingpayed->clientId = $clientid;
        $MFinishingpayed->finishingPayedDate = date("Y-m-d");
        $MFinishingpayed->clientDebtChangeId = $ClientdebtchangeId;
        $MFinishingpayed->payed = $payed;
        $MFinishingpayed->finishingType = 0;
        $MFinishingpayed->remain = 0;
        $MFinishingpayed->del = 0;
        $MFinishingpayed->userId = $_SESSION['userid'];
        $MFinishingpayed->branchId = $_SESSION['branchId'];

        $MFinishingpayedDAO->insert($MFinishingpayed);
    }
}

//show
function show($clientname, $startDate, $endDate) {
    global $ClientdebtchangeEX;
    global $ClientDAO;
    global $smarty;
    global $queryString;
    $queryString = ' WHERE';

    if (isset($clientname) && $clientname != '-1' && $clientname != "all") {
        $clientnamedata = $ClientDAO->load($clientname);
        $message = " اسم العميل " . $clientnamedata->clientname;
        $smarty->assign('message', $message);

        $queryString .= ' clientdebtchange.clientid =' . $clientname . ' AND';
    }
    if (isset($clientname) && $clientname != "-1" && $clientname == "all") {
        $message = " كل العملاء";
        $smarty->assign('message', $message);
        $queryString .= ' clientdebtchange.clientid  > 0  AND';
    }

    if (!empty($startDate) && !empty($endDate)) {
        if ($startDate == $endDate) {
            $message = " تقرير عجز عميل لليوم: " . $startDate;
            $smarty->assign('message', $message);
        } else {

            $message = " تقرير عجز عميل من تاريخ " . $startDate . "  الى تاريخ" . $endDate;
            $smarty->assign('message', $message);
        }

        $queryString .= ' clientdebtchange.clientdebtchangedate >= "' . $startDate . '" AND clientdebtchange.clientdebtchangedate <= "' . $endDate . '" 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 = $ClientdebtchangeEX->search($queryString, "receiptController.php", $_SESSION['branchId']);


    $changeAmountSum = 0;
    foreach ($shownData as $clientdata) {

        $changeAmountSum1 +=$clientdata->clientdebtchangeamount;
        $changeAmountSum = round(($changeAmountSum1 * 2)) / 2;
    }

    $smarty->assign('changeAmountSum', $changeAmountSum);

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

//edit
function edit($clientdebtchangeid) {
    global $ClientdebtchangeEX;

    $clientdebtchangeData = $ClientdebtchangeEX->loadclient($clientdebtchangeid);

    return $clientdebtchangeData;
}

//update
function update() {
    global $MFinishingpayed;
    global $MFinishingpayedEX;
    global $MMaintenancereceipt;
    global $MMaintenancereceiptDAO;
    global $Clientdebtchange;
    global $ClientdebtchangeDAO;
    global $Client;
    global $ClientEX;
    global $ClientDAO;


    //variable
    $clientid = $_POST['clientid'];
    //$totaldebt = $_POST['totaldebt'];
    $payed = $_POST['payed'];
    //$debtafter = $_POST['debtafter'];
    $discount = $_POST['discount'];
    //$remain = $_POST['remain'];
    $textDetails = $_POST['textDetails'];
    $id = $_POST['clientdebtchangeid'];
    $finishingPayedId = $_POST['finishingpayedid'];
    $receiptid = $_POST['receiptid'];

    $Clientdebtchangedata = $ClientdebtchangeDAO->load($id);
    $changeamount = $Clientdebtchangedata->clientdebtchangeamount;
    $clientdiscount = $Clientdebtchangedata->discount;

    $clientvalue = $changeamount + $clientdiscount;

    if ($clientvalue > 0) {

        //get saveFromValue before and saveFromValue after mins transfermoneyValue
        $clientDatavalue = getdebtValueAndPlus($clientid, $clientvalue);
        $clientId = $clientDatavalue[0];
        $debtValuebefore = $clientDatavalue[1];
        $debtValueafter = $clientDatavalue[2];

        //update saveFrom value after add transfer
        $Client->clientdebt = $debtValueafter;
        $Client->userid = $_SESSION['userid'];
        $Client->clientdate = $clientDeptChangedate;
        $Client->clientid = $clientId;

        $ClientEX->updatedept($Client);
    }

    $alldata = $ClientDAO->load($clientid);
    $totaldebt = $alldata->clientdebt;
    if ($payed) {
        if ($payed <= $totaldebt) {
            $debtafter = $totaldebt - $payed;
            $Clientdebtchange->clientdebtchangeafter = $debtafter;
            $Client->clientdebt = $debtafter;
        }
    } else {
        $Clientdebtchange->clientdebtchangeafter = $totaldebt;
        $Client->clientdebt = $totaldebt;
    }


    if ($discount) {
        if ($discount <= $debtafter) {
            $remain = $debtafter - $discount;
        }
        $Clientdebtchange->clientdebtchangeafter = $remain;
        $Client->clientdebt = $remain;
    } else {
        if ($payed) {
            if ($payed <= $totaldebt) {
                //$debtafter = $totaldebt - $payed;
                $Clientdebtchange->clientdebtchangeafter = $debtafter;
                $Client->clientdebt = $debtafter;
            }
        } else {
            $Clientdebtchange->clientdebtchangeafter = $totaldebt;
            $Client->clientdebt = $totaldebt;
        }
    }

    if ($receiptid == -1) {
        $Clientdebtchange->reciptid = 0;
    } else {
        $Clientdebtchange->reciptid = $receiptid;
    }

    if (isset($clientid) && $clientid != '-1') {
        //insert into clientdebtchange
        $Clientdebtchange->clientid = $clientid;
        $Clientdebtchange->clientdebtchangedate = date("Y-m-d");
        $Clientdebtchange->clientdebtchangeamount = $payed;
        $Clientdebtchange->clientdebtchangebefore = $totaldebt;
        $Clientdebtchange->userid = $_SESSION['userid'];
        $Clientdebtchange->processname = "تعديل ايصال استلام";
        $Clientdebtchange->tablename = "receiptController.php";
        $Clientdebtchange->clientdebtchangemodelid = -1;
        $Clientdebtchange->clientdebtchangetype = 1;
        $Clientdebtchange->comment = $textDetails;
        $Clientdebtchange->discount = $discount;
        $Clientdebtchange->totalOperationCost = $payed;
        $Clientdebtchange->clientdebtchangeid = $id;

        $ClientdebtchangeDAO->update($Clientdebtchange);

        //update client
        $Client->userid = $_SESSION['userid'];
        $Client->clientdate = date("Y-m-d");
        $Client->clientid = $clientid;

        $ClientEX->updatedept($Client);


        $MFinishingpayed->payed = $payed;
        $MFinishingpayed->finishingPayedDate = date("Y-m-d");
        $MFinishingpayed->branchId = $_SESSION['branchId'];
        $MFinishingpayed->userId = $_SESSION['userid'];
        $MFinishingpayed->finishingPayedId = $finishingPayedId;

        $MFinishingpayedEX->updatepayed($MFinishingpayed);
    }
}

//delete
function delete() {
    global $MFinishingpayed;
    global $MFinishingpayedEX;
    global $MMaintenancereceipt;
    global $MMaintenancereceiptDAO;
    global $Clientdebtchange;
    global $ClientdebtchangeDAO;
    global $Client;
    global $ClientEX;
    global $ClientDAO;


    //variable
    $clientid = $_GET['clientid'];
    $id = $_GET['id'];
    $finishingPayedId = $_GET['finishingPayedId'];

    $Clientdebtchangedata = $ClientdebtchangeDAO->load($id);
    $changeamount = $Clientdebtchangedata->clientdebtchangeamount;
    $clientdiscount = $Clientdebtchangedata->discount;


    $clientvalue = $changeamount + $clientdiscount;

    if ($clientvalue > 0) {

        //get saveFromValue before and saveFromValue after mins transfermoneyValue
        $clientDatavalue = getdebtValueAndPlus($clientid, $clientvalue);
        $clientId = $clientDatavalue[0];
        $debtValuebefore = $clientDatavalue[1];
        $debtValueafter = $clientDatavalue[2];

        //update saveFrom value after add transfer
        $Client->clientdebt = $debtValueafter;
        $Client->userid = $_SESSION['userid'];
        $Client->clientdate = $clientDeptChangedate;
        $Client->clientid = $clientId;

        $ClientEX->updatedept($Client);
    }
    // delete clientdebtchange
    $ClientdebtchangeDAO->delete($id);

    //update del MFinishingpayed
    $MFinishingpayed->del = 1;
    $MFinishingpayed->finishingPayedDate = date("Y-m-d");
    $MFinishingpayed->branchId = $_SESSION['branchId'];
    $MFinishingpayed->userId = $_SESSION['userid'];
    $MFinishingpayed->finishingPayedId = $finishingPayedId;

    $MFinishingpayedEX->updatecondition($MFinishingpayed);
}

//getdebtValueAndPlus
function getdebtValueAndPlus($clientid, $clientvalue) {

    //to use the variable out side the funcion
    global $Client;
    global $ClientDAO;

    $clientDatavalue = $ClientDAO->load($clientid);

    $clientId = $clientDatavalue->clientid;
    $debtValuebefore = $clientDatavalue->clientdebt;

    $debtValueafter = $debtValuebefore + $clientvalue;

    return array($clientId, $debtValuebefore, $debtValueafter);
}

?>