<?php

include("../public/include_dao.php");
include("../library/uploadImages.php");

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

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

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

//user
$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();



//Branch
$Branch = new Branch();
$BranchDAO = new BranchMySqlDAO();
$BranchEX = new BranchMySqlExtDAO();

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


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

//Store
$myStoreRecord = new StoreMySqlDAO();

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


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

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

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



//Dailyentry
$dailyEntry = new Dailyentry();

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

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

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

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

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

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

function updateClientDebt($clientid, $clientdebtAfter, $offline) {
    //to use the variable out side the funcion
    global $client;
    global $clientExt;

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

    //update clientdebt in client tbl

    $client->clientdebt = $clientdebtAfter;
    $client->clientid = $clientid;

    $clientExt->updateClientdebt($client);
}

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

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

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

function loadStore() {
    global $myStoreRecord;

    // select all data from Storetbl
    $storeData = $myStoreRecord->queryByConditions(0);
    return $storeData;
}

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

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;
    $catData = $productCatExt->getCategoryAndParentByCatId($parentid);
    //print_r($catData);
    if (count($catData) > 0) {
        $categories .= '/' . $catData->productCatName;
        //print("<br>categories: ".$categories."<br>");
        //print_r($catData);
        $newParentId = $catData->productCatParent;
        //print("newParentId: ".$newParentId."<br><br>");
        if ($newParentId != 0 && count($catData) > 0) {
            $newParentName = $catData->parentName;
            $categories .= '/' . $newParentName;
            fetch_recursive($newParentId, $categories);
        }
    }
    return $categories;
}

function getClientData() {
    global $clientExt;

    $alldata = $clientExt->queryAllsup();
    return $alldata;
}

#################### add  bill ####################################################################################################

function add($offline) {
    $detailResult = saveBillDetails($offline);   ## $offline ->    0 online   , 1 offline

    if ($detailResult['flag'] == 0) {
        $billId = $detailResult['billId'];
        $flag = saveBillProducts($billId, $offline);
    }

    return array($flag, $billId, $detailResult);
}

function saveBillDetails($offline) {
    global $bills;
    global $billsDAO;
    global $doctorKashf;
    global $doctorKashfEX;
    global $doctorKashfDAO;
    global $clientDAO;
    global $kashf;
    global $kashfDAO;

    $detailResult = array();
    $detailResult['flag'] = 0;         ## done
    $detailResult['note'] = '';
    $detailResult['noteen'] = '';

    if ($offline == 1) {
        $ex1 = 'bill_';
        $ex2 = 'product_';
        $ex3 = 'doctorkashf_';
        $ex4 = 'kashf_';
        $ex5 = 'client_';
    } else {
        $ex1 = '';
        $ex2 = '';
        $ex3 = '';
        $ex4 = '';
        $ex5 = '';
    }


    $clientId = filter_input(INPUT_POST, $ex1 . "client");
    $receiveDate = filter_input(INPUT_POST, $ex1 . "receivedate");
    $billNo = filter_input(INPUT_POST, $ex1 . "billno");
    $comment = filter_input(INPUT_POST, $ex1 . "comment");
    $billDate = filter_input(INPUT_POST, $ex1 . "billdate");
    $kashftype = filter_input(INPUT_POST, $ex1 . "kashftype");
    $pricetype = filter_input(INPUT_POST, $ex1 . "pricetype");
    $approvalNo = filter_input(INPUT_POST, $ex1 . "approvalNo");
    $allowedDays = (!filter_input(INPUT_POST, $ex1 . "allowedDays")) ? 0 : filter_input(INPUT_POST, $ex1 . "allowedDays");


    $productstotalprice = filter_input(INPUT_POST, $ex1 . "totalBillPrice");   ## إجمالي المشتريات
    $kashfvalue = filter_input(INPUT_POST, $ex1 . "kashfValue");      ##  قيمة الكشف
    $kashfdiscount = filter_input(INPUT_POST, $ex1 . "kashDiscValue");      ##    خصم الكشف
    $netbillvalue = filter_input(INPUT_POST, $ex1 . "netBillValue");      ##  الاجمالى
    $discounttype = filter_input(INPUT_POST, $ex1 . "discType");      ##  نوع الخصم     1 direct   , 2 percent
    $discountvalue = filter_input(INPUT_POST, $ex1 . "discValue");      ##   قيمة الخصم
    $finalnetbillValue = filter_input(INPUT_POST, $ex1 . "netValue");      ## الصافى
    $waitvalue = filter_input(INPUT_POST, $ex1 . "waitValue");        ## الأجل
####################################################################################################################################
################################################# offline bill #####################################################################
    ################################################################################################################################

    if ($offline == 1) {
        ######################## new client added in offline bill  ##########################################
        if ($clientId < 1) {
            $result = addNewClient($ex5);
            if ($result['flag'] == 0) {
                $clientId = $result['clientid'];
                $_POST[$ex1 . "client"] = $clientId;
            } else {
                $detailResult['flag'] = -1;     ## error adding new client
                $detailResult['note'] = $result['note'];
                $detailResult['noteen'] = $result['noteen'];
                return $detailResult;
            }
        }
        ######################## generate bill no  #########################################################
        $billNo = generateBillNo($ex1);
        $_POST[$ex1 . "billno"] = $billNo;
        #####################################################################################################
        $bills->branchid = filter_input(INPUT_POST, $ex1 . "branchid");
        $bills->userid = filter_input(INPUT_POST, $ex1 . "userid");
        $bills->offline = 1;
        $bills->uploaddate = date('Y-m-d h:i:s');
        $bills->rondomtxt = filter_input(INPUT_POST, $ex1 . "rondomtxt");
        $bills->serverdate = filter_input(INPUT_POST, $ex1 . "serverdate");
    }

##################################################################################################################################
############################################### online bill ######################################################################
    ##############################################################################################################################
    else {
        $createdBillNo = filter_input(INPUT_POST, "createdBillNo");
        $billsssss = $billsDAO->queryByBillno($billNo);
        if (count($billsssss) > 0) {

            ## bill no is the created no
            if ($billNo == $createdBillNo) {
                $billNo = generateOnlineBillNo();
                $_POST["billno"] = $billNo;
            }
            ## bill no is not  the created no - user changed it
            else {
                $detailResult['flag'] = 99;         ## error same bill no exist
                $detailResult['note'] = 'رقم الفاتورة موجود من قبل ';
                $detailResult['noteen'] = 'Bill number exist before .';
                $detailResult['billId'] = '';
                return $detailResult;
            }
        }

        $bills->branchid = $_SESSION['branchId'];
        $bills->userid = $_SESSION['userid'];
        $bills->serverdate = date('Y-m-d h:i:s');
    }

####################################################################################################################################
##################################################### offline bill and online bill both ############################################
    ################################################################################################################################


    $client = $clientDAO->load($clientId);
    $clientdebtBefore = $client->clientdebt;
    $clientdebtAfter = $clientdebtBefore + $waitvalue;

    $bills->kashftype = $kashftype;

    ## external
    if ($kashftype == 1) {
        $bills->kashfplace = filter_input(INPUT_POST, $ex1 . "kashfplace");
        $bills->kashfdate = filter_input(INPUT_POST, $ex1 . "kashfdate");
        $kashfId = saveDoctorlKashfDetails($clientId, $offline, 0, 0);
    }
    ##no kashf at all
    elseif ($kashftype == -1) {
        $kashfId = -1;
    }
    ## internal
    else {
        $kashfId = saveInternalKashf($clientId, $offline);
    }

    $bills->clientid = $clientId;
    $bills->billno = $billNo;
    $bills->receivedate = $receiveDate;
    $bills->comment = $comment;
    $bills->billdate = $billDate;

    $bills->kashfid = $kashfId;

    $bills->alloweddays = $allowedDays;
    $bills->pricetype = $pricetype;
    $bills->approvalno = $approvalNo;


    $bills->productstotalprice = $productstotalprice;
    $bills->kashfvalue = $kashfvalue;
    $bills->kashfdiscount = $kashfdiscount;
    $bills->netbillvalue = $netbillvalue;
    $bills->discounttype = $discounttype;
    $bills->discountvalue = $discountvalue;
    $bills->finalnetbillvalue = $finalnetbillValue;
    $bills->waitvalue = $waitvalue;
    $bills->deleted = 0;
    $bills->billstatus = 0;
    //fatma
    if ($offline == 1) {//fatma
        $saveId = filter_input(INPUT_POST, $ex1 . "saveid");
    } else {
        $saveId = $_SESSION['saveid'];
    }
    $bills->saveid = $saveId;
    $payType = filter_input(INPUT_POST, "payType");
    $bills->payType = $payType;
    //--end fatma
    $billId = savePaymentDetails($bills, $waitvalue, $offline);

    updateClientDebt($clientId, $clientdebtAfter, $offline);
    //insertClientdebtchangeupdate($clientId, $clientdebtBefore, $waitvalue, 0, "اضافة فاتورة مبيعات", $billId, $clientdebtAfter, "bills.php", "اضافة فاتورة مبيعات", $finalnetbillValue, $billDate, $offline);


    $detailResult['billId'] = $billId;
    return $detailResult;
}

