<?php

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

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

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



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

//Supplierdebtchange
$Supplierdebtchange = new Supplierdebtchange();
$SupplierdebtchangeDAO = new SupplierdebtchangeMySqlDAO();
$SupplierdebtchangeEX = new SupplierdebtchangeMySqlExtDAO();

//Bank
$bankDAO = new BankMySqlDAO();
$bankEX = new BankMySqlExtDAO();
//account
$account = new Bankaccount();
$accountDAO = new BankaccountMySqlDAO;
$accountExtDAO = new BankaccountMySqlExtDAO;
###########################################################################################################################################################
###########################################################################################################################################################

function updateSupplierDebt($supplierId, $supplierdebtAfter) {
    //to use the variable out side the funcion
    global $supplier;
    global $supplierEX;

    //update supplierdebt in supplier tbl
    $supplierEX->updateSuppDept($supplierId, $supplierdebtAfter);
}

// insert data into SupplierDebtChange tbl
function insertSupplierDebtChangeupdate($supplierId, $supplierDebtChangeBefore, $supplierDebtChangeAmount, $supplierDebtChangeType, $processname, $supplierDebtChangeModelId, $supplierDebtChangeAfter, $tablename, $comment, $mydate) {
    global $supplierDebtChange;
    global $supplierDebtChangeDAO;

    $supplierDebtChange->comment = $comment;
    $supplierDebtChange->processname = $processname;
    $supplierDebtChange->supplierdebtchangeafter = $supplierDebtChangeAfter;
    $supplierDebtChange->supplierdebtchangeamount = $supplierDebtChangeAmount;
    $supplierDebtChange->supplierdebtchangebefore = $supplierDebtChangeBefore;
    $supplierDebtChange->supplierdebtchangedate = $mydate; //$today;
    $supplierDebtChange->supplierdebtchangemodelid = $supplierDebtChangeModelId;
    $supplierDebtChange->supplierdebtchangetype = $supplierDebtChangeType;
    $supplierDebtChange->supplierid = $supplierId;
    $supplierDebtChange->tablename = $tablename;
    $supplierDebtChange->userid = $_SESSION['userid'];
    $supplierDebtChange->dailyentryid = 0;
    $supplierDebtChangeDAO->insert($supplierDebtChange);
}

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

function getSupplierDataBuy() {
    global $supplierEX;
    $alldata = $supplierEX->queryAllsup();
    return $alldata;
}

function getBankDataBuy() {
    global $bankEX;
    $alldata = $bankEX->queryAllExt();
    return $alldata;
}

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

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

    if ($detailResult['flag'] == 0) {
        $billId = $detailResult['billId'];
        $flag = saveBillProductsBuy($billId);
    }

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

