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

//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');
//Sellbilldetail
require_once('../models/dao/SellbilldetailDAO.class.php');
require_once('../models/dto/Sellbilldetail.class.php');
require_once('../models/mysql/SellbilldetailMySqlDAO.class.php');
require_once('../models/mysql/ext/SellbilldetailMySqlExtDAO.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');

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

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

  Controller Name :- clientPayedDeptReportController

  OPERTATION in Controller

  1- تقرير سداد ديون عميل بصاريات

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

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

//here goes the instances and general variables
//Sellbill
$sellBill = new Sellbill();
$sellBillDAO = new SellbillMySqlDAO();
$sellBillEX = new SellbillMySqlExtDAO();
//Sellbilldetail
$sellBillDetail = new Sellbilldetail();
$sellBillDetailDAO = new SellbilldetailMySqlDAO();
$sellBillDetailEX = new SellbilldetailMySqlExtDAO();
//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();

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


//Clientdebtchange
$clientDeptChange = new Clientdebtchange();
$clientDeptChangeDAO = new ClientdebtchangeMySqlDAO();
$clientDeptChangeExt = new ClientdebtchangeMySqlExtDAO();

$today = date("Y-m-d");
if (empty($do)) {// السداد على فاتورة بيع للعميل
    //here the permssion check
    include_once("../public/authentication.php");


    $start_date = $_REQUEST['from'];
    $end_date = $_REQUEST['to'];
    $client = $_POST['client'];
    $bill_no = $_POST['bill_no'];
    $obgyBillType = (int) $_POST['obgyBillType'];

    $queryString = " where 1 ";
    $result_string = '';
    if ((isset($client) && $client != "-1" && $client != '')) {
        $queryString .= ' and sellbill.sellbillclientid = ' . $client . ' ';


        $messageData = $clientDAO->load($client);
        $result_string .= " اسم العميل : " . $messageData->clientname;
        $smarty->assign("client_id", $messageData->clientid);
    }
    if ((isset($bill_no) && $bill_no != "")) {
        $queryString .= ' and sellbill.sellbillid	 = ' . $bill_no . ' ';
    }

    if (isset($start_date) && $start_date != "" && isset($end_date) && $end_date != "") {
        $queryString .= ' and  date(sellbill.sellbilldate) >= "' . $start_date . '" and date(sellbill.sellbilldate) <= "' . $end_date . '" ';
        $result_string .= " التاريخ: من   :  " . $start_date . " إلى: " . $end_date;
    }
    if ((isset($obgyBillType) && !empty($obgyBillType))) {
        $queryString .= ' and sellbill.obgyBillType = ' . $obgyBillType . ' ';
    }


    if ($queryString != " where 1 ") {

        $message = $result_string;
        $smarty->assign("message", $message);

        $queryString .= ' and sellbill.conditions = 0 ';
        //////$sellbillData = $sellBillEX->queryallWithOrder($queryString);
        ##getting bills
        $sellbillData = R::getAll('SELECT sellbillid,sellbilldate,pricetype,sellbilltotalpayed,sellbillfinalbill,sellbillaftertotalbill,conditions,
                                   userid,sellbillclientid
                                   FROM sellbill ' . $queryString . ' ORDER BY  `sellbilldate`  desc ,sellbillid desc ');

        list($billIDs, $userIDs, $clientIDs) = [[], [], []];
        foreach ($sellbillData as $value) {
            $billIDs[] = $value['sellbillid'];
            $userIDs[] = $value['userid'];
            $clientIDs[] = $value['sellbillclientid'];
        }
        $billIDs = !empty($billIDs) ? array_unique($billIDs) : [0];
        $userIDs = !empty($userIDs) ? array_unique($userIDs) : [0];
        $clientIDs = !empty($clientIDs) ? array_unique($clientIDs) : [0];
        ##2-user data
        $userDataArr = R::getAll('select userid,employeename from user where userid in(' . implode(',', $userIDs) . ') ');
        $userDataArr = customArrayIndexOne($userDataArr, 'userid');
        ##3-client
        $clientDataArr = R::getAll('select clientid,clientname from client where clientid in(' . implode(',', $clientIDs) . ') ');
        $clientDataArr = customArrayIndexOne($clientDataArr, 'clientid');
        ##4-bill Pays data
        $billPaysDataArr = R::getAll('SELECT billid , sum(clientdebtchangeamount) as clientdebtchangeamount FROM clientdebtchange WHERE `billid`in(' . implode(',', $billIDs) . ') and tablename = "clientPayedDeptSellBillsController.php" group by billid ');
        $billPaysDataArr = customArrayIndexOne($billPaysDataArr, 'billid');

        $client_bills = array();
        foreach ($sellbillData as $value) {

            $value['useremployeename'] = $userDataArr[$value['userid']]['employeename'];
            $value['clientname'] = $clientDataArr[$value['sellbillclientid']]['clientname'];

            $client_dept_change_amount = $billPaysDataArr[$value['sellbillid']]['clientdebtchangeamount'];
            $waitvalue = $value['sellbillfinalbill'] - $client_dept_change_amount; //# قيمة الدين
            if ($waitvalue > 0) {
                $client_bills[] = array(
                    'id' => $value['sellbillid'],
                    'billno' => $value['sellbillid'],
                    'finalnetbillvalue' => $value['sellbillaftertotalbill'],
                    'waitvalue' => $waitvalue,
                    'billDate' => $value['sellbilldate'],
                    'userName' => $value['useremployeename'],
                    'clientName' => $value['clientname'],
                    'total_payed' => $value['sellbilltotalpayed'] + $client_dept_change_amount//check payed, save payed come from clientdebtchangeamount //sellbilltotalpayed is total of payed cash and visa payed of bill
                );
            }
        }

        $smarty->assign("client_bills", $client_bills);
    }


    $smarty->assign("customClientDeptChangeReportSellbill", 1);
    $smarty->display("clientPayedDeptSellBillsView/add.html");
} elseif ($do == "show") {

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


    $start_date = $_REQUEST['from'];
    $end_date = $_REQUEST['to'];
    $client = $_POST['client'];
    $bill_id = $_POST['bill_no'];

    $where = '';
    if ((isset($client) && $client != "-1" && $client != '')) {
        $where .= 'and clientid = ' . $client . ' ';
    }
    if ((isset($bill_id) && $bill_id != "")) {
        //$bill_data = $billsDAO->load($bill_id);
        //$bill_id = $bill_data->billno;
        $where .= ' and billid = ' . $bill_id . ' ';
    }

    if (isset($start_date) && $start_date != "" && isset($end_date) && $end_date != "") {
        $where .= ' and  date(clientdebtchangedate) >= "' . $start_date . '" and  date(clientdebtchangedate) <= "' . $end_date . '" ';
    }


    if ($where != '') {
        //$client_payed_bills = $clientDeptChangeExt->selectAllPayedBillsAndControl($where, 'clientPayedDeptSellBillsController.php');
        $client_payed_bills = R::getAll('SELECT distinct `billid` FROM `clientdebtchange` where `billid` != "" ' . $where . ' and tablename = "clientPayedDeptSellBillsController.php" order by `billid`');
        list($billIDs) = [[]];
        foreach ($client_payed_bills as $value) {
            $billIDs[] = $value['billid'];
        }
        $billIDs = !empty($billIDs) ? array_unique($billIDs) : [0];
        ##2-bill Pays data
        $billPaysDataArr = R::getAll('SELECT billid , sum(clientdebtchangeamount) as clientdebtchangeamount FROM clientdebtchange WHERE `billid`in(' . implode(',', $billIDs) . ') and tablename = "clientPayedDeptSellBillsController.php" group by billid ');
        $billPaysDataArr = customArrayIndexOne($billPaysDataArr, 'billid');
        ##3-getting bills
        $sellbillData = R::getAll('SELECT sellbillid,sellbilltotalpayed,sellbillfinalbill,sellbillaftertotalbill
                                   FROM sellbill where sellbillid in(' . implode(',', $billIDs) . ')'); //. ' ORDER BY sellbilldate desc ,sellbillid desc '
        $sellbillData = customArrayIndexOne($sellbillData, 'sellbillid');


        $client_bills = array();
        $total_bills = $total_wait_bills = $total_payed_bills = 0;

        foreach ($client_payed_bills as $cli_payed_bill) {
            $client_dept_change_amount = $billPaysDataArr[$cli_payed_bill['billid']]['clientdebtchangeamount'];
            $sellbillfinalbill = $sellbillData[$cli_payed_bill['billid']]['sellbillfinalbill'];
            $sellbillaftertotalbill = $sellbillData[$cli_payed_bill['billid']]['sellbillaftertotalbill'];
            $sellbilltotalpayed = $sellbillData[$cli_payed_bill['billid']]['sellbilltotalpayed'];

            $waitvalue = $sellbillfinalbill - $client_dept_change_amount;

            //if( $waitvalue > 0){

            $client_bills[] = array(
                'id' => $cli_payed_bill['billid'],
                'billno' => $cli_payed_bill['billid'],
                'finalnetbillvalue' => $sellbillaftertotalbill,
                'waitvalue' => $waitvalue,
                'total_payed' => $sellbilltotalpayed + $client_dept_change_amount, //check payed, save payed come from clientdebtchangeamount //sellbilltotalpayed is total of payed cash and visa payed of bill
            );

            $total_bills += $sellbillaftertotalbill;
            $total_wait_bills += $waitvalue;
            $total_payed_bills += $sellbilltotalpayed + $client_dept_change_amount;
            //}
        }
    }


    $smarty->assign("total_bills", $total_bills);
    $smarty->assign("total_wait_bills", $total_wait_bills);
    $smarty->assign("total_payed_bills", $total_payed_bills);

    $smarty->assign("client_bills", $client_bills);

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

    $smarty->assign("customClientDeptChangeReportSellbill", 1);
    $smarty->display("clientPayedDeptSellBillsView/show.html");
} elseif ($do == "show_details" || $do == "editprint" || $do == "details") {



    $bill_no = $_GET['id'];

    $bill_data = $sellBillDAO->load($bill_no);

    //# bill data .
    $finalnetbillvalue = $bill_data->sellbillaftertotalbill;
    $waitvalue = $bill_data->sellbillfinalbill;
    $payed = $bill_data->sellbilltotalpayed;

    //# load client data .
    $clientid = $bill_data->sellbillclientid;
    $messageData = $clientDAO->load($clientid);

    $message = " اسم العميل : " . $messageData->clientname;
    $smarty->assign("message", $message);


    //# select all rows which belongs to this bill no.
    $client_dept_Bills = $clientDeptChangeExt->selectByBillIdAndControl($bill_no, 'clientPayedDeptSellBillsController.php');


    $client_bills = array();
    $x = 1;
    foreach ($client_dept_Bills as $cli_bill_val) {

        $clientdebtchangeamount = $cli_bill_val->clientdebtchangeamount;
        $paytype = $cli_bill_val->paytype;
        $date = $cli_bill_val->clientdebtchangedate;

        if ($x == 1) {
            $wait_before = $waitvalue;
            $wait_aftre = $wait_before - ( $clientdebtchangeamount ); //$wait_before - ( $payed + $clientdebtchangeamount );
        } else {
            $wait_before = $wait_aftre;

            $wait_aftre = $wait_before - $clientdebtchangeamount;
        }
        //if( $waitvalue > 0 ){
        $client_bills[] = array(
            'itra' => $x,
            'finalnetbillvalue' => $finalnetbillvalue,
            'wait_before' => $wait_before,
            'clientdebtchangeamount' => $clientdebtchangeamount,
            'wait_after' => $wait_aftre,
            'date' => $date,
            'paytype' => $paytype,
            'comment' => $cli_bill_val->comment,
            'clientdebtchangeid' => $cli_bill_val->clientdebtchangeid,
            'userName' => $cli_bill_val->employeename,
            'dailyentryid' => $cli_bill_val->dailyentryid,
        );

        $x++;
    }

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

    $smarty->assign("client_bills", $client_bills);

    $smarty->display("clientPayedDeptSellBillsView/show_details.html");
}

//check and use the condition that suite this action
//here the global templates
$smarty->display("footer.html");
?>