HEX
Server: Apache
System: Linux server1.royalgt4.com 4.18.0-553.89.1.lve.el8.x86_64 #1 SMP Wed Dec 10 13:58:50 UTC 2025 x86_64
User: mostafedeg (1125)
PHP: 5.6.40
Disabled: mail,passthru,parse_ini_file,show_source,eval,assert,pcntl_exec,dl,putenv,proc_open,popen
Upload Files
File: /home/mostafedeg/public_html/erp/controllers/billsajax.php
<?php

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



global $showoutside;

//to check if the page from .htacess
//$showoutside = $_GET['sn'];
// get the config file$bill_name = " اضافة فاتورة بصريات عادية";
include_once("../public/config.php");
include("../library/uploadImages.php");

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

include_once('dailyentryfun.php');

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



//Product
$product = new Product();
$productDAO = new ProductMySqlDAO();
$productExt = new ProductMySqlExtDAO();

//Productcat
$productCatDAO = new ProductcatMySqlDAO();
$productCatExt = new ProductcatMySqlExtDAO();

//Client
$client = new Client();
$clientDAO = new ClientMySqlDAO();
$clientExt = new ClientMySqlExtDAO();

$user = new User();
$userDAO = new UserMySqlDAO();
$userEX = new UserMySqlExtDAO();

$userGroup = new Usergroup();
$userGroupDAO = new UsergroupMySqlDAO();
$UsergroupEX = new UsergroupMySqlExtDAO();


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

//billsproducts
$billsProducts = new Billsproduct();
$billsProductsDAO = new BillsproductsMySqlDAO();
$billsProductsEX = new BillsproductsMySqlExtDAO();

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

//bill
$billsReturn = new Billsreturn();
$billsReturnDAO = new BillsreturnMySqlDAO();
$billsReturnEX = new BillsreturnMySqlExtDAO();

//billsproducts
$billsReturnProducts = new Billsreturnproduct();
$billsReturnProductsDAO = new BillsreturnproductsMySqlDAO();
$billsReturnProductsEX = new BillsreturnproductsMySqlExtDAO();

// insurancecompanies
$insuranceCompanies = new Insurancecompanie();
$insuranceCompaniesDAO = new InsurancecompaniesMySqlDAO();
$insuranceCompaniesEx = new InsurancecompaniesMySqlExtDAO();

//doctorkashf
$doctorKashf = new Doctorkashf();
$doctorKashfDAO = new DoctorkashfMySqlDAO();
$doctorKashfEX = new DoctorkashfMySqlExtDAO();


//storedetail

$storeDetail = new Storedetail();
$storeDetailDAO = new StoredetailMySqlDAO();
$storeDetailEX = new StoredetailMySqlExtDAO();

$kashf = new Kashf();
$kashfDAO = new KashfMySqlDAO();
$kashfDAOEx = new KashfMySqlExtDAO();


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

//paymentnetworks
$insurancecompany = new Insurancecompanie();
$insuranceCompanyDAO = new InsurancecompaniesMySqlDAO();
$insuranceCompanyEX = new InsurancecompaniesMySqlExtDAO();

$branchDAO = new BranchMySqlDAO();

//Dailyentry
$dailyEntry = new Dailyentry();

//Dailyentrycreditor دائن
$dailyEntryCreditor = new Dailyentrycreditor();

//Dailyentrydebtor مدين
$dailyEntryDebtor = new Dailyentrydebtor();

//Dailyentrydebtor مدين
$dailyEntryDebtor_2 = new Dailyentrydebtor();

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

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

$mySave = new Save();
$mySaveDAO = new SaveMySqlDAO();
$mySaveEx = new SaveMySqlExtDAO();

//savedaily
$Savedaily = new Savedaily();
$SavedailyDAO = new SavedailyMySqlDAO();


//Storereport
$myStorereport = new Storereport();
$myStorereportRecord = new StorereportMySqlDAO();
$myStorereportEx = new StorereportMySqlExtDAO();

//supplier
$supplier = new Supplier();
$supplierDAO = new SupplierMySqlDAO();
$supplierEX = new SupplierMySqlExtDAO();

//bill
$billsBuy = new Billsbuy();
$billsBuyDAO = new BillsbuyMySqlDAO();
$billsBuyEX = new BillsbuyMySqlExtDAO();
//bill products
$billsProductsBuy = new Billsproductsbuy();
$billsProductsBuyDAO = new BillsproductsbuyMySqlDAO();
$billsProductsBuyEX = new BillsproductsbuyMySqlExtDAO();

//Clientdebtchange
$myClientdebtchange = new Clientdebtchange();
$myClientdebtchangeRecord = new ClientdebtchangeMySqlDAO();
$myClientdebtchangeEx = new ClientdebtchangeMySqlExtDAO();

$myUserRecord = new UserMySqlDAO();