function saveBillDetailsBuy() {
    global $billsBuy;
    global $billsBuyDAO;
    global $supplierDAO;

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

    $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 = 0; //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 = 0; //filter_input(INPUT_POST, $ex1 . "kashfValue");      ##  قيمة الكشف
    $kashfdiscount = 0; //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");        ## الأجل
##################################################################################################################################
############################################### online bill ######################################################################
    ##############################################################################################################################
    $createdBillNo = filter_input(INPUT_POST, "createdBillNo");
    $billsssss = $billsBuyDAO->queryByBillno($billNo);
    if (count($billsssss) > 0) {
        ## bill no is the created no
        if ($billNo == $createdBillNo) {
            $billNo = generateOnlineBillNoBuy();
            $_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;
        }
    }
    $billsBuy->branchid = $_SESSION['branchId'];
    $billsBuy->userid = $_SESSION['userid'];
    $billsBuy->serverdate = date('Y-m-d h:i:s');

####################################################################################################################################
##################################################### offline bill and online bill both ############################################
    ################################################################################################################################
    $client = $supplierDAO->load($clientId);
    $clientdebtBefore = $client->suppliercurrentDebt;
    $clientdebtAfter = $clientdebtBefore + $waitvalue;

    $billsBuy->kashftype = 0; //$kashftype;
    $billsBuy->kashfplace = ''; //filter_input(INPUT_POST, $ex1 . "kashfplace");
    $billsBuy->kashfdate = '';  //filter_input(INPUT_POST, $ex1 . "kashfdate");
    $kashfId = 0; //saveDoctorlKashfDetails($clientId, $offline, 0, 0);

    $billsBuy->clientid = $clientId;
    $billsBuy->billno = $billNo;
    $billsBuy->receivedate = $receiveDate;
    $billsBuy->comment = $comment;
    $billsBuy->billdate = $billDate;
    $billsBuy->kashfid = $kashfId;
    $billsBuy->alloweddays = $allowedDays;
    $billsBuy->pricetype = $pricetype;
    $billsBuy->approvalno = $approvalNo;

    $billsBuy->productstotalprice = $productstotalprice;
    $billsBuy->kashfvalue = $kashfvalue;
    $billsBuy->kashfdiscount = $kashfdiscount;
    $billsBuy->netbillvalue = $netbillvalue;
    $billsBuy->discounttype = $discounttype;
    $billsBuy->discountvalue = $discountvalue;
    $billsBuy->finalnetbillvalue = $finalnetbillValue;
    $billsBuy->waitvalue = $waitvalue;
    $billsBuy->deleted = 0;
    $billsBuy->billstatus = 0;
    //fatma
    $billsBuy->approved = 0;
    $billsBuy->notifSeen = 0;
    $billsBuy->saveid = $_SESSION['saveid']; //fatma
    $billsBuy->approveNo = ''; //fatma
    $billsBuy->approveFile = ''; //fatma
    //--end fatma
    $billId = savePaymentDetailsBuy($billsBuy, $waitvalue, $offline);

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


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

function savePaymentDetailsBuy($billsBuy, $waitvalue, $affectNetworkNow = 0) {
    global $billsBuyDAO;
    $insurance = $card = $cash = 0;
    $paymentamethods = $_POST['paymentamethods'];
    if (empty($paymentamethods)) {

    } else {
        $N = count($paymentamethods);
        for ($i = 0; $i < $N; $i++) {
            $x = $paymentamethods[$i];
            $billsBuy->$x = 1;
            if ($x == 'insurance') {
                $billsBuy = saveInsurancePaymentBuy($billsBuy);
                $insurance = 1;
            } elseif ($x == 'card') {
                $billsBuy = saveCardPaymentBuy($billsBuy);
                $card = 1;
            } elseif ($x == 'cash') {
                $billsBuy = saveCashPaymentBuy($billsBuy);
                $cash = 1;
            }
        }
    }

    $billId = $billsBuyDAO->insert($billsBuy);
    $discountAsMoney = 0;
    if ($billsBuy->discounttype == 1) {
        //direct
        $discountAsMoney = $billsBuy->discountvalue;
    } else {
        //percentage
        $discountAsMoney = $billsBuy->netbillvalue * $billsBuy->discountvalue / 100;
    }
    //if insurance
    if ($billsBuy->insurance == 1) {
        //network pay dont affect now
        if ($affectNetworkNow == 1) {
            saveDailyEntryBuy($insurance, $card, $cash, $waitvalue, $billId, $discountAsMoney);
        }
    } else {
        saveDailyEntryBuy($insurance, $card, $cash, $waitvalue, $billId, $discountAsMoney);
    }
    return $billId;
}

function saveInsurancePaymentBuy($billsBuy) {
    global $insuranceCompaniesDAO;

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

function saveCardPaymentBuy($billsBuy) {
    $ex1 = '';
    ##in this bill card is bank
    $billsBuy->paymentnetworkid = filter_input(INPUT_POST, $ex1 . "paymentNetworks"); ## bank
    $billsBuy->cardvalue = filter_input(INPUT_POST, $ex1 . "cardValue"); ##value
    $billsBuy->netdiscountpercent = filter_input(INPUT_POST, $ex1 . "accountid");        ## account
    return $billsBuy;
}

function saveCashPaymentBuy($billsBuy) {

    $ex1 = '';
    $billsBuy->cashvalue = filter_input(INPUT_POST, $ex1 . "cashValue");

    return $billsBuy;
}

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

function saveDailyEntryBuy($insurance, $card, $cash, $waitvalue, $billId, $discountAsMoney) {
    global $dailyEntry;      ## Dailyentry
    global $accountsTreeDAO;
    global $supplier;
    global $supplierDAO;
    global $mySave;
    global $mySaveDAO;
    global $insuranceCompaniesDAO;
    global $accountDAO;
    global $billsBuyDAO;
    $total = 0;

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

    $mytransactions = new Transaction();
    $billsBuy = $billsBuyDAO->load($billId);

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

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

    if ($waitvalue != 0) {
        $client = $supplierDAO->load($billsBuy->clientid);

        if ($client->treeId > 0) {
            $treeId1 = $client->treeId;
        } else {
            $treeId1 = addTreeElement($client->suppliername, 10, 1, 0, 1, '', 0, 0); //add supplier in the tree
        }

        $dailyEntryCreditor1->value = $waitvalue;
        $dailyEntryCreditor1->accountstreeid = $treeId1;
        $dailyEntryCreditor1->pluginControllerName = 'bills.php?do=buybill';
        $dailyEntryCreditor1->pluginComment = ' تم اضافة فاتورة شراء بصريات جديدة';
        $dailyEntryCreditor1->pluginid = $billId;
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor1);
        $total = $total + $waitvalue;
    }
#########################################################################################
    if ($cash == 1) {
        $saveId = $_SESSION['saveid'];
        $mySave = $mySaveDAO->load($saveId);

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

        $dailyEntryCreditor2->value = filter_input(INPUT_POST, $ex1 . "cashValue");
        $dailyEntryCreditor2->accountstreeid = $treeId2;
        $dailyEntryCreditor2->pluginControllerName = 'bills.php?do=buybill';
        $dailyEntryCreditor2->pluginComment = ' تم اضافة فاتورة شراء بصريات جديدة';
        $dailyEntryCreditor2->pluginid = $billId;
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor2);
        $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 * ($billsBuy->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);
        }


        $dailyEntryCreditor3->value = $insRest;
        $dailyEntryCreditor3->accountstreeid = $treeId3;
        $dailyEntryCreditor3->pluginControllerName = 'bills.php?do=buybill';
        $dailyEntryCreditor3->pluginComment = ' تم اضافة فاتورة شراء بصريات جديدة';
        $dailyEntryCreditor3->pluginid = $billId;
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor3);

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


        $dailyEntryCreditor7->value = $insDiscount;
        $dailyEntryCreditor7->accountstreeid = $treeId7;
        $dailyEntryCreditor7->pluginControllerName = 'bills.php?do=buybill';
        $dailyEntryCreditor7->pluginComment = ' تم اضافة فاتورة شراء بصريات جديدة';
        $dailyEntryCreditor7->pluginid = $billId;
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor7);
        #############
        $total = $total + filter_input(INPUT_POST, $ex1 . "insuranceValue");
    }