function saveInternalKashf($clientId, $offline) {
    global $doctorKashf;
    global $doctorKashfEX;
    global $kashf;
    global $kashfDAO;
    global $kashfDAOEx;

    $doctorKashfId;

    if ($offline == 1) {
        $ex1 = 'bill_';
        $ex2 = 'product_';
        $ex3 = 'doctorkashf_';
        $ex4 = 'kashf_';
        $ex5 = 'client_';
    } else {
        $ex1 = '';
        $ex2 = '';
        $ex3 = '';
        $ex4 = '';
        $ex5 = '';
    }


    if ($offline == 1) {
        $doctorKashfId = filter_input(INPUT_POST, $ex1 . 'kashfid');

        ## 1 - doctorkashf  record added in offline prog
        if ($doctorKashfId < 0) {
            $kashfId = filter_input(INPUT_POST, $ex3 . 'kashfid');
            $doctorId = filter_input(INPUT_POST, $ex3 . 'doctorid');

            ## add kashf record
            $kashfId = saveKashfDetails($clientId, $offline);
            ## add doctor kashf record
            $doctorKashfId = saveDoctorlKashfDetails($clientId, $offline, $kashfId, $doctorId);


//            ############################## 2.1 -    kashf record  added in offline prog     ################################################
//            if ($kashfId < 0) {
//                ## add kashf record
//                $kashfId = saveKashfDetails($clientId, $offline);
//                ## add doctor kashf record
//                $doctorKashfId = saveDoctorlKashfDetails($clientId, $offline, $kashfId, $doctorId);
//            }
//            ############################## 2.2 -   kashf record  already exist              ################################################
//            else {
//                $doctorKashfId = saveDoctorlKashfDetails($clientId, $offline, $kashfId, $doctorId);
//            }
        }
        ## else  2 -  doctorkashf  record already exist    so it will equal to post value
    } else {
        $doctorKashf = $doctorKashfEX->getLastKashfByCustomerId($clientId);
        $kashf = $kashfDAO->load($doctorKashf->kashfid);
        if ($kashf->paystatus == 1) {
            $kashf->paystatus = 2;         ## added to bill previous already
            $kashfDAO->update($kashf);
        }
        $doctorKashfId = $doctorKashf->id;
    }

    //on in ternal kashf mark it as used to stop making discounts every time user use the kashf
    $kashf_serial = filter_input(INPUT_POST, $ex1 . 'kashf_serial');
    if (isset($kashf_serial) && !empty($kashf_serial)) {
        $kashfDAOEx->markKashfAsUsed($kashf_serial);
    }



    return $doctorKashfId;
}

function saveKashfDetails($clientId, $offline) {
    global $kashf;
    global $kashfDAO;
    global $kashfDAOEx;

    if ($offline == 1) {
        $ex1 = 'bill_';
        $ex2 = 'product_';
        $ex3 = 'doctorkashf_';
        $ex4 = 'kashf_';
        $ex5 = 'client_';
    } else {
        $ex1 = '';
        $ex2 = '';
        $ex3 = '';
        $ex4 = '';
        $ex5 = '';
    }


    if ($offline == 1) {
        $rondomTxt = filter_input(INPUT_POST, $ex4 . "rondomtxt");
        $kashf = $kashfDAOEx->queryByRondomtxt($rondomTxt);
        if (count($kashf) > 0) {
            return $kashf->id;
        }
    }
####################################################################################################################################
################################################# offline bill #####################################################################
################################################################################################################################
    if ($offline == 1) {
        $kashf->offline = $offline;
        $kashf->uploaddate = date('Y-m-d h:i:s');
        $kashf->customerid = $clientId;
        $kashf->kashfvalue = filter_input(INPUT_POST, $ex4 . "kashfvalue");
        $kashf->kashftype = filter_input(INPUT_POST, $ex4 . "kashftype");
        $kashf->doctorid = filter_input(INPUT_POST, $ex4 . "doctorid");
        $kashf->kashfdate = filter_input(INPUT_POST, $ex4 . "kashfdate");
        $kashf->paystatus = filter_input(INPUT_POST, $ex4 . "paystatus");
        $kashf->rondomtxt = filter_input(INPUT_POST, $ex4 . "rondomtxt");
        $kashf->branchid = filter_input(INPUT_POST, $ex4 . "branchid");
        $kashf->entered = filter_input(INPUT_POST, $ex4 . "entered");
    }
    $kashfId = $kashfDAO->insert($kashf);
    return $kashfId;
}