$programSettingDAO = new ProgramsettingsMySqlDAO();
$programSetting = $programSettingDAO->load(1);
$smarty->assign("Programsettingdata", $programSetting);
$lastLevelCatIDS = array();
$catsIDS = "";
if ($do == "addnewproduct") {
    $itr = filter_input(INPUT_POST, "newItr");
    $smarty->assign("itr", $itr);
    $smarty->display("billsview/newproduct.html"); //the template page
}
##
elseif ($do == "addnewproduct2") {
    $itr = filter_input(INPUT_POST, "newItr");
    $bill_type = filter_input(INPUT_POST, "bill_type");

    $smarty->assign("itr", $itr);
    $smarty->assign("bill_type", $bill_type);

##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);
    $smarty->display("billsview/newproduct2.html"); //the template page
} elseif ($do == "addnewproduct3") {
    $itr = filter_input(INPUT_POST, "newItr");
    //print_r('$itr = ' . $itr);
    $smarty->assign("itr", $itr);
##التصنيفات
    $catDataReport = getCategoryChilds();
    $smarty->assign("catDataReport", $catDataReport[1]);
    $smarty->display("storemovementview/newrow.html"); //the template page
}
##
elseif ($do == "getinsDetail") {
    $insuranceCompanyId = filter_input(INPUT_POST, "insuranceCompanyId");

    $insuranceCompanies = $insuranceCompaniesDAO->load($insuranceCompanyId);
    $result = array();

    if (count($insuranceCompanies) > 0) {
        $result['name'] = $insuranceCompanies->name;
        $result['instruction'] = $insuranceCompanies->instruction;
    }

    echo json_encode($result);
} elseif ($do == "getclients") {
    $row_array = array();
    $return_arr = array();
    $userData = $myUserRecord->load($_SESSION['userid']);

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $no_add = (int) $_GET['noadd']; //to show or hide add client option
    $limit = 15; //intval($_GET['page_limit']);
    $queryString = "";
    if ($userData->viewclients == 0) {
        $queryString .= ' and userid = ' . $_SESSION['userid'];
    }
    if ($name[0] == "*") {//first char is * search in client code only
        $name = str_replace('*', '', $name);
        $queryString .= ' and conditions = 0 and clientcode LIKE "%' . $name . '%" order by clientid asc limit ' . $limit;
    } elseif ($name[0] == "i") {
        $name = (int) str_replace('i', '', $name);
        $queryString .= ' and conditions = 0 and clientid = ' . $name . ' order by clientid asc limit ' . $limit;
    } else {
        $queryString .= ' and conditions = 0 and (clientname LIKE "%' . $name . '%" or clientphone LIKE "%' . $name . '%" or clientmobile LIKE "%' . $name . '%" or clientid LIKE "%' . $name . '%" or clientcode LIKE "%' . $name . '%" or husbandNameObgy LIKE "%' . $name . '%") order by clientid asc limit ' . $limit;
    }

    $clients = $clientExt->queryAllWithQueryString($queryString);
    if ($no_add != 1) {
        $row_array['id'] = '-2';
        $row_array['text'] = 'اضافه عميل ';
        $row_array['clientdebt'] = '';
        array_push($return_arr, $row_array);
    }
    if (count($clients) > 0) {
        foreach ($clients as $client) {
            $row_array['id'] = $client->clientid;
            $clientName = $client->clientname;
            //when search for mobile show mobile beside name
            if (!empty($client->clientmobile) && !empty((int) $name) && is_integer((int) $name)) {
                $clientName .= ' - ' . $client->clientmobile;
            }
            $row_array['text'] = $clientName;
            $row_array['clientdebt'] = $client->clientdebt;
            array_push($return_arr, $row_array);
        }
    }
//print_r($clients);
    echo json_encode($return_arr);
}
## m7md
elseif ($do == "getpaymentnetworks") {
    $row_array = array();
    $return_arr = array();

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

    $paymentNetwork = $paymentNetworksDAO->queryByDeleted(0);

    foreach ($paymentNetwork as $client) {
        $row_array['id'] = $client->id;
        $row_array['text'] = $client->name;
        array_push($return_arr, $row_array);
    }

//print_r($clients);
    echo json_encode($return_arr);
}
## m7md
elseif ($do == "getBills") {
    $row_array = array();
    $return_arr = array();

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

    $bills = $billsEX->deleteByDeletedAndBillNo($billno);
    foreach ($bills as $bill) {
        $row_array['id'] = $bill->id;
        $row_array['text'] = $bill->billno;
        array_push($return_arr, $row_array);
    }

//print_r($clients);
    echo json_encode($return_arr);
}
## m7md
elseif ($do == "clientBills") {

    $client = $_POST['client_id'];

    $where = '';
    if ((isset($client) && $client != "-1")) {
        $where = ' clientid = ' . $client . ' ';
    }

    $clientBills = $billsEX->queryAllforcondemnedbills($where);

    $client_bills = array();
    foreach ($clientBills as $cli_bill_val) {

        $bill_id = $cli_bill_val->billno;
        $client_dept_change = $clientDeptChangeExt->sumByBillId($bill_id);

        $waitvalue = $cli_bill_val->waitvalue - $client_dept_change->clientdebtchangeamount; //# قيمة الدين

        if ($waitvalue > 0) {
            $client_bills[] = array(
                'id' => $cli_bill_val->id,
                'billno' => $bill_id,
                'finalnetbillvalue' => $cli_bill_val->finalnetbillvalue,
                'waitvalue' => $cli_bill_val->waitvalue - $client_dept_change->clientdebtchangeamount,
                'total_payed' => $cli_bill_val->cashvalue + $cli_bill_val->cardvalue + $cli_bill_val->companycarry + $client_dept_change->clientdebtchangeamount
            );
        }
    }

    $smarty->assign("client_bills", $client_bills);
    $smarty->display("billsview/client_bills.html"); //the template page
}
##
elseif ($do == "getproductdetails2") {
    $productId = filter_input(INPUT_POST, "productId");

    $productsData = $productExt->loadExt($productId);
    echo $productsData->sumProductQuantity;
}
##
elseif ($do == "getproductdetails") {
    $productId = filter_input(INPUT_POST, "productId");
    $priceType = filter_input(INPUT_POST, "priceType");
    $billType = filter_input(INPUT_POST, "billType"); //0 sell //1 buy

    $productsData = $productDAO->load($productId);

    if ($billType == "1") {
##شراء
        $programSetting = $programSettingDAO->load(1);
        if ($programSetting->lastprice == 0) {
            if (empty($productsData->lastbuyprice)) {
                $productsData->lastbuyprice = $productsData->productBuyPrice;
            }
            echo $productsData->lastbuyprice;
        } else {
            if (empty($productsData->meanbuyprice)) {
                $productsData->meanbuyprice = $productsData->productBuyPrice;
            }
            echo $productsData->meanbuyprice;
        }
    } else {
##بيع
//جملة
        if ($priceType == 0) {
            echo $productsData->productSellAllPrice;
        }
//تجزئة
        elseif ($priceType == 1) {
            echo $productsData->productSellUnitPrice;
        }
//نصف جملة
        elseif ($priceType == 2) {
            echo $productsData->productSellHalfPrice;
        }
    }
}
##
elseif ($do == "getservicecats") {
    $service = filter_input(INPUT_POST, "service");

    ##التصنيفات
    $catDataReport = getCategoryChilds(0, $service);
    $data = '';
    if (count($catDataReport) > 0) {
        foreach ($catDataReport[1] as $value) {
            $data .= '<option value="' . $value->productCatId . '">' . $value->productCatName . '</option>';
        }
    } else {
        $data .= '<option></option>';
    }
    echo $data;
}

##
elseif ($do == "checkdiscount") {

    $discType = filter_input(INPUT_POST, "discType");
    $discValue = filter_input(INPUT_POST, "discValue");
    $netBillValue = filter_input(INPUT_POST, "netBillValue");

    $userGroup = $userGroupDAO->load($_SESSION['usergroupid']);
    $percentageDiscount = $userGroup->percentageDiscount;
    $directDiscount = ($netBillValue * $userGroup->percentageDiscount) / 100;


    switch ($discType) {
        case 1 :
            if ($discValue > $directDiscount) {
                echo 9;
            }
            break;
        case 2 :
            if ($discValue > $percentageDiscount) {
                echo 9;
            }
            break;
    }
}

##
elseif ($do == "checkbillno") {
    $billNo = filter_input(INPUT_POST, "billNo");
    $edit = filter_input(INPUT_POST, "edit");
    $billId = filter_input(INPUT_POST, "billId");
    $billType = filter_input(INPUT_POST, "billType");

    if ($billType == 1) {
        if ($edit == 1) {
            $bills = $billsBuyEX->queryByBillNoAndNotId($billNo, $billId);
        }
##
        else {
            $bills = $billsBuyEX->queryByBillno($billNo);
        }
    } else {
        if ($edit == 1) {
            $bills = $billsEX->queryByBillNoAndNotId($billNo, $billId);
        }
##
        else {
            $bills = $billsDAO->queryByBillno($billNo);
        }
    }


    if (count($bills) > 0) {
        echo 0;
    } else {
        echo 1;
    }
}