#########################################################################################
    if ($card == 1) {
        $accountid = filter_input(INPUT_POST, $ex1 . "accountid");
        $accountData = $accountDAO->load($accountid);
        $cardValue = filter_input(INPUT_POST, $ex1 . "cardValue");

        ## bank account
        if ($accountData->treeId > 0) {
            $treeId4 = $accountData->treeId;
        } else {
            $bankid = $billsBuy->paymentnetworkid;
            //we dont add bank to tree now
            $bankData = $bankDAO->load($bankid);
//            $bankTreeData = $accountsTreeDAO->queryByName($bankData->bankname);
//            if (count($bankTreeData) == 0) {
//                $bankTreeId = addTreeElement($bankData->bankname, 21, 3, 0, 0, '', 0, 0);
//            } else {
//                $bankTreeId = $bankTreeData[0]->id;
//            }
//            $treeId4 = addTreeElement($accountData->accountname, $bankTreeId, 3, 0, 1, '', 0, 0);
            $treeId4 = addTreeElement("$accountData->accountname / $bankData->bankname", 38, 3, 0, 1, '', 0, 0);
        }


        $dailyEntryCreditor4->value = $cardValue;
        $dailyEntryCreditor4->accountstreeid = $treeId4;
        $dailyEntryCreditor4->pluginControllerName = 'bills.php?do=buybill';
        $dailyEntryCreditor4->pluginComment = ' تم اضافة فاتورة شراء بصريات جديدة';
        $dailyEntryCreditor4->pluginid = $billId;
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor4);

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



        $dailyEntryCreditor5->value = $cardDiscount;
        $dailyEntryCreditor5->accountstreeid = $treeId5;
        $dailyEntryCreditor5->pluginControllerName = 'bills.php?do=buybill';
        $dailyEntryCreditor5->pluginComment = ' تم اضافة فاتورة شراء بصريات جديدة';
        $dailyEntryCreditor5->pluginid = $billId;
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor5);


        $total = $total + filter_input(INPUT_POST, $ex1 . "cardValue");
    }