function saveDoctorlKashfDetails($clientId, $offline, $kashfId, $doctorId) {
    global $doctorKashf;
    global $doctorKashfDAO;
    global $doctorKashfEX;


    if ($offline == 1) {
        $ex1 = 'bill_';
        $ex2 = 'product_';
        $ex3 = 'doctorkashf_';
        $ex4 = 'kashf_';
        $ex5 = 'client_';
    } else {
        $ex1 = '';
        $ex2 = '';
        $ex3 = '';
        $ex4 = '';
        $ex5 = '';
    }

    if ($offline == 1) {
        $rondomTxt = filter_input(INPUT_POST, $ex3 . "rondomtxt");
        $doctorKashf = $doctorKashfEX->queryByRondomtxt($rondomTxt);
        if (count($doctorKashf) > 0) {
            return $doctorKashf->id;
        }
    }

    $doctorKashf->customerid = $clientId;
    //Left eye المسافة(D)

    $D_Lsphere = filter_input(INPUT_POST, $ex3 . 'D_Lsphere');
    $D_Lcylinder = filter_input(INPUT_POST, $ex3 . 'D_Lcylinder');
    $D_Laxis = filter_input(INPUT_POST, $ex3 . 'D_Laxis');
    $D_Lprism = filter_input(INPUT_POST, $ex3 . 'D_Lprism');
    $D_Lva = filter_input(INPUT_POST, $ex3 . 'D_Lva');

    $doctorKashf->ldsphere = $D_Lsphere;
    $doctorKashf->ldcylinder = $D_Lcylinder;
    $doctorKashf->ldaxis = $D_Laxis;
    $doctorKashf->ldprism = $D_Lprism;
    $doctorKashf->ldva = $D_Lva;

    //Left eye القراءة (N)


    $N_Lsphere = filter_input(INPUT_POST, $ex3 . 'N_Lsphere');
    $N_Lcylinder = filter_input(INPUT_POST, $ex3 . 'N_Lcylinder');
    $N_Laxis = filter_input(INPUT_POST, $ex3 . 'N_Laxis');
    $N_Lprism = filter_input(INPUT_POST, $ex3 . 'N_Lprism');
    $N_Lva = filter_input(INPUT_POST, $ex3 . 'N_Lva');

    $doctorKashf->lnsphere = $N_Lsphere;
    $doctorKashf->lncylinder = $N_Lcylinder;
    $doctorKashf->lnaxis = $N_Laxis;
    $doctorKashf->lnprism = $N_Lprism;
    $doctorKashf->lnva = $N_Lva;


    //Right eye المسافة(D)

    $D_Rsphere = filter_input(INPUT_POST, $ex3 . 'D_Rsphere');
    $D_Rcylinder = filter_input(INPUT_POST, $ex3 . 'D_Rcylinder');
    $D_Raxis = filter_input(INPUT_POST, $ex3 . 'D_Raxis');
    $D_Rprism = filter_input(INPUT_POST, $ex3 . 'D_Rprism');
    $D_Rva = filter_input(INPUT_POST, $ex3 . 'D_Rva');

    $doctorKashf->rdsphere = $D_Rsphere;
    $doctorKashf->rdcylinder = $D_Rcylinder;
    $doctorKashf->rdaxis = $D_Raxis;
    $doctorKashf->rdprism = $D_Rprism;
    $doctorKashf->rdva = $D_Rva;


    //Left eye القراءة (N)

    $N_Rsphere = filter_input(INPUT_POST, $ex3 . 'N_Rsphere');
    $N_Rcylinder = filter_input(INPUT_POST, $ex3 . 'N_Rcylinder');
    $N_Raxis = filter_input(INPUT_POST, $ex3 . 'N_Raxis');
    $N_Rprism = filter_input(INPUT_POST, $ex3 . 'N_Rprism');
    $N_Rva = filter_input(INPUT_POST, $ex3 . 'N_Rva');

    $doctorKashf->rnsphere = $N_Rsphere;
    $doctorKashf->rncylinder = $N_Rcylinder;
    $doctorKashf->rnaxis = $N_Raxis;
    $doctorKashf->rnprism = $N_Rprism;
    $doctorKashf->rnva = $N_Rva;


    $radd = filter_input(INPUT_POST, $ex3 . 'radd');
    $rbiofocal = filter_input(INPUT_POST, $ex3 . 'rbiofocal');
    $ladd = filter_input(INPUT_POST, $ex3 . 'ladd');
    $lbiofocal = filter_input(INPUT_POST, $ex3 . 'lbiofocal');
    $pd = filter_input(INPUT_POST, $ex3 . 'pd');
    $bvd = filter_input(INPUT_POST, $ex3 . 'bvd');
    $notes = filter_input(INPUT_POST, $ex3 . 'notes');

    $doctorKashf->radd = $radd;
    $doctorKashf->rbiofocal = $rbiofocal;
    $doctorKashf->ladd = $ladd;
    $doctorKashf->lbiofocal = $lbiofocal;
    $doctorKashf->pd = $pd;
    $doctorKashf->bvd = $bvd;
    $doctorKashf->notes = $notes;



####################################################################################################################################
################################################# offline bill #####################################################################
################################################################################################################################
    if ($offline == 1) {
        $doctorKashf->uploaddate = date('Y-m-d h:i:s');
        $doctorKashf->date = filter_input(INPUT_POST, $ex3 . "date");
        $doctorKashf->rondomtxt = filter_input(INPUT_POST, $ex3 . "rondomtxt");
        $doctorKashf->branchid = filter_input(INPUT_POST, $ex3 . "branchid");
        $doctorKashf->loguserid = filter_input(INPUT_POST, $ex3 . "loguserid");
    }

##################################################################################################################################
############################################### online bill ######################################################################
##############################################################################################################################
    else {
        $doctorKashf->date = date('Y-m-d');
        $doctorKashf->loguserid = $_SESSION['userid'];
        $doctorKashf->branchid = $_SESSION['branchId'];
    }
    $doctorKashf->kashfid = $kashfId;
    $doctorKashf->doctorid = $doctorId;
    $doctorKashf->offline = $offline;

    $id = $doctorKashfDAO->insert($doctorKashf);

    return $id;
}

function savePaymentDetails($bills, $waitvalue, $offline, $affectNetworkNow = 0) {
    global $billsDAO;
    $insurance = $card = $cash = 0;
    if ($offline == 1) {
        $ex1 = 'bill_';
        $directSave = filter_input(INPUT_POST, $ex1 . "directSave");
        $bills->insurance = filter_input(INPUT_POST, $ex1 . "insurance");
        $bills->card = filter_input(INPUT_POST, $ex1 . "card");
        $bills->cash = filter_input(INPUT_POST, $ex1 . "cash");

        if ($bills->insurance == 1) {
            $bills = saveInsurancePayment($bills, $offline);
            $insurance = 1;
        }
        if ($bills->card == 1) {
            $bills = saveCardPayment($bills, $offline);
            $card = 1;
        }
        if ($bills->cash == 1) {
            $bills = saveCashPayment($bills, $offline);
            $cash = 1;
        }
    } else {
        $paymentamethods = $_POST['paymentamethods'];
        $directSave = filter_input(INPUT_POST, "directSave");
        if (empty($paymentamethods)) {

        } else {
            $N = count($paymentamethods);
            for ($i = 0; $i < $N; $i++) {
                $x = $paymentamethods[$i];
                $bills->$x = 1;
                if ($x == 'insurance') {
                    $bills = saveInsurancePayment($bills, $offline);
                    $insurance = 1;
                } elseif ($x == 'card') {
                    $bills = saveCardPayment($bills, $offline);
                    $card = 1;
                } elseif ($x == 'cash') {
                    $bills = saveCashPayment($bills, $offline);
                    $cash = 1;
                }
            }
        }
    }

    //fatma
    $allowDirectSave = checkDirectSave();
    if ($directSave == 1 && $bills->insurance == 1 && $allowDirectSave == 1) {
        $bills->approved = 1;
        $bills->approveNo = 'direct'; //fatma
        $affectNetworkNow = 1;
    } else {
        $bills->approved = 0;
        $bills->approveNo = ''; //fatma
    }
    $bills->notifSeen = 0;

    $bills->approveFile = ''; //fatma
    //--end fatma
    $billId = $billsDAO->insert($bills);
    //if insurance
    if ($bills->insurance == 1) {
        //network pay dont affect now
        if ($affectNetworkNow == 1) {
            saveDailyEntry($insurance, $card, $cash, $waitvalue, $billId, $offline);
        }
    } else {
        saveDailyEntry($insurance, $card, $cash, $waitvalue, $billId, $offline);
    }
    return $billId;
}