##
elseif ($do == "billssearch") {
    $clientId = filter_input(INPUT_POST, "clientId");
    $billNo = filter_input(INPUT_POST, "billNo");
    $fromDate = filter_input(INPUT_POST, "fromDate");
    $toDate = filter_input(INPUT_POST, "toDate");

    $insuranceOnly = (int) filter_input(INPUT_POST, "insuranceOnly");
    $approved = (int) filter_input(INPUT_POST, "approved");

    if ($clientId == -1 && $billNo == -1 && empty($fromDate) && empty($toDate)) {
        $today = date('Y-m-d');
        $fromDate = date('Y-m-d', strtotime('-10 day', strtotime($today)));
    }


    $q1 = '';
    $q2 = '';
    $q3 = '';
    $q4 = '';
    $q5 = '';
    $msg = '';
    if ($clientId != -1) {
        $q1 = 'and clientid =' . $clientId . ' ';
        $client = $clientDAO->load($clientId);
        $msg .= "<b style='color: blue;'>اسم العميل : </b>" . $client->clientname . "&nbsp;&nbsp;&nbsp;";
    }
    if ($billNo != -1) {
        $q2 = 'and  billno  =' . $billNo . ' ';
        $msg .= "<b style='color: blue;'> رقم الفاتورة : </b>" . $billNo . "&nbsp;&nbsp;&nbsp;";
    }

    if ($insuranceOnly == 1) {
        $q5 = ' and insurance = 1 and approved = ' . $approved;
    }

    if ($fromDate && $toDate) {
        $q3 = 'and  billdate >= "' . $fromDate . ' 00-00-00" and billdate <= "' . $toDate . ' 23-59-55" ';
        $msg .= "<b style='color: blue;'> التاريخ من : </b>" . $fromDate . "&nbsp;&nbsp;&nbsp;";
        $msg .= "<b style='color: blue;'> التاريخ الى : </b>" . $toDate . "&nbsp;&nbsp;&nbsp;";
    } else {
        if ($fromDate) {
            $q3 = 'and  billdate  >= "' . $fromDate . ' 00-00-00" ';
            $msg .= "<b style='color: blue;'> التاريخ من : </b>" . $fromDate . "&nbsp;&nbsp;&nbsp;";
        }
        if ($toDate) {
            $q4 = 'and  billdate  <= "' . $toDate . ' 23-59-55"';
            $msg .= "<b style='color: blue;'> التاريخ الى : </b>" . $toDate . "&nbsp;&nbsp;&nbsp;";
        }
    }


    $q4 .= $q5;
    $bills = $billsEX->searchBills($q1, $q2, $q3, $q4);


    $totalBalance = 0;
    foreach ($bills as $bill) {
## client name
        $client = $clientDAO->load($bill->clientid);
        $bill->clientname = $client->clientname;
## user  name
        $user = $userDAO->load($bill->userid);
        $bill->username = $user->username;
        if ($bill->insurance == 1 && $q5 != "") {
## branch
            if ($bill->branchid == 0) {
                $bill->branchid = '';
            } else {
                $branch = $branchDAO->load($bill->branchid);
                $bill->branchid = $branch->branchName;
            }


## insurance company name
            $company = $insuranceCompanyDAO->load($bill->insurancecompanyid);
            $bill->insurancecompanyid = $company->name;
        }

        if ($bill->deleted == 0) {
            $totalBalance = $totalBalance + $bill->finalnetbillvalue;
        }
    }




## all result  bills total price    but not deleted
    $smarty->assign("totalBalance", $totalBalance);

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

    $smarty->assign("bills", $bills);
    $smarty->assign("billsCount", count($bills));

    $usergroup = $userGroupDAO->load($_SESSION['usergroupid']);
    $smarty->assign("usergroup", $usergroup);

    if ($insuranceOnly == 0) {
        $smarty->display("billsview/searchresult.html"); //the template page
    } else {
        if ($approved == 0) {
            $smarty->display("billsview/decide.html"); //the template page
        } else {
            $smarty->display("billsview/decidehistory.html"); //the template page
        }
    }
}
##
elseif ($do == "billssearchbuy") {
    $clientId = filter_input(INPUT_POST, "clientId");
    $billNo = filter_input(INPUT_POST, "billNo");
    $fromDate = filter_input(INPUT_POST, "fromDate");
    $toDate = filter_input(INPUT_POST, "toDate");

    if ($clientId == -1 && $billNo == -1 && empty($fromDate) && empty($toDate)) {
        $today = date('Y-m-d');
        $fromDate = date('Y-m-d', strtotime('-10 day', strtotime($today)));
    }


    $q1 = '';
    $q2 = '';
    $q3 = '';
    $q4 = '';
    $msg = '';
    if ($clientId != -1) {
        $q1 = 'and clientid =' . $clientId . ' ';
        $client = $supplierDAO->load($clientId);
        $msg .= "<b style='color: blue;'>اسم المورد : </b>" . $client->suppliername . "&nbsp;&nbsp;&nbsp;";
    }
    if ($billNo != -1) {
        $q2 = 'and  billno  =' . $billNo . ' ';
        $msg .= "<b style='color: blue;'> رقم الفاتورة : </b>" . $billNo . "&nbsp;&nbsp;&nbsp;";
    }

    if ($fromDate && $toDate) {
        $q3 = 'and  billdate  >= "' . $fromDate . ' 00-00-00" and billdate <= "' . $toDate . ' 23-59-55" ';
        $msg .= "<b style='color: blue;'> التاريخ من : </b>" . $fromDate . "&nbsp;&nbsp;&nbsp;";
        $msg .= "<b style='color: blue;'> التاريخ الى : </b>" . $toDate . "&nbsp;&nbsp;&nbsp;";
    } else {
        if ($fromDate) {
            $q3 = 'and  billdate  >= "' . $fromDate . ' 00-00-00" ';
            $msg .= "<b style='color: blue;'> التاريخ من : </b>" . $fromDate . "&nbsp;&nbsp;&nbsp;";
        }
        if ($toDate) {
            $q4 = 'and  billdate  <= "' . $toDate . ' 23-59-55"';
            $msg .= "<b style='color: blue;'> التاريخ الى : </b>" . $toDate . "&nbsp;&nbsp;&nbsp;";
        }
    }

    $bills = $billsBuyEX->searchBills($q1, $q2, $q3, $q4);

    $totalBalance = 0;
    foreach ($bills as $bill) {
## client name
        $client = $supplierDAO->load($bill->clientid);
        $bill->clientname = $client->suppliername;
## user  name
        $user = $userDAO->load($bill->userid);
        $bill->username = $user->username;

        if ($bill->deleted == 0) {
            $totalBalance = $totalBalance + $bill->finalnetbillvalue;
        }
    }




## all result  bills total price    but not deleted
    $smarty->assign("totalBalance", $totalBalance);

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

    $smarty->assign("bills", $bills);
    $smarty->assign("billsCount", count($bills));

    $usergroup = $userGroupDAO->load($_SESSION['usergroupid']);
    $smarty->assign("usergroup", $usergroup);

    $smarty->display("billsview/buybill/searchresult.html"); //the template page
}
##
elseif ($do == "getProducts") {
    $productsData = loadProductWithByName();
    $smarty->assign("productsData", $productsData);
}