#########################################################################################
    if ($discountAsMoney != 0) {

        $dailyEntryCreditor55->value = $discountAsMoney;
        $dailyEntryCreditor55->accountstreeid = 52;
        $dailyEntryCreditor55->pluginControllerName = 'bills.php?do=buybill';
        $dailyEntryCreditor55->pluginComment = ' تم اضافة فاتورة شراء بصريات جديدة';
        $dailyEntryCreditor55->pluginid = $billId;
        array_push($dailyEntryCreditorArray, $dailyEntryCreditor55);
        $total = $total + $discountAsMoney;
    }
#########################################################################################
    $dailyEntryDebtor->value = $total;
    $dailyEntryDebtor->accountstreeid = 12;
    $dailyEntryDebtor->pluginControllerName = 'bills.php?do=buybill';
    $dailyEntryDebtor->pluginComment = ' تم اضافة فاتورة شراء بصريات جديدة';
    $dailyEntryDebtor->pluginid = $billId;
    array_push($dailyEntryDebtorArray, $dailyEntryDebtor);

    try {

        $data = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
        $dailyEntryId = $data[1];

        $billsBuy->dailyentryid = $dailyEntryId;
        $billsBuyDAO->update($billsBuy);
        $mytransactions->commit();

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

function generateOnlineBillNoBuy() {
    global $billsBuy;
    global $billsBuyEX;

    ## bill no generate

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

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

function saveBillProductsBuy($billId, $affectNetworkNow = 0) {
    global $billsProductsBuy;
    global $billsProductsBuyDAO;
    global $storeDetail;
    global $storeDetailDAO;
    global $storeDetailEX;
    global $product;
    global $billsBuyDAO;
    global $productDAO;

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


    $flag = 0;
    $affectProductNowFlag = 0;
    $billsBuy = $billsBuyDAO->load($billId);
    if ($billsBuy->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);
        $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) {

            $billsProductsBuy->billid = $billId;
            $billsProductsBuy->productid = $productId;
            $billsProductsBuy->note = $note;
            $billsProductsBuy->productno = $productNum;
            $billsProductsBuy->productprice = $productPrice;
            $billsProductsBuy->service = $service;
            $billsProductsBuy->producttotalprice = $totalProductPrice;
            $billsProductsBuy->deleted = 0;
            $billsProductsBuy->storeid = $storeId;
            $billsProductsBuy->rondomtxt = ''; //filter_input(INPUT_POST, $ex2 . 'rondomtxt' . $i);
            $billsProductsBuy->retproductno = 0; //filter_input(INPUT_POST, $ex2 . 'retproductno' . $i);
            $detailId = $billsProductsBuyDAO->insert($billsProductsBuy);
            $product = $productDAO->load($productId);
            if ($affectProductNowFlag == 1) {
                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;
                    }
                    insertStorereportupdateBuy($productId, $storeId, $productNum, $productbefore, $productafter, 1, $billId, "اضافة فاتورة شراء", "bills.php?do=buybill", $billDate);
                    //$lastBuyPriceOnePiece = $productPrice / $productNum;
                    $lastBuyPriceOnePiece = $productPrice;
                    lastAndMeanBuyPrice_SellOpticBuy($productbefore, $productNum, $productafter, $lastBuyPriceOnePiece, $detailId, $productId);
                }
            }
        }
    }
    return $flag;
}

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

