<?php

//the global file operation
session_start();
ob_start();
//global varable
global $showoutside;

include_once("dailyentryfun.php");

//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");
include_once("../library/num_to_ar.php");
//Programsetting
require_once('../models/dao/ProgramsettingsDAO.class.php');
require_once('../models/dto/Programsetting.class.php');
require_once('../models/mysql/ProgramsettingsMySqlDAO.class.php');
require_once('../models/mysql/ext/ProgramsettingsMySqlExtDAO.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');

//Product
require_once('../models/dao/ProductDAO.class.php');
require_once('../models/dto/Product.class.php');
require_once('../models/mysql/ProductMySqlDAO.class.php');
require_once('../models/mysql/ext/ProductMySqlExtDAO.class.php');

//Project
require_once('../models/dao/ProjectDAO.class.php');
require_once('../models/dto/Project.class.php');
require_once('../models/mysql/ProjectMySqlDAO.class.php');
require_once('../models/mysql/ext/ProjectMySqlExtDAO.class.php');
//Bankaccount
require_once('../models/dao/BankaccountDAO.class.php');
require_once('../models/dto/Bankaccount.class.php');
require_once('../models/mysql/BankaccountMySqlDAO.class.php');
require_once('../models/mysql/ext/BankaccountMySqlExtDAO.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');

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

//get the do the action
$do = $_GET['do'];

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

  Controller Name :- productController

  OPERTATION in Controller

  1- display add form, add supplier cat and supplier with ajax
  2- add in supplier tbl
  2.1- insert into supplier unit tbl
  2.2- insert into storedetail tbl
  2.3- insert new row into storereport tbl
  3- display show and tempdelete
  4- edit supplier
  5- update supplier
  5.1- update supplier tbl with supplierid
  5.2- delete supplier units associated to this supplier from productunit tbl, then insert it again

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

//here goes the instances and general variables
//Save
$save = new Save();
$saveDAO = new SaveMySqlDAO();
$saveExt = new SaveMySqlExtDAO();
$Client = new Client();
$ClientDAO = new ClientMySqlDAO();
$ClientEx = new ClientMySqlExtDAO();

//Product
$myProductRecord = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();

//Programsetting
$Programsetting = new Programsetting();
$ProgramsettingDAO = new ProgramsettingsMySqlDAO();
$ProgramsettingEX = new ProgramsettingsMySqlExtDAO();



$Project = new Project();
$ProjectDAO = new ProjectMySqlDAO();
$ProjectEx = new ProjectMySqlExtDAO();

//Bankaccount
$bankAccount = new Bankaccount();
$bankAccountDAO = new BankaccountMySqlDAO();
$bankAccountEx = new BankaccountMySqlExtDAO();


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

//Sellbill
$mySellbill = new Sellbill();
$mySellbillRecord = new SellbillMySqlDAO();
$mySellbillEx = new SellbillMySqlExtDAO();
//bill
$bills = new Bill();
$billsDAO = new BillsMySqlDAO();
$billsEX = new BillsMySqlExtDAO();
//paymentnetworks
$paymentNetworks = new Paymentnetwork();
$paymentNetworksDAO = new PaymentnetworksMySqlDAO();
//check and use the condition that suite this action
if (empty($do)) {

}