##
elseif ($do == "checkcompanyname") {
    $companyName = filter_input(INPUT_POST, "companyName");
    $edit = filter_input(INPUT_POST, "edit");
    $companyId = filter_input(INPUT_POST, "companyId");


    if ($edit == 1) {
        $insuranceCompanies = $insuranceCompaniesEx->queryByNameAndNotId($companyName, $companyId);
    }
##
    else {
        $insuranceCompanies = $insuranceCompaniesDAO->queryByName($companyName);
    }


    if (count($insuranceCompanies) > 0) {
        echo 0;
    } else {
        echo 1;
    }
}

 elseif ($do == "restauranttable") {
    
    $name = $_POST['term'];
    $productsData = R::getAll("SELECT id, name as texts
    FROM restauranttable WHERE del = 0 and  id > 0 and name LIKE '%" . $name . "%' limit 200");
    $return_arr = array();
    foreach ($productsData as $pro) {
        $row_array = array();
        $row_array['id'] = $pro['id'];
        $row_array['text'] = $pro['texts'];
        array_push($return_arr, $row_array);
    }
    echo json_encode($return_arr);
}

 
##
elseif ($do == "loadkasfdetails") {
    $customerId = filter_input(INPUT_POST, "customerId");
    $result = array();

## last Kashf  details

    $lastDoctorKashf = $doctorKashfEX->getLastKashfByCustomerId($customerId);
    if ($lastDoctorKashf) {
        $result['lastDoctorKashfCount'] = 1;
        $result['lastDoctorKashf'] = $lastDoctorKashf;
    } else {
        $result['lastDoctorKashfCount'] = 0;
    }


    if (count($lastDoctorKashf) > 0 && $lastDoctorKashf->kashfid != 0) {
//$lastKashf = R::load('kashf', $lastDoctorKashf->kashfid);
        $lastKashf = $kashfDAO->load($lastDoctorKashf->kashfid);
//print_r($lastKashf);
        $result['kashfValue'] = $lastKashf->kashfvalue;
        $result['kashfInBill'] = $lastKashf->paystatus;
    }

    echo json_encode($result);
}
## m7md
elseif ($do == "loadkasfdetailsByKashfSerial") {
    $customerId = filter_input(INPUT_POST, "customerId");
    $kashf_serial = filter_input(INPUT_POST, "kashf_serial");

    $result = array();

    ## last Kashf  details

    $lastDoctorKashf = $doctorKashfEX->getLastKashfByCustomerIdAndKashfSerial($customerId, $kashf_serial);
    if ($lastDoctorKashf) {
        $result['lastDoctorKashfCount'] = 1;
        $result['lastDoctorKashf'] = $lastDoctorKashf;
    } else {
        $result['lastDoctorKashfCount'] = 0;
    }


    if (count($lastDoctorKashf) > 0 && $lastDoctorKashf->kashfid != 0) {
        //$lastKashf = R::load('kashf', $lastDoctorKashf->kashfid);
        $lastKashf = $kashfDAO->load($lastDoctorKashf->kashfid);
        //print_r($lastKashf);
        $result['kashfValue'] = $lastKashf->kashfvalue;
        $result['kashfInBill'] = $lastKashf->paystatus;
        $result['usedkashf'] = $lastKashf->used;
    }

    echo json_encode($result);
}
## m7md
elseif ($do == "getBillPrice") {
    $billno = filter_input(INPUT_POST, "billno");

    $billDetails = $billsDAO->queryByBillno($billno);
    $client_id = $billDetails[0]->clientid;

    $client_data = $clientDAO->load($client_id);
    $client_name = $client_data->clientname;
    $productstotalprice = $billDetails[0]->productstotalprice;
    $arr_container = array('client_id' => $client_id, 'client_name' => $client_name, 'productstotalprice' => $productstotalprice);
    // echo $client_name ;
    echo json_encode($arr_container);
}
##
elseif ($do == "checkstorequantity") {
    $productId = filter_input(INPUT_POST, "productId");
    $quantity = filter_input(INPUT_POST, "quantity");
    $storeId = filter_input(INPUT_POST, "storeId");
    $quantityOld = filter_input(INPUT_POST, "quantityOld");

    $storeDetail = $storeDetailEX->getProductQuantity($productId, $storeId);

    if ($storeDetail->productquantity >= ($quantity - $quantityOld )) {
        echo 1;
    }
##
    else {
        echo 99;
    }
}


###############################   payment network  ########################################
##
elseif ($do == "checknetworkname") {
    $networkName = filter_input(INPUT_POST, "networkName");
    $edit = filter_input(INPUT_POST, "edit");
    $networkId = filter_input(INPUT_POST, "networkId");
    $colName = filter_input(INPUT_POST, "colName");


    if ($edit == 1) {
        $paymentNetworks = $paymentNetworksEx->queryByNameAndNotId($networkName, $networkId, $colName);
    }
##
    else {
        $paymentNetworks = $paymentNetworksEx->queryByColName($networkName, $colName);
    }


    if (count($paymentNetworks) > 0) {
        echo 0;
    } else {
        echo 1;
    }
}

###############################   bills return ########################################
##
elseif ($do == "getbillsno") {
    $row_array = array();
    $return_arr = array();

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

    $billsNo = $billsEX->getAllBillNoDistinctSearch($name);
    if (count($billsNo) > 0) {
        foreach ($billsNo as $no) {
            $row_array['id'] = $no->billno;
            $row_array['text'] = $no->billno;
            array_push($return_arr, $row_array);
        }
    }
//print_r($return_arr);
    echo json_encode($return_arr);

//$smarty->assign("productsData", $productsData);
}

##
elseif ($do == "getbillDetail") {
    $bilNo = filter_input(INPUT_POST, "bilNo");


    $bills = $billsDAO->queryByBillno($bilNo);
    if ($bills[0]->insurance == 1) {
        echo '<div class="row">
  <div class="container">
    <div class="panel panel-default">

    <div class="panel-body"><div class="form-group">
            <label class="col-lg-2 control-label"> </label>
            <div class="col-lg-4">
                <p class="form-control-static"> لا يمكن عمل مرتجع لهذه الفاتورة لان الدفع تم عن طريق شركة التأمين </p>
            </div>
           </div>
           <div class="form-group">
<label class="col-lg-2 control-label"> </label>
            <div class="col-lg-4">
                <p class="form-control-static"> يمكنك حذف هذه الفاتورة وعمل فاتورة جديدة </p>
            </div>
           </div></div></div></div></div>';
    }
##
    else {
        getBillDetails($bills[0]->id);
        $smarty->display("billsreturnview/details.html"); //the template page
    }
}


##
elseif ($do == "billsreturnsearch") {
    $clientId = filter_input(INPUT_POST, "clientId");
    $billNo = filter_input(INPUT_POST, "billNo");
    $fromDate = filter_input(INPUT_POST, "fromDate");
    $toDate = filter_input(INPUT_POST, "toDate");

    $q1 = '';
    $q2 = '';
    $q3 = '';
    $q4 = '';

    if ($clientId != -1) {
        $q1 = 'and b.clientid =' . $clientId . ' ';
    }
    if ($billNo != -1) {
        $q2 = 'and  b.billno  =' . $billNo . ' ';
    }


    if ($fromDate && $toDate) {
        $q3 = 'and  r.date  >= "' . $fromDate . '" and r.date <= "' . $toDate . '" ';
    } else {
        if ($fromDate) {
            $q3 = 'and  r.date  >= ' . $fromDate . ' ';
        }
        if ($toDate) {
            $q4 = 'and  r.date  <= ' . $toDate . ' ';
        }
    }


    $billsReturn = $billsReturnEX->searchBills($q1, $q2, $q3, $q4);


    $totalBalance = 0;
    foreach ($billsReturn as $billR) {
## client name
        $client = $clientDAO->load($billR->clientid);
        $billR->clientname = $client->clientname;
## user  name
        $user = $userDAO->load($billR->userid);
        $billR->username = $user->username;

        if ($billR->deleted == 0) {
            $totalBalance = $totalBalance + $billR->returnedprice;
        }
    }

## all result  bills total price    but not deleted
    $smarty->assign("totalBalance", $totalBalance);

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

    $usergroup = $userGroupDAO->load($_SESSION['usergroupid']);
    $smarty->assign("usergroup", $usergroup);

    $smarty->display("billsreturnview/searchresult.html"); //the template page
}

##
elseif ($do == "rejectbill") {
    $billId = filter_input(INPUT_POST, "id");
    $bill = $billsDAO->load($billId);
    $bill->approved = 2;
    $billsDAO->update($bill);
    echo 1;
}
##
elseif ($do == "acceptbill") {
    $billId = filter_input(INPUT_POST, "acceptedBillId");
    $acceptanceNo = filter_input(INPUT_POST, "acceptanceNo");
    $bill = $billsDAO->load($billId);
    $bill->approved = 1;
    $bill->approveNo = $acceptanceNo;
    $bill->approveFile = "";
    if (isset($_FILES["acceptedFile"]["name"]) && $_FILES["acceptedFile"]["error"] != 4) {
        $handle = new upload($_FILES['acceptedFile']);
        $image = uploadImages2($handle, '../views/default/images/acceptedFile');
        $bill->approveFile = $image;
    }
    $billsDAO->update($bill);
    saveDailyEntry2($billId);
    $flag = affectBillProducts($billId, $bill->billdate);
    echo "1," . $flag;
}
##
elseif ($do == "notifseen") {
    $billId = filter_input(INPUT_POST, "id");
    $bill = $billsDAO->load($billId);
    $bill->notifSeen = 1;
    $billsDAO->update($bill);
    echo 1;
}
//# m7md
elseif ($do == "addclientDeptChange") {
    $id_pay = $_POST['id_pay'];

    //# to get number of rows and add 1 to it .
    $loaddata = $clientDeptChangeExt->queryAll();
    $load_last_row = end($loaddata);
    $todayx = (int) $load_last_row->clientdebtchangemodelid;
    $num = $todayx + 1;

    $client_id = $_POST['client_id'];
    $client = $clientDAO->load($client_id);
    $clientdebt = $client->clientdebt;
    $client_bills = array();

    foreach ($id_pay as $val) {
        $bill_no = $val[0];
        $pay = $val[1];
        $paytype_txt = $val[2];
        $paymentnetworks_id = $val[3];
        //# add to client dept change .
        $return_data = addclientDeptChange($client_id, $clientdebt, $num, $bill_no, $paytype_txt, $pay, $paymentnetworks_id);
        $clientdebtchangeid = $return_data[1];
        echo $clientdebtchangeid;

        //# for select data and print it .
        $where = ' billno = ' . $bill_no . ' ';

        $clientBills = $billsEX->queryAllforcondemnedbills($where);

        foreach ($clientBills as $cli_bill_val) {

            $bill_id = $cli_bill_val->billno;
            $client_dept_change = $clientDeptChangeExt->sumByBillId($bill_no);
            $client_dept_change_2 = $clientDeptChangeExt->lastByBillId($bill_no);

            $waitvalue = $cli_bill_val->waitvalue - $client_dept_change->clientdebtchangeamount; //# قيمة الدين
            //if( $waitvalue > 0 ){
            $client_bills[] = array(
                'id' => $cli_bill_val->id,
                'billno' => $bill_id,
                'finalnetbillvalue' => $cli_bill_val->finalnetbillvalue,
                'waitvalue' => $cli_bill_val->waitvalue - $client_dept_change->clientdebtchangeamount + $client_dept_change_2->clientdebtchangeamount,
                'total_payed' => $cli_bill_val->cashvalue + $cli_bill_val->cardvalue + $cli_bill_val->companycarry + $client_dept_change->clientdebtchangeamount - $client_dept_change_2->clientdebtchangeamount,
                'paytype' => $client_dept_change_2->paytype,
                'payed_val' => $client_dept_change_2->clientdebtchangeamount,
                'date' => $client_dept_change_2->clientdebtchangedate,
            );
            //}
        }



        //# update bill .
//        $bill = $billsDAO->queryByBillno($bill_no);
//        $bill[0]->cashvalue = $bill[0]->cashvalue + $pay;
//        $bill[0]->waitvalue =  $bill[0]->waitvalue - $pay;
//
//        $billsDAO->update($bill[0]);
    }
    $smarty->assign("client", $client);
    $smarty->assign("client_bills", $client_bills);

    $smarty->display("billsview/print_client_dept.html"); //the template page
}
#################### show bill  details ####################################################################################################
##

function getBillDetails($billId) {
    global $smarty;
    global $clientDAO;
    global $billsDAO;
    global $doctorKashfDAO;
    global $paymentNetworksDAO;
    global $billsReturnEX;
    global $billsProductsEX;

## bill data
    $bill = $billsDAO->load($billId);

## client name
    $client = $clientDAO->load($bill->clientid);
    $bill->clientname = $client->clientname;

## bill kashf
    $kashf = $doctorKashfDAO->load($bill->kashfid);
    $smarty->assign("kashf", $kashf);

## bill products
    $billProducts = getBillProducts($bill->id);

    //# calculate discount for this bill.
    $dis_val = 0;
    foreach ($billProducts as $value) {
        $dis_val += ( $value->productno * $value->productprice ) - $value->producttotalprice;
    }

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

    $smarty->assign("billProducts", $billProducts);
    $smarty->assign("billProductsCount", count($billProducts));

    $otherBillReturn = $billsReturnEX->returnedpriceSum($billId);
    $bill->finalnetbillvalue = $bill->finalnetbillvalue - $otherBillReturn->returnedprice;     ##اجمالى الفاتورة
## bill
    $smarty->assign("bill", $bill);
}

##

function getBillProducts($billId) {
    global $productDAO;
    global $productCatDAO;
    global $billsProductsEX;
    global $billsReturnProductsEX;

    $billProducts = $billsProductsEX->queryByBillIdAndDeleted($billId, 0);
    $i = 1;
    $categories;
    if (count($billProducts) > 0) {
        foreach ($billProducts as $pro) {
            $product = $productDAO->load($pro->productid);
            $parentId = $product->productCatId;
            $pathArr = getProductPath_recursive($parentId, $categories);
            $pro->productName = $product->productName . '/' . $pathArr;
###################################################################################################################################
            $productReturned = $billsReturnProductsEX->queryByBillIdAndProductidAndDeleted($billId, $pro->id, $pro->productid, 0);
            $pro->netproductno = 0;
            $pro->retproductno = 0;
            if (count($productReturned) > 0) {
                foreach ($productReturned as $retPro) {
                    $pro->retproductno = $pro->retproductno + $retPro->productno;
                }
            }

            $pro->netproductno = $pro->productno - $pro->retproductno;
        }
    }

    return $billProducts;
}

##

function getProducts() {
    global $productExt;
    global $productCatDAO;
    global $smarty;
    $categories;
    $productsData = $productExt->queryAllExt();
    if (count($productsData) > 0) {
        $i = 0;
        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
//print("parentId: ".$parentId."");
            $pathArr = fetch_recursive($parentId, $categories);
            $smarty->assign("names" . $i, $pathArr);
            $pro->userId = $pathArr;
            $i++;
        }
    }
    return $productsData;
}