function saveInsurancePayment($bills, $offline) {
    global $insuranceCompaniesDAO;

    if ($offline == 1) {
        $ex1 = 'bill_';
    } else {
        $ex1 = '';
    }

    $insuranceCompanies = $insuranceCompaniesDAO->load(filter_input(INPUT_POST, $ex1 . "insuranceCompanies"));
    $bills->insurancecompanyid = filter_input(INPUT_POST, $ex1 . "insuranceCompanies");
    $bills->customerpercent = filter_input(INPUT_POST, $ex1 . "clientPercent");
    $bills->customermax = filter_input(INPUT_POST, $ex1 . "clientMax");
    $bills->customercarry = filter_input(INPUT_POST, $ex1 . "clientCarry");
    $bills->companyaccept = filter_input(INPUT_POST, $ex1 . "insAccept");
    $bills->companycarry = filter_input(INPUT_POST, $ex1 . "insuranceValue");
    $bills->insdiscountpercent = $insuranceCompanies->discountpercent;
    $oldattatch = filter_input(INPUT_POST, $ex1 . "oldattatch");
    $handle = new upload($_FILES['attatch']);
    $image = uploadImages2($handle, '../views/default/images/billsattatch');
    if (strlen($image) > 4) {
        $bills->attatch = $image;
        unlink('../views/default/images/billsattatch/' . $oldattatch);
    } else {
        $bills->attatch = $oldattatch;
    }
    return $bills;
}

function saveCardPayment($bills, $offline) {
    global $paymentNetworksDAO;

    if ($offline == 1) {
        $ex1 = 'bill_';
    } else {
        $ex1 = '';
    }

    $paymentNetworks = $paymentNetworksDAO->load(filter_input(INPUT_POST, $ex1 . "paymentNetworks"));
    $bills->paymentnetworkid = filter_input(INPUT_POST, $ex1 . "paymentNetworks");
    $bills->cardvalue = filter_input(INPUT_POST, $ex1 . "cardValue");
    $bills->netdiscountpercent = $paymentNetworks->discountpercent;
    return $bills;
}

function saveCashPayment($bills, $offline) {

    if ($offline == 1) {
        $ex1 = 'bill_';
    } else {
        $ex1 = '';
    }
    $bills->cashvalue = filter_input(INPUT_POST, $ex1 . "cashValue");

    return $bills;
}

##   mada network  with  daily entry  as percent on card value of each bill   القيد الخاص بمدا كنسبة على الفاتورة مثل اى شبكة اخرى