/* ========sellprice ==================== */ elseif ($do == "checkprojectname") {

    //get id for item //registeyid //requestidnt
    $projectname = filter_input(INPUT_POST, 'projectname');
    $oldid = filter_input(INPUT_POST, 'proid');

    if (!empty($oldid)) {
        $oldmemberinfo = $ProjectDAO->load($oldid);
        $projectoldname = $oldmemberinfo->name;
    }

    $projectname = trim($projectname);
    //insert
    $checkprojectname = $ProjectEx->queryByNameadd($projectname);

    if (count($checkprojectname) > 0) {

        if ($checkprojectname[0]->name == $projectoldname) {
            $status = 'OK';
            $message = "يمكن استخدام هذا الاسم";
        } else {
            $status = 'NO';
            $message = "يجب تجربه اسم اخر لان هذا الاسم مستخدم";
        }
    } else {
        $status = 'OK';
        $message = "يمكن استخدام هذا الاسم";
    }

    $reslt = array("status" => $status, "message" => $message);
    echo json_encode($reslt);
} elseif ($do == "getproject") {

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);

    $row_array = array();
    $return_arr = array();


   
   

    if ($_SESSION['projectids'] == 0) {
        $allproject = $ProjectEx->getprojectsExt($name);
    }else{
        $queryString = " and name LIKE '%" . $name . "%' ";
        $queryString .= ' and id in (' . $_SESSION['projectids'] . ')';
        $allproject = $ProjectEx->queryWithConditionWithQueryString($queryString);
    }



    
    foreach ($allproject as $project) {
        $row_array['id'] = $project->id;
        $row_array['text'] = $project->name;

        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
} elseif ($do == "getprojectdata") {
    $id = filter_input(INPUT_POST, 'id');
     $Project = $ProjectDAO->load($id);
     echo json_encode($Project);
    
} elseif ($do == "getprojectforreport") {

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);

    $row_array = array();
    $return_arr = array();

    $allproject = $ProjectEx->getprojectsforreportExt($name);
    foreach ($allproject as $project) {
        $row_array['id'] = $project->id;
        $row_array['text'] = $project->name;

        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
} elseif ($do == "getclient") {

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);

    $row_array = array();
    $return_arr = array();

    $allclient = $ClientEx->getClients1($name);
    foreach ($allclient as $data) {
        $row_array['id'] = $data->value;
        $row_array['text'] = $data->label;

        array_push($return_arr, $row_array);
    }

    echo json_encode($return_arr);
}

/* ========sellprice ==================== */ elseif ($do == "getproductsellprice") {

    $productid = $_GET['productid'];
    $proofferData = $productExt->loadEX($productid);
    echo json_encode($proofferData);
} elseif ($do == "getbankaccount") {
    $id = filter_input(INPUT_POST, "id");
    $bankAccount = $bankAccountDAO->queryByBankid($id);
    $html = '<option value=""></option>';
    foreach ($bankAccount as $value) {
        $html .= "<option value=" . $value->accountid . ">" . $value->accountname . "</option>";
    }

    echo $html;
}


/* =====================payednetwork ================================= */ elseif ($do == "paynetwork") {

    /////VAR
    $clientpayed = filter_input(INPUT_POST, 'clientpayed');
    $payedtype = filter_input(INPUT_POST, 'payedtype');
    $paynetwork = filter_input(INPUT_POST, 'paynetwork');
    $billid = filter_input(INPUT_POST, 'billid');
    $billtype = filter_input(INPUT_POST, 'billtype');
    $billclientid = filter_input(INPUT_POST, 'billclientid');
    $debtbefore = filter_input(INPUT_POST, 'debtbefore');

    $bankid = filter_input(INPUT_POST, 'bankid');
    $bankaccountid = filter_input(INPUT_POST, 'bankaccountid');

    $searchClientId = filter_input(INPUT_POST, 'searchClientId');
    $searchDate = filter_input(INPUT_POST, 'searchDate');
    $mypaymethod = filter_input(INPUT_POST, 'mypaymethod');
    if ($mypaymethod == 1) {
        $newDebt = payDebt($clientpayed, $searchClientId, $payedtype, $paynetwork, $mypaymethod, $bankid, $bankaccountid);
    } else {
        $newDebt = payBill($clientpayed, $payedtype, $paynetwork, $billid, $billtype, $billclientid, $debtbefore, $mypaymethod, $bankid, $bankaccountid);
    }
    echo $newDebt;
    //getBillsToPay($searchClientId, $searchDate);
} elseif ($do == "clientdebt") {
    $id = filter_input(INPUT_POST, 'id');
    $client = $ClientDAO->load($id);
    echo $client->clientdebt;
} 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/showajax.html");
    } else {


        $smarty->assign("receiptValidation", 1);
        $smarty->display("clientreceiptview/secondshow.html");
    }
}
/* ===============================
  function in this CONTROLLER
  ================================ */