function fetch_recursive($parentid, $categories) {
    global $productCatExt;
//print($parentid."<br>");
    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);
//print_r($catData);
    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;

        if ($newParentId != 0 && isset($newParentId)) {
//$newParentName = $catData->parentName;
//$categories .= $newParentName.'/';
            return fetch_recursive($newParentId, $categories);
        }
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}

function loadProductWithByName() {
    global $productExt;
    global $productCatExt;
    global $catsIDS;
    global $lastLevelCatIDS;

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

    $name = $_GET['term']; //It could be product name or category name
    $limit = intval($_GET['page_limit']);
    $storeid = $_REQUEST["storeid"];
    $service = $_REQUEST["serviceid"];
    $hiddenpricetype = $_REQUEST["pricetype"];

////    //when choosing service
////    if (!empty($service) && $service != -1) {
////        //going to get products by its main cat that has the service
////        ##التصنيفات
////        $catDataReport = getCategoryChilds(0, $service);
////        $proids = '0,';
////        $name_QS = '';
////        if (!empty($name)) {
////            $name_QS = ' and product.productName LIKE "%' . $name . '%" ';
////        }
////        foreach ($catDataReport[1] as $mycatId) {
////
////            $catsIDS = '' . $mycatId->productCatId;
////            getAllSubCat($mycatId->productCatId, 1); //mode = 1 get all sub cats
////            $productsOfCat = $productExt->queryByProductCatIdIn($catsIDS, $name_QS);
////            foreach ($productsOfCat as $value) {
////                $proids .= $value->productId . ',';
////            }
////        }
////        $proids = rtrim($proids, ",");
////        $productsData = $productExt->queryByIdsInExt($proids, $storeid);
////    } else {
    //going to search in products and cats
    $proids = '0,';
    $productsIds = $productExt->getIdsOfProductsLike($name);
    foreach ($productsIds as $value) {
        $proids .= $value->productId . ",";
    }
    $categoriesIds = $productCatExt->getIdsOfCatsLike($name);
    foreach ($categoriesIds as $mycatId) {

        $catsIDS = '' . $mycatId->productCatId;
        getAllSubCat($mycatId->productCatId, 1); //mode = 1 get all sub cats
        $productsOfCat = $productExt->queryByProductCatIdIn($catsIDS);
        foreach ($productsOfCat as $value) {
            $proids .= $value->productId . ',';
        }
    }
    $proids = rtrim($proids, ",");
    $productsData = $productExt->queryByIdsInExt($proids, $storeid);
////    }
//$productsData = $productExt->queryByNameExtWithoutLimit2($name, $storeid);
    if (count($productsData) > 0) {


        foreach ($productsData as $pro) {
            $parentId = $pro->productCatId;
//names of product's parents
            $pathArr = fetch_recursive($parentId, $categories);

//send product id and product name as something that select2 expects.
            $row_array['id'] = $pro->productId;
            $row_array['text'] = $pro->productName . '/' . $pathArr;


            $row_array['productquantity'] = $pro->productquantity;


//جملة
            if ($hiddenpricetype == 0) {

                $price = 'productSellAllPrice';
                $row_array['price'] = $pro->productSellAllPrice;
            }
//تجزئة
            elseif ($hiddenpricetype == 1) {
                $price = 'productSellUnitPrice';
                $row_array['price'] = $pro->productSellUnitPrice;
            }
//نصف جملة
            elseif ($hiddenpricetype == 2) {
                $price = 'productSellHalfPrice';
                $row_array['price'] = $pro->productSellHalfPrice;
            }

            array_push($return_arr, $row_array);
        }
    }


//print_r($return_arr);
    echo json_encode($return_arr);
}