function saveDailyEntry($insurance, $card, $cash, $waitvalue, $billId, $offline) {
    global $dailyEntry;      ## Dailyentry
    global $accountsTreeDAO;
    global $client;
    global $clientDAO;
    global $mySave;
    global $mySaveDAO;
    global $insuranceCompaniesDAO;
    global $paymentNetworksDAO;
    global $billsDAO;
    $total = 0;

    if ($offline == 1) {
        $ex1 = 'bill_';
        $ex2 = 'product_';
        $ex3 = 'doctorkashf_';
        $ex4 = 'kashf_';
        $ex5 = 'client_';
        $_SESSION['userid'] = filter_input(INPUT_POST, $ex1 . "userid");
    } else {
        $ex1 = '';
        $ex2 = '';
        $ex3 = '';
        $ex4 = '';
        $ex5 = '';
    }

    $mytransactions = new Transaction();
    $bills = $billsDAO->load($billId);

    $client = $clientDAO->load($bills->clientid);
    if ($offline == 1) {
        $saveId = filter_input(INPUT_POST, $ex1 . "saveid");
    } else {
        $saveId = $_SESSION['saveid'];
    }

    $mySave = $mySaveDAO->load($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 ($waitvalue != 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 ($cash == 1) {
        if ($mySave->treeId > 0) {
            $treeId2 = $mySave->treeId;
        } else {
            $treeId2 = addTreeElement($mySave->savename, 20, 3, 0, 1, '', 0, 0);
        }

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

        $insValue = filter_input(INPUT_POST, $ex1 . "insuranceValue");
        $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 = '  اضافة كشف بصريات جديد';
        $dailyEntryDebtor7->pluginid = $billId;
        array_push($dailyEntryDebtorArray, $dailyEntryDebtor7);
        #############
        $total = $total + filter_input(INPUT_POST, $ex1 . "insuranceValue");
    }
#########################################################################################
    if ($card == 1) {
        $networkId = filter_input(INPUT_POST, $ex1 . "paymentNetworks");
        $paymentNetworks = $paymentNetworksDAO->load($networkId);


        $cardValue = filter_input(INPUT_POST, $ex1 . "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 + filter_input(INPUT_POST, $ex1 . "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();

        $message = 'تمت العملية بنجاح';
    } catch (Exception $ex) {
        $mytransactions->rollback();
        $message = 'عفوا لقد حدث خطأ';
    }
}

function addNewClient($ex5) {
    global $client;
    global $clientDAO;
    global $clientExt;
    global $myClientdebtchange;
    global $myClientdebtchangeRecord;
    global $dailyEntry;

    $clientaddress = filter_input(INPUT_POST, $ex5 . "clientaddress");
    $clientdate = filter_input(INPUT_POST, $ex5 . "clientdate");
    $clientdetails = filter_input(INPUT_POST, $ex5 . "clientdetails");
    $clientmobile = filter_input(INPUT_POST, $ex5 . "clientmobile");
    $clientdebt = (filter_input(INPUT_POST, $ex5 . "clientdebt")) + 0;
    $clientname = filter_input(INPUT_POST, $ex5 . "clientname");
    $clientphone = filter_input(INPUT_POST, $ex5 . "clientphone");
    $clientareaid = filter_input(INPUT_POST, $ex5 . "clientareaid");
    $userid = filter_input(INPUT_POST, $ex5 . "userid");
    $clientcode = filter_input(INPUT_POST, $ex5 . "clientcode");
    $conditions = filter_input(INPUT_POST, $ex5 . "conditions");
    $rondomtxt = filter_input(INPUT_POST, $ex5 . "rondomtxt");

    $flag;
    $clientid;
    $result = array();

    $clientss = $clientExt->queryByRondomtxt($rondomtxt);
    if (count($clientss) > 0) {
        $flag = 0;     ## client exist return id
        $note = '';
        $noteen = '';
        $clientid = $clientss->clientid;
    } else {
        if (!empty($clientname)) {
            //check if this name already exists
            if (count($clientDAO->queryByClientname($clientname)) == 0) {
                //insert into client
                $client->clientaddress = $clientaddress;
                $client->clientdate = $clientdate;
                $client->clientdetails = $clientdetails;
                $client->clientdebt = $clientdebt;
                $client->clientname = $clientname;
                $client->clientphone = $clientphone;
                $client->clientareaid = $clientareaid;
                $client->userid = $userid;
                $client->clientcode = $clientcode;
                $client->conditions = $conditions;
                $client->clientmobile = $clientmobile;
                $client->rondomtxt = $rondomtxt;
                $client->dailyentryid = 0;

                $clientid = $clientDAO->insert($client);

                if (!empty($clientid)) {
                    //insert into clientdeptchange
                    $myClientdebtchange->clientdebtchangeafter = $clientdebt;
                    $myClientdebtchange->clientdebtchangeamount = $clientdebt;
                    $myClientdebtchange->clientdebtchangebefore = 0;
                    $myClientdebtchange->clientdebtchangedate = $clientdate;
                    $myClientdebtchange->clientdebtchangemodelid = $clientid;
                    $myClientdebtchange->clientdebtchangetype = 0;
                    $myClientdebtchange->clientid = $clientid;
                    $myClientdebtchange->comment = "";
                    $myClientdebtchange->processname = "إضافة عميل جديد";
                    $myClientdebtchange->tablename = "bills.php";
                    $myClientdebtchange->userid = $userid;
                    $myClientdebtchange->dailyentryid = 0;

                    $myClientdebtchangeRecord->insert($myClientdebtchange);

                    $_SESSION['userid'] = $userid;
                    $treeId = addTreeElement($clientname, 23, 3, 0, 1, '', 0, 0);
                    //$_SESSION['userid'] = '';

                    $dailyEntry->dDateTime = date('Y-m-d H:i:s');
                    $dailyEntry->entryComment = 'تم اضافة عميل ' . $clientname;

                    $dailyEntryDebtor->value = $clientdebt;
                    $dailyEntryDebtor->accountstreeid = $treeId;
                    $dailyEntryDebtor->pluginControllerName = 'bills.php';
                    $dailyEntryDebtor->pluginComment = $bill_name;
                    $dailyEntryDebtor->pluginid = $billId;
                    $dailyEntryCreditor->value = $clientdebt;
                    $dailyEntryCreditor->accountstreeid = 121;
                    $dailyEntryCreditor->pluginControllerName = 'bills.php';
                    $dailyEntryCreditor->pluginComment = $bill_name;
                    $dailyEntryCreditor->pluginid = $billId;
                    $dailyEntryDebtorArray = array();
                    $dailyEntryCreditorArray = array();
                    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);
                    array_push($dailyEntryCreditorArray, $dailyEntryCreditor);

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

                    $client = $clientDAO->load($clientid);
                    $client->dailyentryid = $did;
                    $clientDAO->update($client);
                }

                $flag = 0;     ## new name   insert done
                $note = '';
                $noteen = '';
            } else {
                $flag = 1;    ##  name   exist
                $note = ' اسم العميل موجود من قبل';
                $noteen = 'client name exist';
            }
        } else {
            $flag = 2;    ## empty name
            $note = 'اسم  العميل فارغ ';
            $noteen = 'empty client name ';
        }
    }





    $result['flag'] = $flag;
    $result['note'] = $note;
    $result['noteen'] = $noteen;
    $result['clientid'] = $clientid;
    return $result;
}

function generateBillNo($ex1) {
    global $bills;
    global $billsEX;

    ## bill no generate

    $branchId = filter_input(INPUT_POST, $ex1 . "branchid");
    $today = date('y');
    $billNo = $branchId;
    $billNo .= $today;

    $bills = $billsEX->searchInBillNo($billNo);
    if (count($bills) > 0) {
        $billNo = $bills->billno + 1;
        if ($branchId == 0) {
            $billNo = '0' . $billNo;
        }
    } else {
        $billNo .= '00001';
    }
    return $billNo;
}

function generateOnlineBillNo() {
    global $bills;
    global $billsEX;

    ## bill no generate

    $branchId = $_SESSION['branchId'];
    $today = date('y');
    $billNo = $branchId;
    $billNo .= $today;

    $bills = $billsEX->searchInBillNo($billNo);
    if (count($bills) > 0) {
        $billNo = $bills->billno + 1;
        if ($branchId == 0) {
            $billNo = '0' . $billNo;
        }
    } else {
        $billNo .= '00001';
    }
    return $billNo;
}

function saveBillProducts($billId, $offline, $affectNetworkNow = 0) {
    global $billsProducts;
    global $billsProductsDAO;
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailEX;
    global $product;
    global $billsDAO;
    global $productDAO;


    if ($offline == 1) {
        $ex1 = 'bill_';
        $ex2 = 'product_';
        $ex3 = 'doctorkashf_';
        $ex4 = 'kashf_';
        $ex5 = 'client_';
    } else {
        $ex1 = '';
        $ex2 = '';
        $ex3 = '';
        $ex4 = '';
        $ex5 = '';
    }


    $flag = 0;
    $affectProductNowFlag = 0;
    $bills = $billsDAO->load($billId);
    if ($bills->insurance == 1) {
        //network pay dont affect now
        if ($affectNetworkNow == 1) {
            $affectProductNowFlag = 1;
        }
    } else {
        $affectProductNowFlag = 1;
    }
    $itr = filter_input(INPUT_POST, $ex1 . "hidden_itr");
    for ($i = 1; $i <= $itr; $i++) {

        $productId = filter_input(INPUT_POST, $ex2 . 'product' . $i);
        $note = filter_input(INPUT_POST, $ex2 . 'note' . $i);
        $productNum = filter_input(INPUT_POST, $ex2 . 'pronum' . $i);
        $productPrice = filter_input(INPUT_POST, $ex2 . 'proprice' . $i);
        $service = filter_input(INPUT_POST, $ex2 . 'service' . $i);
        $productcode = filter_input(INPUT_POST, $ex2 . 'productcode' . $i);
        $totalProductPrice = filter_input(INPUT_POST, $ex2 . 'totalProductPrice' . $i);

        $billDate = filter_input(INPUT_POST, $ex1 . "billdate");
        $storeId = filter_input(INPUT_POST, $ex1 . 'storeid');

        if ($productId && $productId != -1) {

            $billsProducts->billid = $billId;
            $billsProducts->productid = $productId;
            $billsProducts->note = $note;
            $billsProducts->productno = $productNum;
            $billsProducts->productprice = $productPrice;
            $billsProducts->service = $service;
            $billsProducts->productcode = $productcode;
            $billsProducts->producttotalprice = $totalProductPrice;
            $billsProducts->deleted = 0;
            $billsProducts->storeid = $storeId;
            if ($offline == 1) {
                $billsProducts->rondomtxt = filter_input(INPUT_POST, $ex2 . 'rondomtxt' . $i);
                $billsProducts->retproductno = filter_input(INPUT_POST, $ex2 . 'retproductno' . $i);
            }
            $detailId = $billsProductsDAO->insert($billsProducts);
            $product = $productDAO->load($productId);
            if ($affectProductNowFlag == 1) {
                lastAndMeanBuyPrice_SellOptic($detailId, $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;
}

#################### show bill  details ####################################################################################################

function getBillDetails($billId) {
    global $smarty;
    global $clientDAO;
    global $billsDAO;
    global $doctorKashfDAO;
    global $insuranceCompaniesDAO;
    global $paymentNetworksDAO;
    global $BranchDAO;
    global $userDAO;




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


    $oldclientdata = $clientDAO->load($bill->clientid);

    $smarty->assign("oldclientdata", $oldclientdata);
    //$dayName = DateTime::createFromFormat('Y-m-d H:i:s', $bill->billdate);
    $dayName = new DateTime($bill->billdate); //by fatma
    $smarty->assign("dayName", $dayName->format('D') . 'day');
    $smarty->assign("billDate", $dayName->format('d-m-Y'));

    if ($bill->branchid == 0) {
        $smarty->assign("shopName", '');
    } else {


        $Branch = $BranchDAO->load($bill->branchid);
        $smarty->assign("Branch", $Branch);
    }

    //$receivedate = DateTime::createFromFormat('Y-m-d H:i:s', $bill->receivedate);
    $receivedate = new DateTime($bill->receivedate); //by fatma
    $smarty->assign("date", $receivedate->format('d-m-Y'));
    $smarty->assign("time", $receivedate->format('g:i A'));

    ## client name
    $client = $clientDAO->load($bill->clientid);
    $bill->clientname = $client->clientname;
    $bill->username = $client->clientphone . ' / ' . $client->clientmobile;
    $bill->approveNo = $client->clientcode;
    $bill->approveFile = $client->clientaddress;

    ## insurance company
    if ($bill->insurance == 1 && $bill->insurancecompanyid) {
        $insurancecompanies = $insuranceCompaniesDAO->load($bill->insurancecompanyid);
        $bill->companyname = $insurancecompanies->name;
        $smarty->assign("instruction", $insurancecompanies->instruction);
    }
    ## payment network
    if ($bill->card == 1 && $bill->paymentnetworkid) {
        $paymentnetworks = $paymentNetworksDAO->load($bill->paymentnetworkid);
        $bill->networkname = $paymentnetworks->name;
    }

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


    $doctor_data = $userDAO->load($kashf->doctorid);
    $smarty->assign("doctor_name", $doctor_data->username);

    $user_data = $userDAO->load($bill->userid);

    $user_branch = $user_data->branchId;
    if ($user_branch == '0') {
        //# user deal with all branchs , so selection first branch .
        $allBranch = $BranchDAO->queryAll();
        $Branch = $allBranch[0];
    } else {

        $Branch = $BranchDAO->load($user_branch);
    }

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


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

    // print_r($billProducts);
    $smarty->assign("billProducts", $billProducts);
    $smarty->assign("billProductsCount", count($billProducts));
    //print_r('<pre>');
    //print_r($bill);
    // print_r('<pre>');
    ## bill
    $smarty->assign("bill", $bill);
}

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

    $opCount = 1;
    $frameCount = 1;

    $billProducts = $billsProductsEX->queryByBillIdAndDeleted($billId, 0);
    $i = 1;
    $categories;
    if (count($billProducts) > 0) {
        foreach ($billProducts as $pro) {
            $product = $productDAO->load($pro->productid);
            $pro->productName = $product->productName;
            $productCat = $productCatDAO->load($product->productCatId);
            $pro->productCatName = $productCat->productCatName;


            $parentId = $product->productCatId;
            $pathArr = getProductPath_recursive($parentId, $categories, 0);
            $pro->productName = $product->productName . '/' . $pathArr;


            if ($pro->service == "Frame") {
                $no = strlen($frameCount);
                $itr = $frameCount;
                $pro->productCode = 'FRM';
                $frameCount = $frameCount + 001;
            } else {
                $no = strlen($opCount);
                $itr = $opCount;
                $pro->productCode = 'OPT';
                $opCount = $opCount + 001;
            }

            if ($no == 3) {

            } elseif ($no == 2) {
                $itr = '0' . $itr;
            } else {
                $itr = '00' . $itr;
            }

            $pro->productCode .= $itr;
        }
    }

    return $billProducts;
}

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

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

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

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

#################### update bill ####################################################################################################

function update() {
    $billId = filter_input(INPUT_POST, "billId");
    updateBillDetails($billId);
    $flag = updateBillProducts($billId);
    return $flag;
}

function updateBillDetails($billId) {
    global $bills;
    global $billsDAO;
    global $clientDAO;
    global $myClientdebtchangeEx;

    $clientId = filter_input(INPUT_POST, "client");
    $receiveDate = filter_input(INPUT_POST, "receivedate");
    $billNo = filter_input(INPUT_POST, "billno");
    $comment = filter_input(INPUT_POST, "comment");
    $billDate = filter_input(INPUT_POST, "billdate");
    $kashftype = filter_input(INPUT_POST, "kashftype");
    $pricetype = filter_input(INPUT_POST, "pricetype");
    $approvalNo = filter_input(INPUT_POST, "approvalNo");
    $allowedDays = (!filter_input(INPUT_POST, "allowedDays")) ? 0 : filter_input(INPUT_POST, "allowedDays");


    $productstotalprice = filter_input(INPUT_POST, "totalBillPrice");   ## إجمالي المشتريات
    $kashfvalue = filter_input(INPUT_POST, "kashfValue");      ##  قيمة الكشف
    $kashfdiscount = filter_input(INPUT_POST, "kashDiscValue");      ##    خصم الكشف
    $netbillvalue = filter_input(INPUT_POST, "netBillValue");      ##  الاجمالى
    $discounttype = filter_input(INPUT_POST, "discType");      ##  نوع الخصم     1 direct   , 2 percent
    $discountvalue = filter_input(INPUT_POST, "discValue");      ##   قيمة الخصم
    $finalnetbillValue = filter_input(INPUT_POST, "netValue");      ## الصافى
    $waitvalue = filter_input(INPUT_POST, "waitValue");        ## الأجل


    $bills = $billsDAO->load($billId);
    $client = $clientDAO->load($clientId);
    $amount = $waitvalue - $bills->waitvalue;
    ###############################################################################
    ## reverse old  client dept
    $newBefore = $client->clientdebt;
    $newAfter = $newBefore + $amount;


//    insertClientdebtchangeupdate($clientId, $newBefore, $amount, 0, "تعديل  فاتورة مبيعات", $billId, $newAfter, "bills.php", "تعديل فاتورة مبيعات", $finalnetbillValue, $billDate, 0);
//    updateClientDebt($clientId, $newAfter, 0);
###############################################################################
    //($clientId, $newAfter, 0);
    ###############################################################################
    ## external
    if ($bills->kashftype == 1) {
        $bills->kashfplace = filter_input(INPUT_POST, "kashfplace");
        $bills->kashfdate = filter_input(INPUT_POST, "kashfdate");
        updateExternalKashfDetails($bills->kashfid, $clientId);
    }

    $bills->clientid = $clientId;
    $bills->receivedate = $receiveDate;
    $bills->billno = $billNo;
    $bills->comment = $comment;
    $bills->billdate = $billDate;
    $bills->userid = $_SESSION['userid'];
    $bills->alloweddays = $allowedDays;
    $bills->pricetype = $pricetype;
    $bills->approvalno = $approvalNo;


    $bills->productstotalprice = $productstotalprice;
    $bills->kashfvalue = $kashfvalue;
    $bills->kashfdiscount = $kashfdiscount;
    $bills->netbillvalue = $netbillvalue;
    $bills->discounttype = $discounttype;
    $bills->discountvalue = $discountvalue;
    $bills->finalnetbillvalue = $finalnetbillValue;
    $bills->waitvalue = $waitvalue;
    $bills->deleted = 0;
    //fatma
    $bills->approved = $bills->approved;
    $bills->notifSeen = 0;
    //$bills->billstatus = 0;
    $oldattatch = filter_input(INPUT_POST, $ex1 . "oldattatch");
    $handle = new upload($_FILES['attatch']);
    $image = uploadImages2($handle, '../views/default/images/billsattatch');
    if (strlen($image) > 4) {
        $bills->attatch = $image;
        unlink('../views/default/images/billsattatch/' . $oldattatch);
    } else {
        $bills->attatch = $oldattatch;
    }

    $bills->saveid = $_SESSION['saveid'];
    $bills->approveNo = ''; //fatma
    $bills->approveFile = ''; //fatma

    $billsDAO->update($bills);

    emptyPaymentData($billId);
    updatePaymentDetails($billId, $waitvalue);
}

function updateExternalKashfDetails($kasfId, $clientId) {
    global $doctorKashf;
    global $doctorKashfDAO;

    $doctorKashf = $doctorKashfDAO->load($kasfId);

    $doctorKashf->customerid = $clientId;
    //Left eye المسافة(D)

    $D_Lsphere = filter_input(INPUT_POST, 'D_Lsphere');
    $D_Lcylinder = filter_input(INPUT_POST, 'D_Lcylinder');
    $D_Laxis = filter_input(INPUT_POST, 'D_Laxis');
    $D_Lprism = filter_input(INPUT_POST, 'D_Lprism');
    $D_Lva = filter_input(INPUT_POST, 'D_Lva');

    $doctorKashf->ldsphere = $D_Lsphere;
    $doctorKashf->ldcylinder = $D_Lcylinder;
    $doctorKashf->ldaxis = $D_Laxis;
    $doctorKashf->ldprism = $D_Lprism;
    $doctorKashf->ldva = $D_Lva;

    //Left eye القراءة (N)


    $N_Lsphere = filter_input(INPUT_POST, 'N_Lsphere');
    $N_Lcylinder = filter_input(INPUT_POST, 'N_Lcylinder');
    $N_Laxis = filter_input(INPUT_POST, 'N_Laxis');
    $N_Lprism = filter_input(INPUT_POST, 'N_Lprism');
    $N_Lva = filter_input(INPUT_POST, 'N_Lva');

    $doctorKashf->lnsphere = $N_Lsphere;
    $doctorKashf->lncylinder = $N_Lcylinder;
    $doctorKashf->lnaxis = $N_Laxis;
    $doctorKashf->lnprism = $N_Lprism;
    $doctorKashf->lnva = $N_Lva;


    //Right eye المسافة(D)

    $D_Rsphere = filter_input(INPUT_POST, 'D_Rsphere');
    $D_Rcylinder = filter_input(INPUT_POST, 'D_Rcylinder');
    $D_Raxis = filter_input(INPUT_POST, 'D_Raxis');
    $D_Rprism = filter_input(INPUT_POST, 'D_Rprism');
    $D_Rva = filter_input(INPUT_POST, 'D_Rva');

    $doctorKashf->rdsphere = $D_Rsphere;
    $doctorKashf->rdcylinder = $D_Rcylinder;
    $doctorKashf->rdaxis = $D_Raxis;
    $doctorKashf->rdprism = $D_Rprism;
    $doctorKashf->rdva = $D_Rva;


    //Left eye القراءة (N)

    $N_Rsphere = filter_input(INPUT_POST, 'N_Rsphere');
    $N_Rcylinder = filter_input(INPUT_POST, 'N_Rcylinder');
    $N_Raxis = filter_input(INPUT_POST, 'N_Raxis');
    $N_Rprism = filter_input(INPUT_POST, 'N_Rprism');
    $N_Rva = filter_input(INPUT_POST, 'N_Rva');

    $doctorKashf->rnsphere = $N_Rsphere;
    $doctorKashf->rncylinder = $N_Rcylinder;
    $doctorKashf->rnaxis = $N_Raxis;
    $doctorKashf->rnprism = $N_Rprism;
    $doctorKashf->rnva = $N_Rva;

    $doctorKashf->doctorid = 0;
    $doctorKashf->date = date('Y-m-d');
    $doctorKashf->loguserid = $_SESSION['userid'];
    $doctorKashf->branchid = $_SESSION['branchId'];


    $radd = filter_input(INPUT_POST, 'radd');
    $rbiofocal = filter_input(INPUT_POST, 'rbiofocal');
    $ladd = filter_input(INPUT_POST, 'ladd');
    $lbiofocal = filter_input(INPUT_POST, 'lbiofocal');
    $pd = filter_input(INPUT_POST, 'pd');
    $bvd = filter_input(INPUT_POST, 'bvd');
    $notes = filter_input(INPUT_POST, 'notes');

    $doctorKashf->radd = $radd;
    $doctorKashf->rbiofocal = $rbiofocal;
    $doctorKashf->ladd = $ladd;
    $doctorKashf->lbiofocal = $lbiofocal;
    $doctorKashf->pd = $pd;
    $doctorKashf->bvd = $bvd;
    $doctorKashf->notes = $notes;

    $doctorKashfDAO->update($doctorKashf);
}

function emptyPaymentData($billId) {
    global $bills;
    global $billsDAO;

    $bills = $billsDAO->load($billId);

    $bills->cash = 0;
    $bills->insurance = 0;
    $bills->card = 0;

    $bills->cardvalue = 0;
    $bills->cashvalue = 0;

    $bills->insurancecompanyid = NULL;
    $bills->paymentnetworkid = NULL;

    $bills->customerpercent = 0;
    $bills->customermax = 0;
    $bills->customercarry = 0;
    $bills->companyaccept = 0;
    $bills->companycarry = 0;


    $billsDAO->update($bills);
}

function updatePaymentDetails($billId, $waitvalue) {
    global $billsDAO;
    global $insuranceCompaniesDAO;
    global $paymentNetworksDAO;

    $insurance = $card = $cash = 0;

    $bills = $billsDAO->load($billId);


    $paymentamethods = $_POST['paymentamethods'];
    if (empty($paymentamethods)) {

    } else {
        $N = count($paymentamethods);
        for ($i = 0; $i < $N; $i++) {
            $x = $paymentamethods[$i];
            $bills->$x = 1;

            if ($x == 'insurance') {
                $insuranceCompanies = $insuranceCompaniesDAO->load(filter_input(INPUT_POST, "insuranceCompanies"));
                $bills->insurancecompanyid = filter_input(INPUT_POST, "insuranceCompanies");
                $bills->customerpercent = filter_input(INPUT_POST, "clientPercent");
                $bills->customermax = filter_input(INPUT_POST, "clientMax");
                $bills->customercarry = filter_input(INPUT_POST, "clientCarry");
                $bills->companyaccept = filter_input(INPUT_POST, "insAccept");
                $bills->companycarry = filter_input(INPUT_POST, "insuranceValue");
                if ($bills->insdiscountpercent == 0) {
                    $bills->insdiscountpercent = $insuranceCompanies->discountpercent;
                }

                $insurance = 1;
            } elseif ($x == 'card') {
                $paymentNetworks = $paymentNetworksDAO->load(filter_input(INPUT_POST, "paymentNetworks"));

                $bills->paymentnetworkid = filter_input(INPUT_POST, "paymentNetworks");
                $bills->cardvalue = filter_input(INPUT_POST, "cardValue");

                if ($bills->netdiscountpercent == 0) {
                    $bills->netdiscountpercent = $paymentNetworks->discountpercent;
                }

                $card = 1;
            } elseif ($x == 'cash') {
                $bills->cashvalue = filter_input(INPUT_POST, "cashValue");
                $cash = 1;
            }
        }
    }

    $billsDAO->update($bills);
    //if insurance
    if ($bills->insurance == 1) {
        //network pay dont affect now
        if ($affectNetworkNow == 1) {
            reverseEntryWithItsID($bills->dailyentryid);
            saveDailyEntry($insurance, $card, $cash, $waitvalue, $billId, 0);
        }
    } else {
        reverseEntryWithItsID($bills->dailyentryid);
        saveDailyEntry($insurance, $card, $cash, $waitvalue, $billId, 0);
    }
}

function updateBillProducts($billId, $affectNetworkNow = 0) {

    global $billsProducts;
    global $billsProductsDAO;
    global $billsProductsEX;
    global $storeDetail;
    global $storeDetailEX;
    global $storeDetailDAO;
    global $billsDAO;
    $flag = 0;

    $itr = filter_input(INPUT_POST, "hidden_itr");
    $billDate = filter_input(INPUT_POST, "billdate");


    $affectProductNowFlag = 0;
    $bills = $billsDAO->load($billId);
    if ($bills->insurance == 1) {
        //network pay dont affect now
        if ($affectNetworkNow == 1) {
            $affectProductNowFlag = 1;
        }
    } else {
        $affectProductNowFlag = 1;
    }
    ## deleted products that user del it
    $del_pro_ids = filter_input(INPUT_POST, 'del_pro_ids');
    if (!empty($del_pro_ids)) {
        $del_pro_ids = rtrim($del_pro_ids, ',');
        $billsProductsEX->deleteIDS($del_pro_ids);
    }

    for ($i = 1; $i <= $itr; $i++) {
        $billProductId = filter_input(INPUT_POST, 'billProductId' . $i);
        $productId = filter_input(INPUT_POST, 'product' . $i);
        $note = filter_input(INPUT_POST, 'note' . $i);
        $productNum = filter_input(INPUT_POST, 'pronum' . $i);
        $productNumOld = filter_input(INPUT_POST, 'pronumOld' . $i);
        $productPrice = filter_input(INPUT_POST, 'proprice' . $i);
        $service = filter_input(INPUT_POST, 'service' . $i);
        $productcode = filter_input(INPUT_POST, 'productcode' . $i);

        $totalProductPrice = filter_input(INPUT_POST, 'totalProductPrice' . $i);

        $storeId = filter_input(INPUT_POST, 'storeid');

        ## existing product update it
        if ($billProductId) {
            if ($productId && $productId != -1) {
                $billsProducts = $billsProductsDAO->load($billProductId);
                $billsProducts->productid = $productId;
                $billsProducts->note = $note;
                $billsProducts->productno = $productNum;
                $billsProducts->productprice = $productPrice;

                $billsProducts->service = $service;
                $billsProducts->productcode = $productcode;

                $billsProducts->producttotalprice = $totalProductPrice;
                $billsProducts->deleted = 0;
                $billsProducts->storeid = $storeId;
                $billsProductsDAO->update($billsProducts);

                if ($affectProductNowFlag == 1) {
                    $storeDetail = $storeDetailEX->getProductQuantity($productId, $storeId);
                    if (count($storeDetail) <= 0) {
                        $storeDetail->productid = $productId;
                        $storeDetail->storeid = $storeId;
                        $storeDetail->productquantity = 0;
                        $storeDetail->userid = $_SESSION['userid'];
                        $storeDetail->storedetaildate = date('Y-m-d');
                        $storeDetailDAO->insert($storeDetail);
                    }

                    $productbefore = $storeDetail->productquantity;
                    $productafter = $productbefore - ($productNum - $productNumOld);
                    $storeDetail->productquantity = $productafter;
                    $storeDetailDAO->update($storeDetail);
                    if ($storeDetail->productquantity < 0) {
                        $flag = 1;
                    }
                    insertStorereportupdate($productId, $storeId, $productNum, $productbefore, $productafter, 1, $billId, "اضافة فاتورة مبيعات", "bills.php", $billDate, 0);
                    $detailId = $billsProducts->id;
                    lastAndMeanBuyPrice_SellOptic($detailId, $productId);
                }
            }
        }
        ## new product insert it
        else {
            if ($productId && $productId != -1) {

                $billsProducts->billid = $billId;
                $billsProducts->productid = $productId;
                $billsProducts->note = $note;
                $billsProducts->productno = $productNum;
                $billsProducts->productprice = $productPrice;
                $billsProducts->service = $service;
                $billsProducts->productcode = $productcode;

                $billsProducts->producttotalprice = $totalProductPrice;
                $billsProducts->deleted = 0;
                $billsProducts->storeid = $storeId;
                $detailId = $billsProductsDAO->insert($billsProducts);

                if ($affectProductNowFlag == 1) {
                    $storeDetail = $storeDetailEX->getProductQuantity($productId, $storeId);
                    if (count($storeDetail) <= 0) {
                        $storeDetail->productid = $productId;
                        $storeDetail->storeid = $storeId;
                        $storeDetail->productquantity = 0;
                        $storeDetail->userid = $_SESSION['userid'];
                        $storeDetail->storedetaildate = date('Y-m-d');
                        $storeDetailDAO->insert($storeDetail);
                    }

                    $productbefore = $storeDetail->productquantity;
                    $productafter = $productbefore - ($productNum - $productNumOld);
                    $storeDetail->productquantity = $productafter;
                    $storeDetailDAO->update($storeDetail);
                    if ($storeDetail->productquantity < 0) {
                        $flag = 1;
                    }
                    insertStorereportupdate($productId, $storeId, $productNum, $productbefore, $productafter, 1, $billId, "اضافة فاتورة مبيعات", "bills.php", $billDate, 0);
                    lastAndMeanBuyPrice_SellOptic($detailId, $productId);
                }
            }
        }
    }

    return $flag;
}

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

function checkDirectSave() {
    global $userDAO;
    global $userGroupDAO;
    $user = $userDAO->load($_SESSION['userid']);
    $usergroup = $userGroupDAO->load($_SESSION['usergroupid']);
    $allow = 0;
    if ($user->directSaveBills == 1 && $usergroup->directSaveBills == 1) {
        $allow = 1;
    }
    return $allow;
}

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

?>