function payDebt($clientpayed, $searchClientId, $payedtype, $paynetwork, $mypaymethod, $bankid, $bankaccountid) {
    global $saveDAO;
    global $accountsTreeDAO;
    global $ClientDAO;
    global $bankDAO;
    global $bankAccountDAO;
    global $paymentNetworksDAO;


    //Transaction
    $mytransactions = new Transaction();
    try {

        $saveid = $_SESSION['saveid'];

        #####insert in dataentry##this include affectting save && client
        if ($payedtype == 2) {
            ##bank
            $EFrom = $bankAccountDAO->load($bankaccountid);
            $ETTreeData = $accountsTreeDAO->queryByName($EFrom->accountname);
            $saveTreeId = $ETTreeData[0]->id;
            if (count($ETTreeData) == 0) {
                $bankData = $bankDAO->load($bankid);
                $bankTreeData = $accountsTreeDAO->queryByName($bankData->bankname);
                if (count($bankTreeData) == 0) {
                    $bankTreeId = addTreeElement($bankData->bankname, 21, 3, 0, 0, '', 0, 0);
                } else {
                    $bankTreeId = $bankTreeData[0]->id;
                }
                $saveTreeId = addTreeElement($EFrom->accountname, $bankTreeId, 3, 0, 1, '', 0, 0);
            }
        } else if ($payedtype == 1) {
            ##network
            $network = $paymentNetworksDAO->load($paynetwork);
            $networkTree = $accountsTreeDAO->queryByName($network->name);
            if (count($networkTree) < 1) {
                $saveTreeId = addTreeElement($network->name, 41, 3, 0, 1, '', 0, 0);
            } else {
                $saveTreeId = $networkTree[0]->id;
            }
        } else {##$payedtype == 0 case
            ##save
            $save = $saveDAO->load($saveid);
            $saveTree = $accountsTreeDAO->queryByName($save->savename);
            if (count($saveTree) < 1) {
                $saveTreeId = addTreeElement($save->savename, 20, 3, 0, 1, '', 0, 0);
            } else {
                $saveTreeId = $saveTree[0]->id;
            }
        }

        $client = $ClientDAO->load($searchClientId);
        $debtbefore = $client->clientdebt;
        $clientTree = $accountsTreeDAO->queryByName($client->clientname);
        if (count($clientTree) < 1) {
            $clientTreeId = addTreeElement($client->clientname, 23, 3, 0, 1, '', 0, 0);
        } else {
            $clientTreeId = $clientTree[0]->id;
        }


        $entryid = entryinsert_data($clientpayed, $saveTreeId, $clientTreeId);
        $client = $ClientDAO->load($searchClientId);
        $debtafter = $client->clientdebt;

        insertClientPaymentReceiptt($searchClientId, -1, -1, $payedtype, $debtbefore, $clientpayed, $paynetwork, $debtafter, $entryid, $mypaymethod);


        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }

    return "paymethod1success";
}