function getProductPath_recursive($parentid, $categories) {
    global $productCatExt;

    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);

    if (count($catData) > 0) {
        $categories .= $catData->productCatName . '/';
        $newParentId = $catData->productCatParent;

        return getProductPath_recursive($newParentId, $categories);
    }
    $categories = substr($categories, 0, strlen($categories) - 1);
    return $categories;
}

function getAllSubCat($catid, $mode) {
    global $productCatExt;
    global $productCatDAO;
    global $catsIDS;
    global $lastLevelCatIDS;
//mode = 1 get all sub cats
//mode = 2 get last level cats

    $result = $productCatExt->queryByParentExt($catid);
    if (count($result) > 0) {
        foreach ($result as $data) {
            if ($mode == 1) {
                $catsIDS .= "," . $data->productCatId;
                getAllSubCat($data->productCatId, $mode);
            } elseif ($mode == 2) {
                $childData = $productCatExt->queryByParentExt($data->productCatId);
                if (count($childData) > 0) {
                    getAllSubCat($data->productCatId, $mode);
                } else {
                    if (!empty($data->productCatId)) {
                        array_push($lastLevelCatIDS, $data->productCatId);
                    }
                }
            }
        }
    } else {
//        if ($mode == 2) {
//            $childData = $productCatExt->queryByParentExt($data->productCatId);
//            if (count($childData) > 0) {
//                getAllSubCat($data->productCatId, $mode);
//            } else {
//                if (!empty($data->productCatId)) {
//                    array_push($lastLevelCatIDS, $data->productCatId);
//                }
//            }
//        }
    }
}

function getCategoryChilds($parentid = 0, $service = -1) {
    global $productCatExt;
    global $productCatDAO;

    $serviceQS = '';
    if (!empty($service) && $service != -1) {
        $serviceQS = ' and ( opticServices = "" or opticServices LIKE "%' . $service . '%") ';
    }
    //load cat
    $parentobject = $productCatDAO->load($parentid);
    $childsArray = $productCatExt->getChilds($parentid, $serviceQS);

    return array($parentobject, $childsArray);
}

//fatma
function saveDailyEntry2($billId) {
    global $dailyEntry;      ## Dailyentry
    global $accountsTreeDAO;
    global $client;
    global $clientDAO;
    global $mySave;
    global $mySaveDAO;
    global $insuranceCompaniesDAO;
    global $paymentNetworksDAO;
    global $billsDAO;
    $total = 0;

    $ex1 = '';
    $ex2 = '';
    $ex3 = '';
    $ex4 = '';
    $ex5 = '';

    $mytransactions = new Transaction();
    $bills = $billsDAO->load($billId);
    $client = $clientDAO->load($bills->clientid);
    $mySave = $mySaveDAO->load($bills->saveid);

    $dailyEntryDebtorArray = array();
    $dailyEntryCreditorArray = array();

    $dailyEntry->dDateTime = $bills->serverdate;
    $dailyEntry->entryComment = 'اضافة فاتورة ';
    $dailyEntry->fromFlag = 2;
    $dailyEntry->reverseofid = -9;

    $payType = $bills->payType;

    switch ($payType) {
        case 'normal_bill':
            $bill_name = "  فاتورة بصريات عادية";
            break;
        case 'cate_bill':
            $bill_name = "  فاتورة بصريات مصنفة";
            break;
        case 'ins':
            $bill_name = "  فاتورة بصريات مصنفة تأمين";
            break;
        case 'cash':
            $bill_name = "  فاتورة بصريات مصنفة كاش";
            break;

        default:
            break;
    }
    $bill_name .= " -- ";
    if ($bills->kashftype == -1) {
        $bill_name .= " بدون كشف ";
    } elseif ($bills->kashftype == 0) {
        $bill_name .= " بكشف داخلى ";
    } elseif ($bills->kashftype == 1) {
        $bill_name .= " بكشف خارجى ";
    } elseif ($bills->kashftype == 0) {
        $bill_name .= " كشف ";
    }
    $bill_name .= " (  ";
    if ($bills->cash == 1) {
        $bill_name .= " كاش= " . $bills->cashvalue . "  &nbsp&nbsp";
    }
    if ($bills->insurance == 1) {
        $bill_name .= " تأمين= " . ($bills->customercarry + $bills->companycarry) . "  &nbsp&nbsp";
    }
    if ($bills->card == 1) {
        $bill_name .= " شبكة= " . $bills->cardvalue . "  &nbsp&nbsp";
    }
    if ($bills->waitvalue > 0) {
        $bill_name .= " اجل= " . $bills->waitvalue;
    }
    $bill_name .= " )";

    if ($bills->wait != 0) {
        $clientId = $bills->clientid;


        if ($client->treeId > 0) {
            $treeId1 = $client->treeId;
        } else {
            $treeId1 = addTreeElement($client->clientname, 23, 3, 0, 1, '', 0, 0);
        }



        $dailyEntryDebtor1->value = $waitvalue;
        $dailyEntryDebtor1->accountstreeid = $treeId1;
        $dailyEntryDebtor1->pluginControllerName = 'bills.php';
        $dailyEntryDebtor1->pluginComment = $bill_name;
        $dailyEntryDebtor1->pluginid = $billId;
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor1);
        $total = $total + $waitvalue;
    }
#########################################################################################
    if ($bills->cash == 1) {

        if ($mySave->treeId > 0) {
            $treeId2 = $mySave->treeId;
        } else {
            $treeId2 = addTreeElement($mySave->savename, 20, 3, 0, 1, '', 0, 0);
        }

        $dailyEntryDebtor2->value = $bills->cashvalue;
        $dailyEntryDebtor2->accountstreeid = $treeId2;
        $dailyEntryDebtor2->pluginControllerName = 'bills.php';
        $dailyEntryDebtor2->pluginComment = $bill_name;
        $dailyEntryDebtor2->pluginid = $billId;
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor2);
        $total = $total + $bills->cashvalue;
    }
#########################################################################################
    if ($bills->insurance == 1) {
        $insuranceCompanies = $insuranceCompaniesDAO->load($bills->insurancecompanyid);

        $insValue = $bills->companycarry;
        $insDiscount = $insValue * ($bills->insdiscountpercent) / 100;
        $insRest = $insValue - $insDiscount;

############# insurance
        $accountsTree33 = $accountsTreeDAO->queryByName($insuranceCompanies->name);
        if (count($accountsTree33) > 0) {
            $treeId3 = $accountsTree33[0]->id;
        } else {
            $treeId3 = addTreeElement($insuranceCompanies->name, 40, 3, 0, 1, '', 0, 0);
        }


        $dailyEntryDebtor3->value = $insRest;
        $dailyEntryDebtor3->accountstreeid = $treeId3;
        $dailyEntryDebtor3->pluginControllerName = 'bills.php';
        $dailyEntryDebtor3->pluginComment = $bill_name;
        $dailyEntryDebtor3->pluginid = $billId;
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor3);

############# insurance  discount

        $accountsTree7 = $accountsTreeDAO->queryByName('خصم ' . $insuranceCompanies->name);
        if (count($accountsTree7) > 0) {
            $treeId7 = $accountsTree7[0]->id;
        } else {
            $treeId7 = addTreeElement('خصم ' . $insuranceCompanies->name, 36, 0, 0, 1, '', 0, 0);
        }


        $dailyEntryDebtor7->value = $insDiscount;
        $dailyEntryDebtor7->accountstreeid = $treeId7;
        $dailyEntryDebtor7->pluginControllerName = 'bills.php';
        $dailyEntryDebtor7->pluginComment = $bill_name;
        $dailyEntryDebtor7->pluginid = $billId;
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor7);
#############
        $total = $total + $bills->companycarry;
    }
