<?php

//the global file operation
include("../public/impOpreation.php");
include("../library/class.upload.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");

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

//Bill
require_once('../models/dao/BillsDAO.class.php');
require_once('../models/dto/Bill.class.php');
require_once('../models/mysql/BillsMySqlDAO.class.php');
require_once('../models/mysql/ext/BillsMySqlExtDAO.class.php');


//Sellbill
require_once('../models/dao/SellbillDAO.class.php');
require_once('../models/dto/Sellbill.class.php');
require_once('../models/mysql/SellbillMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbillMySqlExtDAO.class.php');

require_once('../models/dao/ClientpaymentreceipttDAO.class.php');
require_once('../models/dto/Clientpaymentreceiptt.class.php');
require_once('../models/mysql/ClientpaymentreceipttMySqlDAO.class.php');
require_once('../models/mysql/ext/ClientpaymentreceipttMySqlExtDAO.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');

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


include_once("dailyentryfun.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 :- productCatController

  OPERTATION in Controller

  1-display add form
  2- add in productCat tble
  4-display sucess or error
  5-display show and delete
  6-delete from productCat tbl
  7-display edit
  8- update productCat 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();

//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();

//Sellbill
$mySellbill = new Sellbill();
$mySellbillRecord = new SellbillMySqlDAO();
$mySellbillEx = new SellbillMySqlExtDAO();

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

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

//Dailyentry
$dailyEntry = new Dailyentry();
$dailyEntryDAO = new DailyentryMySqlDAO();
$dailyEntryEX = new DailyentryMySqlExtDAO();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();
$dailyEntryCreditorDAO = new DailyentrycreditorMySqlDAO();
$dailyEntryCreditorEX = new DailyentrycreditorMySqlExtDAO();

$dailyEntryDebtor2 = new Dailyentrydebtor();
//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();
$dailyEntryDebtorDAO = new DailyentrydebtorMySqlDAO();
$dailyEntryDebtorEX = new DailyentrydebtorMySqlExtDAO();

//paymentnetworks
$paymentNetworks = new Paymentnetwork();
$paymentNetworksDAO = new PaymentnetworksMySqlDAO();


//Clientpaymentreceiptt
$Clientpaymentreceiptt = new Clientpaymentreceiptt();
$ClientpaymentreceipttDAO = new ClientpaymentreceipttMySqlDAO();
$ClientpaymentreceipttEx = new ClientpaymentreceipttMySqlExtDAO();

//Save
$save = new Save();
$saveDAO = new SaveMySqlDAO();
$saveExt = new SaveMySqlExtDAO();
$today = date("Y-m-d");

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

    ###########payment network
    $paymentmethod = $paymentNetworksDAO->queryByDeleted(0);
    $smarty->assign('paymentmethod', $paymentmethod);

    $banks = $bankDAO->queryAll();
    $smarty->assign("banks", $banks);

    $smarty->assign("receiptValidation", 1);
    $smarty->display("clientreceiptview/show.html");
} elseif ($do == 'search') {

    ###########payment network
    $paymentmethod = $paymentNetworksDAO->queryByDeleted(0);
    $smarty->assign('paymentmethod', $paymentmethod);

    $banks = $bankDAO->queryAll();
    $smarty->assign("banks", $banks);

    $clientname = filter_input(INPUT_POST, 'clientname');
    $clientdate = filter_input(INPUT_POST, 'clientdate');
    $paymethod = filter_input(INPUT_POST, 'paymethod');


    $smarty->assign("searchClientId", $clientname);
    $smarty->assign("searchDate", $clientdate);
    $smarty->assign("paymethod", $paymethod);

    if ($paymethod == 0) {

        if (!empty($clientname)) {
            getBillsToPay($clientname, $clientdate);
        }

        $smarty->assign("receiptValidation", 1);
        $smarty->display("clientreceiptview/show.html");
    } else {


        $smarty->assign("receiptValidation", 1);
        $smarty->display("clientreceiptview/secondshow.html");
    }
} elseif ($do == "show") {
    $showdel = filter_input(INPUT_POST, "showdel");
    if (empty($showdel)) {
        $showdel = 0;
    }

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

    $clientid = filter_input(INPUT_POST, "clientname");
    $datefrom = filter_input(INPUT_POST, "datefrom");
    $dateto = filter_input(INPUT_POST, "dateto");

    $queryString = " WHERE ";
    $queryString .= " del = " . $showdel;
    if (!empty($clientid)) {
        $queryString .= " and clientpaymentreceiptt.clientid= " . $clientid;
    }
    if (isset($datefrom) && !empty($datefrom)) {
        $queryString .= ' and clientpaymentreceiptt.sysdate >= "' . $datefrom . '" ';
    }
    if (isset($dateto) && !empty($dateto)) {
        $queryString .= ' and clientpaymentreceiptt.sysdate <= "' . $dateto . '" ';
    }
    $allDataArr = $ClientpaymentreceipttEx->queryAllEX($queryString);
    $smarty->assign("allDataArr", $allDataArr);

    $smarty->assign("receiptValidation", 1);
    $smarty->display("clientreceiptview/doshow.html");
} elseif ($do == "delete") {
    include_once("../public/authentication.php");

    try {
        remove();

        header("location:?do=show");
    } catch (Exception $e) {
        //echo $e;
        header("location:?do=error");
    }
} elseif ($do == "editprint") {
    include_once("../public/authentication.php");


    $id = $_GET['id'];

    $clientRecit = $ClientpaymentreceipttEx->queryByDailyentryid($id);
    $smarty->assign("clientRecit", $clientRecit[0]);


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

    $smarty->display("clientreceiptview/editprint.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->display("footer.html");

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

function getBillsToPay($clientname, $clientdate) {
    global $smarty;
    global $mySellbillEx;
    global $billsEX;
    $allDataArr = array();
    if (isset($clientname) && $clientname != '-1') {

        $message = "تقرير يوميه   ";
        $smarty->assign('message', $message);

        if (empty($clientdate)) {

            $queryString = 'WHERE sellbill.sellbillclientid = ' . $clientname . ' AND sellbillfinalbill !=0';
            $queryString1 = 'WHERE bills.clientid = ' . $clientname . ' AND  waitvalue !=0';
            #####bill Data
            $allsellbillData = $mySellbillEx->queryAllforreceipt($queryString);
            $allbillsData = $billsEX->queryAllforreceipt($queryString1);
            $i = 0;
            foreach ($allbillsData as $value) {
                $needToPay = $value->waitvalue - $value->clientPayReceiptVal;
                $value->waitvalue = $needToPay;
                if ($needToPay < 0) {##bill totally payed
                    unset($allbillsData[$i]);
                }
                $i++;
            }

            ##put in one array to order by date
            foreach ($allsellbillData as $value) {
                $value->userid = 0; ##type = sellbill
                $value->theDate = $value->sellbilldate;
                array_push($allDataArr, $value);
            }
            foreach ($allbillsData as $value) {
                $value->userid = 1; ##type = opticalbill
                $value->theDate = $value->billdate;
                array_push($allDataArr, $value);
            }
            $allDataArr = sortByDate('asc', $allDataArr);
        } else {

            $queryString = 'WHERE sellbill.sellbillclientid = ' . $clientname . ' and sellbilldate =' . $clientdate . '  AND sellbillfinalbill !=0';
            $queryString1 = 'WHERE bills.clientid = ' . $clientname . ' and billdate =' . $clientdate . ' AND  waitvalue !=0';
            #####bill Data
            $allsellbillData = $mySellbillEx->queryAllforreceipt($queryString);
            $allbillsData = $billsEX->queryAllforreceipt($queryString1);
            $i = 0;
            foreach ($allbillsData as $value) {
                $needToPay = $value->waitvalue - $value->clientPayReceiptVal;
                $value->waitvalue = $needToPay;
                if ($needToPay < 0) {##bill totally payed
                    unset($allbillsData[$i]);
                }
                $i++;
            }
            ##put in one array to order by date
            foreach ($allsellbillData as $value) {
                $value->userid = 0; ##type = sellbill
                array_push($allDataArr, $value);
            }
            foreach ($allbillsData as $value) {
                $value->userid = 1; ##type = opticalbill
                array_push($allDataArr, $value);
            }
            $allDataArr = sortByDate('asc', $allDataArr);
        }
    }
    /* $smarty->assign('allsellbillData', $allsellbillData);
      $smarty->assign('allbillsData', $allbillsData); */
    $smarty->assign('allDataArr', $allDataArr);
}

################################################################################

function sortByDate($type, $allDataArr) {

    //1-sort by date
    $Count = count($allDataArr) - 1; //-1 so as not to compare last item with null "reduce one itration"
    foreach ($allDataArr as $obj) {
        $tempObj;
        for ($i = 0; $i < $Count; $i++) {
            if ($type == "desc") {
                if ($allDataArr[$i]->theDate < $allDataArr[$i + 1]->theDate) {
                    $tempObj = $allDataArr[$i];
                    $allDataArr[$i] = $allDataArr[$i + 1];
                    $allDataArr[$i + 1] = $tempObj;
                }
            } elseif ($type == "asc") {
                if ($allDataArr[$i]->theDate > $allDataArr[$i + 1]->theDate) {
                    $tempObj = $allDataArr[$i + 1];
                    $allDataArr[$i + 1] = $allDataArr[$i];
                    $allDataArr[$i] = $tempObj;
                }
            }
        }
    }
    return $allDataArr;
}

function remove() {
    global $ClientpaymentreceipttDAO;
    $id = $_GET['id'];

    $clientRecit = $ClientpaymentreceipttDAO->load($id);

    if ($clientRecit->biltype == -1) {
        $data = payDebtReverse($clientRecit);
    } else {
        $data = payBillReverse($clientRecit);
    }
    if ($data == 1) {
        $clientRecit->del = 1;
        $ClientpaymentreceipttDAO->update($clientRecit);
    }
}

function payDebtReverse($clientRecit) {
    global $saveDAO;
    global $accountsTreeDAO;
    global $ClientDAO;
    global $bankDAO;
    global $bankAccountDAO;
    global $ClientpaymentreceipttDAO;

    $saveid = $_SESSION['saveid'];

//    $client = $ClientDAO->load($clientRecit->clientid);
//    $debtbefore = $client->clientdebt;
    #####reverse in dataentry##this include affectting save && client
    $data = reverseEntryWithItsID($clientRecit->dailyentryid);


//    $client = $ClientDAO->load($clientRecit->clientid);
//    $debtafter = $client->clientdebt;
//
//    insertClientPaymentReceiptt($clientRecit->clientid, -1, -1, $clientRecit->payedtype, $debtbefore, $clientRecit->payed, $clientRecit->paymethod, $debtafter, $data[1], $clientRecit->biltype);

    return 1;
}

function payBillReverse($clientRecit) {
    global $saveDAO;
    global $accountsTreeDAO;
    global $ClientDAO;
    global $mySellbillRecord;
    global $mySellbillEx;
    global $billsDAO;
    global $billsEX;
    global $bankDAO;
    global $bankAccountDAO;
    global $ClientpaymentreceipttDAO;

    $thevalue = $clientRecit->payed;
    $billid = $clientRecit->billid;
    $billtype = $clientRecit->biltype;
    #####reverse in dataentry##this include affectting save && client
//    $client = $ClientDAO->load($clientRecit->clientid);
//    $debtbefore = $client->clientdebt;
    #####reverse in dataentry##this include affectting save && client
    $data = reverseEntryWithItsID($clientRecit->dailyentryid);


//    $client = $ClientDAO->load($clientRecit->clientid);
//    $debtafter = $client->clientdebt;
    ##affect bill payed ,remaining
    if ($billtype == 0) {##فاتورة مبيعات
        $sellbill = $mySellbillRecord->load($billid);
        $sellbill->sellbilltotalpayed = $sellbill->sellbilltotalpayed - $thevalue;
        $sellbill->sellbillfinalbill = $sellbill->sellbillfinalbill + $thevalue;
        $sellbill->sellbillid = $billid;

        $mySellbillEx->updatePayedAndRemain($sellbill);
    } elseif ($billtype == 1) {##فاتورة بصريات
        $thebill = $billsDAO->load($billid);
        $newPay = $thebill->clientPayReceiptVal - $thevalue;
        $billsEX->updateClientPayReceiptVal($newPay, $thebill->id);
    }
    return 1;
}

?>