function getBillDetailsBuy($billId) {
    global $smarty;
    global $supplierDAO;
    global $billsBuyDAO;
    global $bankDAO;
    global $accountDAO;
    global $paymentNetworksDAO;
    global $BranchDAO;

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

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

    if ($billsBuy->branchid == 0) {
        $smarty->assign("shopName", '');
    } else {
        $Branch = $BranchDAO->load($billsBuy->branchid);
        $smarty->assign("Branch", $Branch);
    }

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

    ## client name
    $client = $supplierDAO->load($billsBuy->clientid);
    $billsBuy->clientname = $client->suppliername;

    ## insurance company
    if ($billsBuy->insurance == 1 && $billsBuy->insurancecompanyid) {
        $insurancecompanies = $insuranceCompaniesDAO->load($billsBuy->insurancecompanyid);
        $billsBuy->companyname = $insurancecompanies->name;
        $smarty->assign("instruction", $insurancecompanies->instruction);
    }
    ## payment network
    if ($billsBuy->card == 1 && $billsBuy->paymentnetworkid) {
        $bank = $bankDAO->load($billsBuy->paymentnetworkid);
        $billsBuy->networkname = $bank->bankname;
        $account = $accountDAO->load($billsBuy->netdiscountpercent);
        $billsBuy->notifSeen = $account->accountname;
    }

    ## bill products
    $billProducts = getBillProductsBuy($billsBuy->id);
    $smarty->assign("billProducts", $billProducts);
    $smarty->assign("billProductsCount", count($billProducts));

    ## accounts Data
    $accountsData = $accountDAO->queryByBankid($billsBuy->paymentnetworkid);
    $smarty->assign('accountsData', $accountsData);

    ## bill

    $smarty->assign("bill", $billsBuy);
}

function getBillProductsBuy($billId) {
    global $productDAO;
    global $productCatDAO;
    global $billsProductsBuyEX;

    $opCount = 1;
    $frameCount = 1;

    $billProducts = $billsProductsBuyEX->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;
}

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

function updateBuy() {
    $billId = filter_input(INPUT_POST, "billId");
    updateBillDetailsBuy($billId);
    $flag = updateBillProductsBuy($billId);
    return $flag;
}

function updateBillDetailsBuy($billId) {
    global $billsBuy;
    global $billsBuyDAO;
    global $supplierDAO;
    global $SupplierdebtchangeEX;

    $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 = 0; //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 = 0; //filter_input(INPUT_POST, "kashfValue");      ##  قيمة الكشف
    $kashfdiscount = 0; //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");        ## الأجل


    $billsBuy = $billsBuyDAO->load($billId);
    $client = $supplierDAO->load($clientId);
    $amount = $waitvalue - $billsBuy->waitvalue;
    ###############################################################################
    ## reverse old  client dept
    $newBefore = $client->suppliercurrentDebt;
    $newAfter = $newBefore + $amount;


    ###############################################################################
    ## external
    $billsBuy->kashfplace = ''; //filter_input(INPUT_POST, "kashfplace");
    $billsBuy->kashfdate = ''; //filter_input(INPUT_POST, "kashfdate");

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

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

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

    $billsBuyDAO->update($billsBuy);

    emptyPaymentDataBuy($billId);
    updatePaymentDetailsBuy($billId, $waitvalue);
}

function emptyPaymentDataBuy($billId) {
    global $billsBuy;
    global $billsBuyDAO;

    $billsBuy = $billsBuyDAO->load($billId);

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

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

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

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


    $billsBuyDAO->update($billsBuy);
}