#########################################################################################
    if ($bills->card == 1) {
        $networkId = $bills->insurancecompanyid;
        $paymentNetworks = $paymentNetworksDAO->load($networkId);


        $cardValue = $bills->cardvalue;
        $cardDiscount = $cardValue * ($bills->netdiscountpercent) / 100;
        $cardRest = $cardValue - $cardDiscount;

## network
        $accountsTree44 = $accountsTreeDAO->queryByName($paymentNetworks->name);
        if (count($accountsTree44) > 0) {
            $treeId4 = $accountsTree44[0]->id;
        } else {
            $treeId4 = addTreeElement($paymentNetworks->name, 41, 3, 0, 1, '', 0, 0);
        }



        $dailyEntryDebtor4->value = $cardRest;
        $dailyEntryDebtor4->accountstreeid = $treeId4;
        $dailyEntryDebtor4->pluginControllerName = 'bills.php';
        $dailyEntryDebtor4->pluginComment = $bill_name;
        $dailyEntryDebtor4->pluginid = $billId;
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor4);

## network  discount

        $accountsTree55 = $accountsTreeDAO->queryByName('رسوم ' . $paymentNetworks->name);
        if (count($accountsTree55) > 0) {
            $treeId5 = $accountsTree55[0]->id;
        } else {
            $treeId5 = addTreeElement('رسوم ' . $paymentNetworks->name, 37, 0, 0, 1, '', 0, 0);
        }



        $dailyEntryDebtor5->value = $cardDiscount;
        $dailyEntryDebtor5->accountstreeid = $treeId5;
        $dailyEntryDebtor5->pluginControllerName = 'bills.php';
        $dailyEntryDebtor5->pluginComment = $bill_name;
        $dailyEntryDebtor5->pluginid = $billId;
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor5);


        $total = $total + $bills->cardvalue;
    }

#########################################################################################
    $dailyEntryCreditor->value = $total;
    $dailyEntryCreditor->accountstreeid = 16;
    $dailyEntryCreditor->pluginControllerName = 'bills.php';
    $dailyEntryCreditor->pluginComment = $bill_name;
    $dailyEntryCreditor->pluginid = $billId;
    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);


    try {
        $_SESSION['client_id'] = $bills->clientid;
        $data = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
        $dailyEntryId = $data[1];

        //savedaily only happen when there is cash in the money
        //add other cases manually
        $cash_val = (float) filter_input(INPUT_POST, $ex1 . "cashValue");
        $non_cash_values = $total - $cash_val;
        if ($cash_val == 0) {
            //insertsavedaily
            insertSavedaily($mySave->savecurrentvalue, 0, 0, $mySave->saveid, $bill_name, $bills->id, $mySave->savecurrentvalue, "bills.php");
        }
        unset($_SESSION['client_id']);

        //Clientdebtchange only happen when there is remain in the money
        //add other cases manually
        if ($waitvalue == 0) {
            $non_wait_values = $total - $waitvalue;
            insertClientdebtchangeupdate($bills->clientid, $client->clientdebt, 0, 0, $bill_name, $bills->id, $bill_name, "bills.php", $bill_name, $total, date("Y-m-d", strtotime($bills->billdate)), 0);
        }



        $bills->dailyentryid = $dailyEntryId;
        $billsDAO->update($bills);
        $mytransactions->commit();
        $flag = 0;
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $flag = 1;
    }
    return $flag; //1 حدث خطأ
}

//fatma
function affectBillProducts($billId, $billDate) {
    global $billsProductsDAO;
    global $productDAO;
    global $storeDetailDAO;
    global $storeDetailEX;
    $flag = 0;
    $offline = 0;
    $billsProducts = $billsProductsDAO->queryByBillid($billId);
    foreach ($billsProducts as $value) {
        $detailId = $value->id;
        $productId = $value->productid;
        $storeId = $value->storeid;
        $productNum = $value->productno;
        lastAndMeanBuyPrice_SellOptic($detailId, $productId);
        $product = $productDAO->load($productId);
        if ($product->isService != 1) {
            $storeDetail = $storeDetailEX->getProductQuantity($productId, $storeId);
            $productbefore = $storeDetail->productquantity;
            $productafter = $productbefore - $productNum;
            $storeDetail->productquantity = $productafter;
            $storeDetailDAO->update($storeDetail);
            if ($storeDetail->productquantity < 0) {
                $flag = 1;
            }
            insertStorereportupdate($productId, $storeId, $productNum, $productbefore, $productafter, 1, $billId, "اضافة فاتورة مبيعات", "bills.php", $billDate, $offline);
        }
    }
    return $flag; //1 الكمية بالمخزن لا تكفى
}

//fatma
function lastAndMeanBuyPrice_SellOptic($detailId, $productId) {

    global $productDAO;
    global $billsProductsEX;

##the differance
## use $buyProduct->lastbuyprice and $buyProduct->meanbuyprice and put them in sell table
    $buyProduct = new Product();

##1- get mean
    $buyProduct = $productDAO->load($productId);
    if ($buyProduct->meanbuyprice == NULL || $buyProduct->meanbuyprice == 0) {
        $buyProduct->meanbuyprice = $buyProduct->productBuyPrice;
    }
    if ($buyProduct->lastbuyprice == NULL || $buyProduct->lastbuyprice == 0) {
        $buyProduct->lastbuyprice = $buyProduct->productBuyPrice;
    }

    if (isset($detailId) && !empty($detailId)) {
        $billsProductsEX->updatePrices_f_optic($buyProduct->lastbuyprice, $buyProduct->meanbuyprice, $detailId);
    }
}

//fatma
//add in Storemovement tbl
function insertStorereportupdate($productid, $storeid, $productChangeAmount, $productbefore, $productafter, $storereporttype, $storereportmodelid, $processname, $tablename, $mydate, $offline) {
    global $myStorereport;
    global $myStorereportRecord;

    if ($offline == 1) {
        $ex1 = 'bill_';
        $myStorereport->userid = filter_input(INPUT_POST, $ex1 . "userid");
    } else {
        $myStorereport->userid = $_SESSION['userid'];
    }



    $myStorereport->processname = $processname;
    $myStorereport->productafter = $productafter;
    $myStorereport->productbefore = $productbefore;
    $myStorereport->productquantity = $productChangeAmount;
    $myStorereport->productid = $productid;
    $myStorereport->storeid = $storeid;
    $myStorereport->storereportdate = $mydate;
    $myStorereport->storereportmodelid = $storereportmodelid;
    $myStorereport->storereporttype = $storereporttype;
    $myStorereport->tablename = $tablename;
//    $myStorereport->userid = $_SESSION['userid'];

    $myStorereportRecord->insert($myStorereport);
}