function payBill($clientpayed, $payedtype, $paynetwork, $billid, $billtype, $billclientid, $debtbefore, $mypaymethod, $bankid, $bankaccountid) {
    global $saveDAO;
    global $accountsTreeDAO;
    global $ClientDAO;
    global $mySellbillRecord;
    global $mySellbillEx;
    global $billsDAO;
    global $billsEX;
    global $bankDAO;
    global $bankAccountDAO;
    global $paymentNetworksDAO;


    //Transaction
    $mytransactions = new Transaction();
    try {

        $saveid = $_SESSION['saveid'];
        $debtafter = 0;
        $thevalue = 0;

        if ($clientpayed == $debtbefore) {
            $thevalue = $clientpayed;
            $debtafter = 0;
        } elseif ($clientpayed > $debtbefore) {
            $thevalue = $debtbefore;
            $debtafter = 0;
        } elseif ($clientpayed < $debtbefore) {
            $thevalue = $clientpayed;
            $debtafter = $debtbefore - $clientpayed;
        }
        $remainPayed = $clientpayed - $thevalue;


        #####insert in dataentry##this include affectting save && client
        if ($payedtype == 2) {
            ##bank
            $EFrom = $bankAccountDAO->load($bankaccountid);
            $ETTreeData = $accountsTreeDAO->queryByName($EFrom->accountname);
            $saveTreeId = $ETTreeData[0]->id;
            if (count($ETTreeData) == 0) {
                $bankData = $bankDAO->load($bankid);
                $bankTreeData = $accountsTreeDAO->queryByName($bankData->bankname);
                if (count($bankTreeData) == 0) {
                    $bankTreeId = addTreeElement($bankData->bankname, 21, 3, 0, 0, '', 0, 0);
                } else {
                    $bankTreeId = $bankTreeData[0]->id;
                }
                $saveTreeId = addTreeElement($EFrom->accountname, $bankTreeId, 3, 0, 1, '', 0, 0);
            }
        } else if ($payedtype == 1) {
            ##network
            $network = $paymentNetworksDAO->load($paynetwork);
            $networkTree = $accountsTreeDAO->queryByName($network->name);
            if (count($networkTree) < 1) {
                $saveTreeId = addTreeElement($network->name, 41, 3, 0, 1, '', 0, 0);
            } else {
                $saveTreeId = $networkTree[0]->id;
            }
        } else {##$payedtype == 0 case
            ##save
            $save = $saveDAO->load($saveid);
            $saveTree = $accountsTreeDAO->queryByName($save->savename);
            if (count($saveTree) < 1) {
                $saveTreeId = addTreeElement($save->savename, 20, 3, 0, 1, '', 0, 0);
            } else {
                $saveTreeId = $saveTree[0]->id;
            }
        }
        $client = $ClientDAO->load($billclientid);
        $clientTree = $accountsTreeDAO->queryByName($client->clientname);
        if (count($clientTree) < 1) {
            $clientTreeId = addTreeElement($client->clientname, 23, 3, 0, 1, '', 0, 0);
        } else {
            $clientTreeId = $clientTree[0]->id;
        }


        $entryid = entryinsert_data($thevalue, $saveTreeId, $clientTreeId);
        insertClientPaymentReceiptt($billclientid, $billid, $billtype, $payedtype, $debtbefore, $clientpayed, $paynetwork, $debtafter, $entryid, $mypaymethod);
        $newDebt = 0;
        ##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);
            $newDebt = $sellbill->sellbillfinalbill;
        } elseif ($billtype == 1) {##فاتورة بصريات
            $thebill = $billsDAO->load($billid);
            $newPay = $thebill->clientPayReceiptVal + $thevalue;
            $billsEX->updateClientPayReceiptVal($newPay, $thebill->id);
            $newDebt = $thebill->waitvalue - $newPay;
        }


        $mytransactions->commit();
    } catch (Exception $ex) {
        $mytransactions->rollback();
    }

    return $newDebt . "-" . $remainPayed;
}

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);
    $smarty->assign('allDataArrCount', count($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 insertClientPaymentReceiptt($billclientid, $billid, $billtype, $payedtype, $debtbefore, $clientpayed, $paynetwork, $debtafter, $entryid, $mypaymethod) {
    global $Clientpaymentreceiptt;
    global $ClientpaymentreceipttDAO;

    $Clientpaymentreceiptt->clientid = $billclientid;
    $Clientpaymentreceiptt->billid = $billid;
    $Clientpaymentreceiptt->biltype = $billtype;
    $Clientpaymentreceiptt->payedtype = $payedtype;
    $Clientpaymentreceiptt->debtbefore = $debtbefore;
    $Clientpaymentreceiptt->payed = $clientpayed;
    $Clientpaymentreceiptt->paymethod = $mypaymethod; //$paynetwork;
    $Clientpaymentreceiptt->debtafter = $debtafter;
    $Clientpaymentreceiptt->userid = $_SESSION['userid'];
    $Clientpaymentreceiptt->sysdate = date("Y-m-d");
    $Clientpaymentreceiptt->del = 0;
    $Clientpaymentreceiptt->dailyentryid = $entryid;

    $ClientpaymentreceipttDAO->insert($Clientpaymentreceiptt);
}

function entryinsert_data($value, $saveTreeId, $clientTreeId) {

    global $dailyEntry;
    global $dailyEntryCreditor;
    global $dailyEntryDebtor;



    ########## nsert into entry
    $dailyEntry->entryComment = 'ايصالات قبض';
    $dailyEntry->fromFlag = 2;
    $dailyEntry->reverseofid = 0;

    $dailyEntryDebtorArray = array();
    $dailyEntryDebtor->value = $value;
    $dailyEntryDebtor->accountstreeid = $saveTreeId;
    $dailyEntryDebtor->pluginComment = "ايصالات قبض";
    $dailyEntryDebtor->pluginControllerName = "clientreceiptController.php";
    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

    $dailyEntryCreditorArray = array();
    $dailyEntryCreditor->value = $value;
    $dailyEntryCreditor->accountstreeid = $clientTreeId;
    $dailyEntryCreditor->pluginComment = "ايصالات قبض";
    $dailyEntryCreditor->pluginControllerName = "clientreceiptController.php";
    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);



    $entryData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
    return $entryData[1];
}

?>