function updatePaymentDetailsBuy($billId, $waitvalue) {
    global $billsBuyDAO;
    global $insuranceCompaniesDAO;
    global $paymentNetworksDAO;

    $insurance = $card = $cash = 0;

    $billsBuy = $billsBuyDAO->load($billId);


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

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

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

                $insurance = 1;
            } elseif ($x == 'card') {


                $billsBuy->paymentnetworkid = filter_input(INPUT_POST, "paymentNetworks"); ## bank
                $billsBuy->cardvalue = filter_input(INPUT_POST, "cardValue"); ##value
                $billsBuy->netdiscountpercent = filter_input(INPUT_POST, "accountid");        ## account

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

    $billsBuyDAO->update($billsBuy);
    $discountAsMoney = 0;
    if ($billsBuy->discounttype == 1) {
        //direct
        $discountAsMoney = $billsBuy->discountvalue;
    } else {
        //percentage
        $discountAsMoney = $billsBuy->netbillvalue * $billsBuy->discountvalue / 100;
    }
    //if insurance
    if ($billsBuy->insurance == 1) {
        //network pay dont affect now
        if ($affectNetworkNow == 1) {
            reverseEntryWithItsID($billsBuy->dailyentryid);
            saveDailyEntryBuy($insurance, $card, $cash, $waitvalue, $billId, $discountAsMoney);
        }
    } else {
        reverseEntryWithItsID($billsBuy->dailyentryid);
        saveDailyEntryBuy($insurance, $card, $cash, $waitvalue, $billId, $discountAsMoney);
    }
}

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

    global $billsProductsBuy;
    global $billsProductsBuyDAO;
    global $storeDetail;
    global $storeDetailEX;
    global $storeDetailDAO;
    global $billsBuyDAO;
    $flag = 0;

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


    $affectProductNowFlag = 0;
    $billsBuy = $billsBuyDAO->load($billId);
    if ($billsBuy->insurance == 1) {
        //network pay dont affect now
        if ($affectNetworkNow == 1) {
            $affectProductNowFlag = 1;
        }
    } else {
        $affectProductNowFlag = 1;
    }
    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);
        $totalProductPrice = filter_input(INPUT_POST, 'totalProductPrice' . $i);

        $storeId = filter_input(INPUT_POST, 'storeid');
        ## existing product update it
        if ($billProductId) {
            if ($productId && $productId != -1) {
                $billsProductsBuy = $billsProductsBuyDAO->load($billProductId);
                $billsProductsBuy->productid = $productId;
                $billsProductsBuy->note = $note;
                $billsProductsBuy->productno = $productNum;
                $billsProductsBuy->productprice = $productPrice;
                $billsProductsBuy->service = $service;
                $billsProductsBuy->producttotalprice = $totalProductPrice;
                $billsProductsBuy->deleted = 0;
                $billsProductsBuy->storeid = $storeId;
                $billsProductsBuyDAO->update($billsProductsBuy);

                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;
                    }
                    insertStorereportupdateBuy($productId, $storeId, $productNum, $productbefore, $productafter, 1, $billId, "اضافة فاتورة شراء", "bills.php?do=buybill", $billDate);
                    $detailId = $billsProductsBuy->id;
                    lastAndMeanBuyPrice_SellOpticBuy($productbefore, $productNum, $productafter, $detailId, $productId);
                }
            }
        }
        ## new product insert it
        else {
            if ($productId && $productId != -1) {

                $billsProductsBuy->billid = $billId;
                $billsProductsBuy->productid = $productId;
                $billsProductsBuy->note = $note;
                $billsProductsBuy->productno = $productNum;
                $billsProductsBuy->productprice = $productPrice;
                $billsProductsBuy->service = $service;
                $billsProductsBuy->producttotalprice = $totalProductPrice;
                $billsProductsBuy->storeid = $storeId;
                $billsProductsBuy->deleted = 0;
                $detailId = $billsProductsBuyDAO->insert($billsProductsBuy);

                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;
                    }
                    insertStorereportupdateBuy($productId, $storeId, $productNum, $productbefore, $productafter, 1, $billId, "اضافة فاتورة شراء", "bills.php?do=buybill", $billDate);
                    lastAndMeanBuyPrice_SellOpticBuy($productbefore, $productNum, $productafter, $detailId, $productId);
                }
            }
        }
    }

    return $flag;
}

function lastAndMeanBuyPrice_SellOpticBuy($productquantityBefore, $productChangeAmount, $productquantityAfter, $lastBuyPriceOnePiece, $detailId, $productId) {

    global $productDAO;
    global $billsProductsBuyEX;

    $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;
    }
    $Bast = ($productquantityBefore * $buyProduct->meanbuyprice) + ($productChangeAmount * $lastBuyPriceOnePiece);
    $makam = $productquantityAfter;
    $meanBuyPrice = round(($Bast / $makam), 3);
    ##2-save them
    $buyProduct->meanbuyprice = $meanBuyPrice;
    $buyProduct->lastbuyprice = $lastBuyPriceOnePiece;
    $productDAO->update($buyProduct);
    if (isset($detailId) && !empty($detailId)) {
        $billsProductsBuyEX->updatePrices_f_optic($buyProduct->lastbuyprice, $buyProduct->meanbuyprice, $detailId);
    }
}

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

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

?>