//# m7md
// add in clientDeptChange tbl
function addclientDeptChange($client_id, $clientdebt, $num, $bill_no, $paytype_txt, $pay, $paymentnetworks_id) {
    global $clientExt;
    global $clientDAO;
    global $client;
    global $clientDeptChange;
    global $clientDeptChangeDAO;
    global $today;

    //Dailyentry
    global $dailyEntry;
    global $dailyEntryDAO;

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

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

    //Dailyentrydebtor مدين
    global $dailyEntryDebtor_2;

    global $accountsTreeDAO;
    global $accountsTree;

    //save
    global $mySave;
    global $mySaveDAO;
    global $paymentNetworksDAO;


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


        $clientid = $client_id;
        //$lastDate = $_POST["lastDate"];
        //$currentDate = $_POST["currentDate"];
        $debtBefore = $clientdebt;
        $payedDept = $pay;
        //$debtAfter = $_POST["debtAfter"];
        $voucher = $num;
        $comment = $_POST["comment"];
        $today = date("Y-m-d");

        if (isset($clientid) && $clientid != '-1') {
            $client = $clientDAO->load($clientid);
            //update current dept in client tbl
            $debtAfter = $client->clientdebt - $payedDept;
            $client->clientdebt = $debtAfter;
            $client->userid = $_SESSION['userid'];
            $client->clientdate = $today;
            $client->clientid = $clientid;

            $clientExt->updatedept($client);

            //insert into supplierdeptchange tbl
            $clientDeptChange->comment = $comment;
            $clientDeptChange->processname = "سداد ديون عميل";
            $clientDeptChange->clientdebtchangeafter = $debtAfter;
            $clientDeptChange->clientdebtchangeamount = $payedDept;
            $clientDeptChange->clientdebtchangebefore = $debtBefore;
            $clientDeptChange->clientdebtchangeafter = $debtBefore - $payedDept;
            $clientDeptChange->clientdebtchangedate = $today;
            $clientDeptChange->clientdebtchangemodelid = $voucher;
            $clientDeptChange->clientdebtchangetype = 0;
            $clientDeptChange->tablename = "clientPayedDeptReportController.php";
            $clientDeptChange->userid = $_SESSION['userid'];
            $clientDeptChange->clientid = $clientid;
            $clientDeptChange->dailyentryid = 0;
            $clientDeptChange->num = $num;
            $clientDeptChange->billid = $bill_no;
            $clientDeptChange->paytype = $paytype_txt;


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

            //update save's current value
            //get saveVsalue before and saveValue after plus payedDept
            $valueData = getSaveValueAndPlus($payedDept);

            //  print_r($valueData);
            if (count($valueData) > 0) {
                $saveId = $valueData[0];
                $saveValuebefore = $valueData[1];
                $saveValueafter = $valueData[2];

                //update save value after payedDept
                updateSave($saveId, $saveValueafter);
                //insert into savedaily tbl
                insertSavedaily($saveValuebefore, $payedDept, 0, $saveId, "سداد ديون عميل", $clientdebtchangeId, $saveValueafter, "clientPayedDeptController.php");
            }
        }
        $clientData = $clientDAO->load($clientid);

        $dailyEntry->entryComment = 'اضافة ايصال سداد للعميل ' . $clientData->clientname;

        //# نوع الدفع شبكة
        $payedDept_discount = 0;
        if ($paymentnetworks_id != 0) {

            // start paymentnetworks
            $paymentnetworks_data = $paymentNetworksDAO->load($paymentnetworks_id);
            $discountpercent = $paymentnetworks_data->discountpercent;
            $payedDept_discount = ($discountpercent / 100) * $payedDept;
            $dailyEntryDebtor_2->value = $payedDept_discount;

            $treepaymentnetworks = $accountsTreeDAO->queryByName($paymentnetworks_data->name);
            $treeId = $treepaymentnetworks[0]->id;
            $dailyEntryDebtor_2->accountstreeid = $treeId;
            /// end paymentnetworks
        }

        // start save
        $dailyEntryDebtorArray = array();
        $dailyEntryDebtor->value = $payedDept - $payedDept_discount;
        $saveid = $_SESSION['saveid'];
        $dataSave = $mySaveDAO->load($saveid);

        $idTreeSave = $dataSave->treeId;
        if (empty($idTreeSave)) {
            $idTreeSave = addTreeElement($dataSave->savename, 20, 3, 0, 1, '', 0, 0);
        }
        $dailyEntryDebtor->accountstreeid = $idTreeSave;
        /// end save
        //
        /// start L 7sab L da2non
        $dailyEntryCreditorArray = array();
        $dailyEntryCreditor->value = $payedDept;
        $oldClient = $clientDAO->load($clientid);
        $treeId = $oldClient->treeId;
        // print_r($treeId . 'aaaaaaaaaaaaa');
        $dailyEntryCreditor->accountstreeid = $treeId;
        /// end L 7sab L da2non

        array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

        if ($paymentnetworks_id != 0) {
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor, $dailyEntryDebtor_2);
        } else {
            array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
        }


        $returnedData = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
        $did = $returnedData[1];

        $rowData = $clientDeptChangeDAO->load($clientdebtchangeId);

        $clientDeptChange->comment = $rowData->comment;
        $clientDeptChange->processname = $rowData->processname;
        $clientDeptChange->clientdebtchangeafter = $rowData->clientdebtchangeafter;
        $clientDeptChange->clientdebtchangeamount = $rowData->clientdebtchangeamount;
        $clientDeptChange->clientdebtchangebefore = $rowData->clientdebtchangebefore;
        $clientDeptChange->clientdebtchangedate = $rowData->clientdebtchangedate;
        $clientDeptChange->clientdebtchangemodelid = $rowData->clientdebtchangemodelid;
        $clientDeptChange->clientdebtchangetype = $rowData->clientdebtchangetype;
        $clientDeptChange->tablename = $rowData->tablename;
        $clientDeptChange->userid = $rowData->userid;
        $clientDeptChange->clientid = $rowData->clientid;
        $clientDeptChange->dailyentryid = $did;
        $clientDeptChange->num = $rowData->num;
        $clientDeptChange->billid = $rowData->bill_no;
        $clientDeptChange->paytype = $rowData->paytype_txt;

        $clientDeptChangeDAO->update($clientDeptChange);

        $add_print = filter_input(INPUT_POST, 'add_print');

        $data_arr = array($add_print, $clientdebtchangeId);



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


    return $data_arr;
}

// get initialvalue and plus from save tbl
function getSaveValueAndPlus($savevaluechanged) {

    //to use the variable out side the funcion
    global $mySave;
    global $mySaveDAO;

    $saveData = $mySaveDAO->load($_SESSION['saveid']);
    $saveId = $saveData->saveid;
    $saveValuebefore = $saveData->savecurrentvalue;

    $saveValueafter = $saveValuebefore + $savevaluechanged;

    return array($saveId, $saveValuebefore, $saveValueafter);
}

// update Save tbl
function updateSave($saveid, $savevalueafter) {
    global $mySave;
    global $mySaveExt;

    //update savecurrentvalue in Save tbl
    $mySave->savecurrentvalue = $savevalueafter;
    $mySave->userid = $_SESSION['userid'];
    $mySave->saveid = $saveid;
    //$mySaveExt->updateSaveValue($mySave);
}

// insert data into Clientdebtchange tbl
function insertClientdebtchangeupdate($clientid, $clientdebtchangebefore, $clientdebtchangeamount, $clientdebtchangetype, $processname, $clientdebtchangemodelid, $clientdebtchangeafter, $tablename, $comment, $totalOperationCost, $mydate, $offline) {

    //to use the variable out side the funcion
    global $myClientdebtchange;
    global $myClientdebtchangeRecord;

    $myClientdebtchange->clientdebtchangeafter = $clientdebtchangeafter;
    $myClientdebtchange->clientdebtchangeamount = $clientdebtchangeamount;
    $myClientdebtchange->clientdebtchangebefore = $clientdebtchangebefore;
    $myClientdebtchange->clientdebtchangedate = $mydate; //date("Y-m-d");
    $myClientdebtchange->clientdebtchangemodelid = $clientdebtchangemodelid;
    $myClientdebtchange->clientdebtchangetype = $clientdebtchangetype;
    $myClientdebtchange->clientid = $clientid;
    $myClientdebtchange->comment = $comment;
    $myClientdebtchange->processname = $processname;
    $myClientdebtchange->tablename = $tablename;
    $myClientdebtchange->totalOperationCost = $totalOperationCost;
    $myClientdebtchange->dailyentryid = 0;


    if ($offline == 1) {
        $ex1 = 'bill_';
        $myClientdebtchange->userid = filter_input(INPUT_POST, $ex1 . "userid");
    } else {
        $myClientdebtchange->userid = $_SESSION['userid'];
    }



    $myClientdebtchangeRecord->insert($myClientdebtchange);
}

// insert in Savedaily tbl
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) {
    global $saveDaily;
    global $saveDailyDAO;

    //insert in Savedaily tbl
    $saveDaily->savedailydate = date("Y-m-d");
    $saveDaily->userid = $_SESSION['userid'];
    $saveDaily->savedailysavebefore = $savedailysavebefore;
    $saveDaily->savedailychangeamount = $savedailychangeamount;
    $saveDaily->savedailychangetype = $savedailychangetype;
    $saveDaily->saveid = $saveid;
    $saveDaily->processname = $processname;
    $saveDaily->savedailymodelid = $savedailymodelid;
    $saveDaily->savedailysaveafter = $savedailysaveafter;
    $saveDaily->tablename = $tablename;
    if (isset($_SESSION['client_id']) && !empty($_SESSION['client_id'])) {
        $saveDaily->clientid = $_SESSION['client_id'];
    } else {
        $saveDaily->clientid = 0;
    }
    $saveDailyDAO->insert($saveDaily);
}

?>