<?php

namespace App\Http\Controllers;

use App\Imports\CityImport;
use App\Imports\GovImport;
use App\Imports\PlaceImport;
use App\Imports\TestImport;
use App\Services\Average;
use App\Traits\GeneralTrait;
use Illuminate\Http\Request;


use App\Models\AcccountingManual;
use App\Models\OutcomManufacturingModel;
use App\Models\UsersMoves;
use App\Models\Admin;
use App\Models\Stores;
use App\Models\Measuerments;
use App\Models\Brands;
use App\Models\Assets;
use App\Models\Virables;
use App\Models\SubVirables;
use App\Models\Taxes;
use App\Models\ItemsGroups;
use App\Models\ProductMoves;
use App\Models\ProductUnits;
use App\Models\Products;
use App\Models\SubImages;
use App\Models\AssemblyProducts;
use App\Models\Coins;
use App\Models\StartPeriods;
use App\Models\ProductsStartPeriods;
use App\Models\ProductsStores;
use App\Models\ProductsQty;
use App\Models\Journalizing;
use App\Models\JournalizingDetails;
use App\Models\GeneralDaily;
use App\Models\ProductsVira;
use App\Models\SubscribeTypes;
use App\Models\Inventory;
use App\Models\ProductInventory;
use App\Models\Settlement;
use App\Models\ProductSettlement;
use App\Models\StorsTransfers;
use App\Models\ProductsStoresTransfers;
use App\Models\BarcodeSettings;
use App\Models\BarcodeProducts;
use App\Models\BarcodeShow;
use App\Models\ProductsPurchases;
use App\Models\ProductSales;
use App\Models\Employess;
use App\Models\EmpPOSStores;
use App\Models\ShippingCompany;
use App\Models\CostCenter;
use App\Models\SalesDefaultData;
use App\Models\StoresDefaultData;
use App\Models\PermissionToRecivedGoods;
use App\Models\ProductsPermissionToRecivedGoods;
use App\Models\PermissionToExchangeGoods;
use App\Models\StoreCountSales;
use App\Models\Branches;
use App\Models\Consists;
use App\Models\ManufactureCompany;
use App\Models\ProductsConsists;
use App\Models\DefaultDataShowHide;
use App\Models\ProductsPermissionToExchangeGoods;
use App\Models\Customers;
use App\Models\EmpExc;
use App\Models\ImportNewProds;
use App\Models\ImportNewProdsStart;
use App\Models\PurchasesDefaultData;
use App\Models\MaintainceDefaultData;
use App\Models\ModuleSettingsNum;
use App\Models\Vendors;
use App\Models\Purchases;
use App\Models\ChecksTypes;
use App\Models\ReciptVoucher;
use App\Models\PaymentVoucher;
use App\Models\Vouchers;
use App\Models\ReciptVoucherDetails;
use App\Models\PaymentVoucherDetails;
use App\Models\StoresMoves;
use App\Models\ReturnStorsTransfer;
use App\Models\ReturnProductsStoresTransfers;
use App\Models\Sales;
use App\Models\InstallmentCompanies;
use App\Models\SafesBanks;
use App\Models\ProductSalesSubscribes;
use App\Models\ProductsExecutingReceiving;
use App\Models\ProductsQuote;
use App\Models\ProductSalesOrder;
use App\Models\ProductsPurchasesOrder;
use App\Models\AdditionalProducts;
use App\Models\VAProducts;
use App\Models\VAPrice;
use App\Models\VAQty;
use App\Models\Notifications;
use App\Models\ExpireDateQty;
use App\Models\AttendDepartureImport;
use App\Models\Attendance;
use App\Models\Departure;
use App\Models\AttendanceEmp;
use App\Models\DepartureEmp;
use App\Models\AttendencePolicyEmp;
use App\Models\DepaarturePolicyEmp;
use App\Models\FifoQty;

use Illuminate\Support\Facades\Log;
use Str;
use DB;
use App\Imports\ImportAccountingManual;
use App\Imports\AttendImport;
use App\Imports\Vendorss;
use App\Imports\Voucher;
use App\Imports\CustGroupss;
use App\Imports\ImpBrands;
use App\Imports\ProductFileStart;
use App\Imports\ProductFile;
use App\Imports\ProductUnit;
use App\Imports\ProductMovess;
use App\Imports\Groupss;
use App\Imports\ImportAssets;
use App\Imports\Clients;
use App\Imports\EmpExcc;
use App\Exports\StoresQtyyy;
use App\Exports\ExportDelegateSalesDetails;
use App\Exports\ExportProfitDelegateSalesDetails;
use App\Exports\ExportStoresCosts;
use App\Exports\ExportInstallmentCompaniesSales;
use App\Exports\StoresQtyyyRased;
use App\Exports\StoresQtyyyRasedSerial;
use App\Exports\StoresBalances;
use App\Exports\StoresBalancesCat;
use App\Exports\ExportSalesBillsReport;
use App\Exports\ExportPurchasesBillsReport;
use App\Exports\ExportStoresMovesReport;
use App\Exports\ExportStoresTransferReport;
use App\Exports\ExportSafesTransferReport;
use App\Exports\ExportProductMoveDetails;
use App\Exports\ExportCompareSalesPrice;
use App\Exports\ExportMostSalesProducts;
use App\Exports\ExportProfitSalesProduct;
use App\Exports\ExportClientsStatement;
use App\Exports\ExportVendorsStatement;
use App\Exports\ExportClientAccountStatement;
use App\Exports\ExportVendorAccountStatement;
use App\Exports\ExportSalesCustomersGroupsFilter;
use App\Exports\ExportInventorySerial;
use App\Exports\ExportReturnSalesBillsReport;
use App\Exports\ExportReturnPurchasesBillsReport;
use App\Exports\ExportMaintenance_Tune;
use App\Exports\ExportMaintanceSalesReport;
use App\Exports\ExportAllProducts;
use App\Exports\ExportAllVendors;
use App\Exports\ExportAllPaymentVoucher;
use App\Exports\ExportAllJournalizing;
use App\Exports\ExportAllOpeningEntries;
use App\Exports\ExportAllReceiptVoucher;
use App\Exports\ExportAllSettlement;
use App\Exports\IncomListExport;
use App\Exports\IncomListExportDetails;
use App\Exports\ExportAllClients;
use App\Exports\ExportAllEmployees;
use App\Exports\ExportGeneralDailyFilter;
use App\Exports\ExpensesListExport;
use App\Exports\ExportSalesDetailsBillsReport;
use App\Exports\ExportPurchasesDetailsBillsReport;
use App\Exports\ExpensesListExportDetails;
use App\Imports\StratPeriod;
use App\Imports\ImportCustomerFollowUp;
use App\Imports\ImportExporting_Checks;
use App\Imports\ImportIncoming_checks;
use App\Imports\ImportInsurance_Paper;
use App\Imports\ProStratPeriod;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Excel\Facades\DOMPDF;
 use Illuminate\Support\Facades\Artisan;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class ImportExportController extends Controller
{
    use GeneralTrait;
    function __construct()
    {

    $this->middleware('permission:استيراد ملفات اكسيل', ['only' => ['ExportProductsPage','ImportProducts','ImportProductsUnits','ImportGroups']]);

    }


    //Page
    public function ExportProductsPage(){

        return view('admin.Export.ImportProducts');

    }

    //Export   ======================================================================================

    public function ExportGeneralDailyFilter(Request $request){

    $from = $request->get('From');
    $to = $request->get('To');
    $coin = $request->get('Coin');
    $account = $request->get('Account');
    $type = $request->get('Type');
    $cost = $request->get('Cost_Center');
    $user = $request->get('User');


    return Excel::download(new ExportGeneralDailyFilter(['from'=>$from,'to'=>$to , 'coin'=>$coin,'account'=>$account , 'type'=>$type,'cost'=>$cost,'user'=>$user]), 'GeneralDaily.xlsx');


    }

    public function ExportStoresQtyyy(){

    $store=request('Store');
    $group=request('Group');
    $brand=request('Brand');
    $branch=request('Branch');
    $product_Name=request('Product_Name');
    $product_Code=request('Product_Code');
    $zero=request('Zero');


    return Excel::download(new StoresQtyyy(['store'=>$store,'group'=>$group , 'brand'=>$brand,'branch'=>$branch , 'product_Name'=>$product_Name,'product_Code'=>$product_Code,'zero'=>$zero]), 'StoresQtyTaklfa.xlsx');

    //return Excel::download(new StoresQtyyy(['store'=>$store,'group'=>$group , 'brand'=>$brand,'branch'=>$branch , 'product_Name'=>$product_Name,'product_Code'=>$product_Code,'zero'=>$zero]), 'StoresQty.pdf');




    }

    public function ExportStoresQtyyyRased(){

    $store=request('Store');
    $group=request('Group');
    $brand=request('Brand');
    $branch=request('Branch');
    $product_Name=request('Product_Name');
    $product_Code=request('Product_Code');
    $zero=request('Zero');


    return Excel::download(new StoresQtyyyRased(['store'=>$store,'group'=>$group , 'brand'=>$brand,'branch'=>$branch , 'product_Name'=>$product_Name,'product_Code'=>$product_Code,'zero'=>$zero]), 'StoresQtyRased.xlsx');

    //return Excel::download(new StoresQtyyy(['store'=>$store,'group'=>$group , 'brand'=>$brand,'branch'=>$branch , 'product_Name'=>$product_Name,'product_Code'=>$product_Code,'zero'=>$zero]), 'StoresQty.pdf');




    }

    public function ExportStoresQtyyyRasedSerial(){

    $store=request('Store');
    $group=request('Group');
    $brand=request('Brand');
    $branch=request('Branch');
    $product_Name=request('Product_Name');
    $product_Code=request('Product_Code');
    $zero=request('Zero');


    return Excel::download(new StoresQtyyyRasedSerial(['store'=>$store,'group'=>$group , 'brand'=>$brand,'branch'=>$branch , 'product_Name'=>$product_Name,'product_Code'=>$product_Code,'zero'=>$zero]), 'StoresQtyRasedSerial.xlsx');

    //return Excel::download(new StoresQtyyy(['store'=>$store,'group'=>$group , 'brand'=>$brand,'branch'=>$branch , 'product_Name'=>$product_Name,'product_Code'=>$product_Code,'zero'=>$zero]), 'StoresQty.pdf');




    }



    public function ExportStoresBalancesNew(){

    $store=request('Store');
    $group=request('Group');
    $brand=request('Brand');
    $branch=request('Branch');
    $product_Name=request('Product_Name');
    $product_Code=request('Product_Code');
    $zero=request('Zero');


    return Excel::download(new StoresBalances(['store'=>$store,'group'=>$group , 'brand'=>$brand,'branch'=>$branch , 'product_Name'=>$product_Name,'product_Code'=>$product_Code,'zero'=>$zero]), 'StoreeBalances.xlsx');


    }

    public function ExportStoresBalancesCat(){

    $store=request('Store');
    $group=request('Group');
    $brand=request('Brand');
    $branch=request('Branch');
    $product_Name=request('Product_Name');
    $product_Code=request('Product_Code');
    $zero=request('Zero');


    return Excel::download(new StoresBalancesCat(['store'=>$store,'group'=>$group , 'brand'=>$brand,'branch'=>$branch , 'product_Name'=>$product_Name,'product_Code'=>$product_Code,'zero'=>$zero]), 'StoresBalancesCat.xlsx');


    }

    public function ExportDelegateSalesDetails(){

    $from=request('From');
    $to=request('To');
    $delegate=request('Delegate');
    $branch=request('Branch');
    $store=request('Store');
    $group=request('Group');
    $brand=request('Brand');
    $payment_Method=request('Payment_Method');

    return Excel::download(new ExportDelegateSalesDetails(['from'=>$from,'to'=>$to , 'delegate'=>$delegate,'branch'=>$branch , 'store'=>$store,'group'=>$group,'brand'=>$brand,'payment_Method'=>$payment_Method]), 'ExportDelegateSalesDetails.xlsx');


    }

    public function ExportProfitDelegateSalesDetails(){

    $from=request('From');
    $to=request('To');
    $delegate=request('Delegate');
    $branch=request('Branch');
    $store=request('Store');
    $group=request('Group');
    $brand=request('Brand');
    $payment_Method=request('Payment_Method');

    return Excel::download(new ExportProfitDelegateSalesDetails(['from'=>$from,'to'=>$to , 'delegate'=>$delegate,'branch'=>$branch , 'store'=>$store,'group'=>$group,'brand'=>$brand,'payment_Method'=>$payment_Method]), 'ExportDelegateSalesDetails.xlsx');


    }

    public function ExportStoresCosts(){

    $store=request('Store');
    $group=request('Group');
    $brand=request('Brand');
    $branch=request('Branch');
    $product_Name=request('Product_Name');
    $product_Code=request('Product_Code');
    $zero=request('Zero');


    return Excel::download(new ExportStoresCosts(['store'=>$store,'group'=>$group , 'brand'=>$brand,'branch'=>$branch , 'product_Name'=>$product_Name,'product_Code'=>$product_Code,'zero'=>$zero]), 'StoresCosts.xlsx');


    }

    public function ExportInstallmentCompaniesSales(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $clients_Group=request('Clients_Group');
    $cost_Center=request('Cost_Center');
    $coin=request('Coin');
    $code=request('Code');
    $shift_Code=request('Shift_Code');
    $refrence_Number=request('Refrence_Number');
    $store=request('Store');
    $safe=request('Safe');
    $client=request('Client');
    $payment_Method=request('Payment_Method');
    $delegate=request('Delegate');
    $executor=request('Executor');
    $user=request('User');
    $shipping_Company=request('Shipping_Company');
    $types=request('Type');
    $installCompany=request('InstallCompany');
    $contractNumber=request('ContractNumber');
    $payFees=request('PayFees');


    return Excel::download(new ExportInstallmentCompaniesSales(['from'=>$from,'to'=>$to , 'branch'=>$branch,'clients_Group'=>$clients_Group , 'cost_Center'=>$cost_Center,'coin'=>$coin,'code'=>$code,'shift_Code'=>$shift_Code,'refrence_Number'=>$refrence_Number,'store'=>$store,'safe'=>$safe,'client'=>$client,'payment_Method'=>$payment_Method,'delegate'=>$delegate,'executor'=>$executor,'user'=>$user,'shipping_Company'=>$shipping_Company,'types'=>$types,'installCompany'=>$installCompany,'contractNumber'=>$contractNumber,'payFees'=>$payFees]), 'ExportInstallmentCompaniesSales.xlsx');


    }


    public function ExportSalesBillsReport(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $clients_Group=request('Clients_Group');
    $cost_Center=request('Cost_Center');
    $coin=request('Coin');
    $code=request('Code');
    $shift_Code=request('Shift_Code');
    $refrence_Number=request('Refrence_Number');
    $store=request('Store');
    $safe=request('Safe');
    $client=request('Client');
    $payment_Method=request('Payment_Method');
    $delegate=request('Delegate');
    $executor=request('Executor');
    $user=request('User');
    $shipping_Company=request('Shipping_Company');
    $types=request('Type');
    $typeX=request('typeX');


    return Excel::download(new ExportSalesBillsReport(['from'=>$from,'to'=>$to , 'branch'=>$branch,'clients_Group'=>$clients_Group , 'cost_Center'=>$cost_Center,'coin'=>$coin,'code'=>$code,'shift_Code'=>$shift_Code,'refrence_Number'=>$refrence_Number,'store'=>$store,'safe'=>$safe,'client'=>$client,'payment_Method'=>$payment_Method,'delegate'=>$delegate,'executor'=>$executor,'user'=>$user,'shipping_Company'=>$shipping_Company,'types'=>$types,'typeX'=>$typeX]), 'ExportSalesBillsReport.xlsx');


    }


    public function ExportPurchasesBillsReport(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $clients_Group=request('Clients_Group');
    $cost_Center=request('Cost_Center');
    $coin=request('Coin');
    $code=request('Code');
    $refrence_Number=request('Refrence_Number');
    $store=request('Store');
    $safe=request('Safe');
    $client=request('Vendor');
    $payment_Method=request('Payment_Method');
    $delegate=request('Delegate');
    $user=request('User');
    $shipping_Company=request('Shipping_Company');
    $types=request('Type');
    $typeX=request('typeX');




    return Excel::download(new ExportPurchasesBillsReport(['from'=>$from,'to'=>$to , 'branch'=>$branch,'clients_Group'=>$clients_Group , 'cost_Center'=>$cost_Center,'coin'=>$coin,'code'=>$code,'refrence_Number'=>$refrence_Number,'store'=>$store,'safe'=>$safe,'client'=>$client,'payment_Method'=>$payment_Method,'delegate'=>$delegate,'user'=>$user,'shipping_Company'=>$shipping_Company,'types'=>$types,'typeX'=>$typeX]), 'ExportPurchasesBillsReport.xlsx');


    }


    public function ExportSalesDetailsBillsReport(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $clients_Group=request('Clients_Group');
    $cost_Center=request('Cost_Center');
    $coin=request('Coin');
    $code=request('Code');
    $shift_Code=request('Shift_Code');
    $refrence_Number=request('Refrence_Number');
    $store=request('Store');
    $safe=request('Safe');
    $client=request('Client');
    $payment_Method=request('Payment_Method');
    $delegate=request('Delegate');
    $executor=request('Executor');
    $user=request('User');
    $shipping_Company=request('Shipping_Company');
    $types=request('Type');
    $typeX=request('typeX');


    return Excel::download(new ExportSalesDetailsBillsReport(['from'=>$from,'to'=>$to , 'branch'=>$branch,'clients_Group'=>$clients_Group , 'cost_Center'=>$cost_Center,'coin'=>$coin,'code'=>$code,'shift_Code'=>$shift_Code,'refrence_Number'=>$refrence_Number,'store'=>$store,'safe'=>$safe,'client'=>$client,'payment_Method'=>$payment_Method,'delegate'=>$delegate,'executor'=>$executor,'user'=>$user,'shipping_Company'=>$shipping_Company,'types'=>$types,'typeX'=>$typeX]), 'ExportSalesBillsReport.xlsx');


    }


    public function ExportPurchasesDetailsBillsReport(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $clients_Group=request('Clients_Group');
    $cost_Center=request('Cost_Center');
    $coin=request('Coin');
    $code=request('Code');
    $refrence_Number=request('Refrence_Number');
    $store=request('Store');
    $safe=request('Safe');
    $client=request('Vendor');
    $payment_Method=request('Payment_Method');
    $delegate=request('Delegate');
    $user=request('User');
    $shipping_Company=request('Shipping_Company');
    $types=request('Type');
    $typeX=request('typeX');




    return Excel::download(new ExportPurchasesDetailsBillsReport(['from'=>$from,'to'=>$to , 'branch'=>$branch,'clients_Group'=>$clients_Group , 'cost_Center'=>$cost_Center,'coin'=>$coin,'code'=>$code,'refrence_Number'=>$refrence_Number,'store'=>$store,'safe'=>$safe,'client'=>$client,'payment_Method'=>$payment_Method,'delegate'=>$delegate,'user'=>$user,'shipping_Company'=>$shipping_Company,'types'=>$types,'typeX'=>$typeX]), 'ExportPurchasesBillsReport.xlsx');


    }


    public function ExpensesListExportDetails(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $safe=request('Safe');
    $account=request('Account');
    $subAccount=request('SubAccount');





    return Excel::download(new ExpensesListExportDetails(['from'=>$from,'to'=>$to , 'branch'=>$branch,'safe'=>$safe , 'account'=>$account,'subAccount'=>$subAccount]), 'ExpensesListExport.xlsx');


    }

    public function ExpensesListExport(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $safe=request('Safe');
    $account=request('Account');
    $subAccount=request('SubAccount');





    return Excel::download(new ExpensesListExport(['from'=>$from,'to'=>$to , 'branch'=>$branch,'safe'=>$safe , 'account'=>$account,'subAccount'=>$subAccount]), 'ExpensesListExport.xlsx');


    }


    public function IncomListExport(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $safe=request('Safe');
    $account=request('Account');
    $subAccount=request('SubAccount');





    return Excel::download(new IncomListExport(['from'=>$from,'to'=>$to , 'branch'=>$branch,'safe'=>$safe , 'account'=>$account,'subAccount'=>$subAccount]), 'ExpensesListExport.xlsx');


    }


    public function IncomListExportDetails(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $safe=request('Safe');
    $account=request('Account');
    $subAccount=request('SubAccount');





    return Excel::download(new IncomListExportDetails(['from'=>$from,'to'=>$to , 'branch'=>$branch,'safe'=>$safe , 'account'=>$account,'subAccount'=>$subAccount]), 'ExpensesListExport.xlsx');


    }


    public function ExportReturnSalesBillsReport(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $clients_Group=request('Clients_Group');
    $cost_Center=request('Cost_Center');
    $coin=request('Coin');
    $code=request('Code');
    $shift_Code=request('Shift_Code');
    $refrence_Number=request('Refrence_Number');
    $store=request('Store');
    $safe=request('Safe');
    $client=request('Client');
    $payment_Method=request('Payment_Method');
    $delegate=request('Delegate');
    $executor=request('Executor');
    $user=request('User');
    $shipping_Company=request('Shipping_Company');
    $types=request('Type');
    $typeX=request('typeX');


    return Excel::download(new ExportReturnSalesBillsReport(['from'=>$from,'to'=>$to , 'branch'=>$branch,'clients_Group'=>$clients_Group , 'cost_Center'=>$cost_Center,'coin'=>$coin,'code'=>$code,'shift_Code'=>$shift_Code,'refrence_Number'=>$refrence_Number,'store'=>$store,'safe'=>$safe,'client'=>$client,'payment_Method'=>$payment_Method,'delegate'=>$delegate,'executor'=>$executor,'user'=>$user,'shipping_Company'=>$shipping_Company,'types'=>$types,'typeX'=>$typeX]), 'ExportReturnSalesBillsReport.xlsx');


    }


    public function ExportReturnPurchasesBillsReport(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $clients_Group=request('Clients_Group');
    $cost_Center=request('Cost_Center');
    $coin=request('Coin');
    $code=request('Code');
    $refrence_Number=request('Refrence_Number');
    $store=request('Store');
    $safe=request('Safe');
    $client=request('Vendor');
    $payment_Method=request('Payment_Method');
    $delegate=request('Delegate');
    $user=request('User');
    $shipping_Company=request('Shipping_Company');
    $types=request('Type');
    $typeX=request('typeX');




    return Excel::download(new ExportReturnPurchasesBillsReport(['from'=>$from,'to'=>$to , 'branch'=>$branch,'clients_Group'=>$clients_Group , 'cost_Center'=>$cost_Center,'coin'=>$coin,'code'=>$code,'refrence_Number'=>$refrence_Number,'store'=>$store,'safe'=>$safe,'client'=>$client,'payment_Method'=>$payment_Method,'delegate'=>$delegate,'user'=>$user,'shipping_Company'=>$shipping_Company,'types'=>$types,'typeX'=>$typeX]), 'ExportReturnPurchasesBillsReport.xlsx');


    }


    public function ExportStoresMovesReport(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $store=request('Store');
    $safe=request('Safe');
    $account=request('Account');
    $type=request('Type');
    $user=request('User');
    $shipping_Company=request('Shipping_Company');
    $cost_Center=request('Cost_Center');
    $coin=request('Coin');
    $sadr=request('sadr');
    $ward=request('ward');



    return Excel::download(new ExportStoresMovesReport(['from'=>$from,'to'=>$to , 'branch'=>$branch,'store'=>$store , 'safe'=>$safe,'account'=>$account,'type'=>$type,'user'=>$user,'shipping_Company'=>$shipping_Company,'cost_Center'=>$cost_Center,'coin'=>$coin,'sadr'=>$sadr,'ward'=>$ward]), 'ExportStoresMovesReport.xlsx');


    }

    public function ExportStoresTransferReport(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $coin=request('Coin');
    $code=request('Code');
    $value=request('Value');
    $qty=request('Qty');
    $fromStore=request('FromStore');
    $toStore=request('ToStore');
    $delegate=request('Delegate');
    $user=request('User');
    $shipping_Company=request('Shipping_Company');
    $types=request('Type');

    return Excel::download(new ExportStoresTransferReport(['from'=>$from,'to'=>$to , 'branch'=>$branch,'coin'=>$coin , 'code'=>$code,'value'=>$value,'qty'=>$qty,'fromStore'=>$fromStore,'toStore'=>$toStore,'delegate'=>$delegate,'user'=>$user,'shipping_Company'=>$shipping_Company,'types'=>$types]), 'ExportStoresTransferReport.xlsx');


    }

    public function ExportSafesTransferReport(){

    $from=request('From');
    $to=request('To');
    $branch=request('Branch');
    $coin=request('Coin');
    $code=request('Code');
    $value=request('Value');
    $fromSafe=request('FromSafe');
    $toSafe=request('ToSafe');
    $delegate=request('Delegate');
    $user=request('User');
    $types=request('Type');

    return Excel::download(new ExportSafesTransferReport(['from'=>$from,'to'=>$to , 'branch'=>$branch,'coin'=>$coin , 'code'=>$code,'value'=>$value,'fromSafe'=>$fromSafe,'toSafe'=>$toSafe,'delegate'=>$delegate,'user'=>$user,'types'=>$types]), 'ExportSafesTransferReport.xlsx');


    }


    public function ExportProductMoveDetails(){

    $from=request('From');
    $to=request('To');
    $store=request('Store');
    $type=request('Type');
    $safe=request('Safe');
    $group=request('Group');
    $brand=request('Brand');
    $user=request('User');
    $branch=request('Branch');
    $product_Name=request('Product_Name');
    $product_Code=request('Product_Code');
    $payment_method=request('Payment_Method');
    return Excel::download(new ExportProductMoveDetails(['from'=>$from,'to'=>$to , 'store'=>$store,'type'=>$type , 'safe'=>$safe,'group'=>$group,'brand'=>$brand,'user'=>$user,'branch'=>$branch,'product_Name'=>$product_Name,'product_Code'=>$product_Code,'payment_method'=>$payment_method]), 'ExportProductMoveDetails.xlsx');


    }

    public function ExportCompareSalesPrice(){

    $from=request('From');
    $to=request('To');
    $store=request('Store');
    $type=request('Type');
    $safe=request('Safe');
    $group=request('Group');
    $brand=request('Brand');
    $user=request('User');
    $branch=request('Branch');
    $product_Name=request('Product_Name');
    $product_Code=request('Product_Code');
    $delegate=request('Delegate');


    return Excel::download(new ExportCompareSalesPrice(['from'=>$from,'to'=>$to , 'store'=>$store,'type'=>$type , 'safe'=>$safe,'group'=>$group,'brand'=>$brand,'user'=>$user,'branch'=>$branch,'product_Name'=>$product_Name,'product_Code'=>$product_Code,'delegate'=>$delegate]), 'ExportCompareSalesPrice.xlsx');


    }


    public function ExportMostSalesProducts(){

    $from=request('From');
    $to=request('To');
    $store=request('Store');
    $safe=request('Safe');
    $group=request('Group');
    $brand=request('Brand');
    $branch=request('Branch');
    $product_Name=request('Product_Name');
    $product_Code=request('Product_Code');

    return Excel::download(new ExportMostSalesProducts(['from'=>$from,'to'=>$to , 'store'=>$store,'safe'=>$safe , 'group'=>$group,'brand'=>$brand,'branch'=>$branch,'product_Name'=>$product_Name,'product_Code'=>$product_Code]), 'ExportMostSalesProducts.xlsx');


    }

    public function ExportProfitSalesProduct(){

    $branch=request('Branch');
    $store=request('Store');
    $group=request('Group');
    $brand=request('Brand');
    $product_Name=request('Product_Name');
    $product_Code=request('Product_Code');


    return Excel::download(new ExportProfitSalesProduct(['branch'=>$branch,'store'=>$store , 'group'=>$group,'brand'=>$brand , 'product_Name'=>$product_Name,'product_Code'=>$product_Code]), 'ExportProfitSalesProduct.xlsx');


    }

    public function ExportClientsStatement(){

    $from=request('From');
    $to=request('To');
    $account=request('Account');


    return Excel::download(new ExportClientsStatement(['from'=>$from,'to'=>$to , 'account'=>$account]), 'ExportClientsStatement.xlsx');


    }

    public function ExportVendorsStatement(){

    $from=request('From');
    $to=request('To');
    $account=request('Account');


    return Excel::download(new ExportVendorsStatement(['from'=>$from,'to'=>$to , 'account'=>$account]), 'ExportVendorsStatement.xlsx');


    }

    public function ExportClientAccountStatement(){

    $from=request('From');
    $to=request('To');
    $cost_Center=request('Cost_Center');
    $coin=request('Coin');
    $client=request('Client');
    $payment_Method=request('Payment_Method');
    $types=request('Type');

    return Excel::download(new ExportClientAccountStatement(['from'=>$from,'to'=>$to , 'cost_Center'=>$cost_Center,'coin'=>$coin,'client'=>$client , 'payment_Method'=>$payment_Method,'types'=>$types]), 'ExportClientAccountStatement.xlsx');


    }


    public function ExportVendorAccountStatement(){

    $from=request('From');
    $to=request('To');
    $cost_Center=request('Cost_Center');
    $coin=request('Coin');
    $client=request('Vendor');
    $payment_Method=request('Payment_Method');
    $types=request('Type');

    return Excel::download(new ExportVendorAccountStatement(['from'=>$from,'to'=>$to , 'cost_Center'=>$cost_Center,'coin'=>$coin,'client'=>$client , 'payment_Method'=>$payment_Method,'types'=>$types]), 'ExportVendorAccountStatement.xlsx');


    }

    public function ExportInventorySerial(){

    $Group=request('Group');
    $Brand=request('Brand');
    $Product_Name=request('Product_Name');
    $Product_Code=request('Product_Code');

    return Excel::download(new ExportInventorySerial(['Group'=>$Group,'Brand'=>$Brand , 'Product_Name'=>$Product_Name,'Product_Code'=>$Product_Code]), 'ExportInventorySerial.xlsx');


    }

    public function ExportSalesCustomersGroupsFilter(){

    $From=request('From');
    $To=request('To');
    $group=request('group');
    $Client=request('Client');

    return Excel::download(new ExportSalesCustomersGroupsFilter(['From'=>$From,'To'=>$To , 'group'=>$group,'Client'=>$Client]), 'ExportSalesCustomersGroupsFilter.xlsx');


    }

    public function ExportMaintanceSalesReport(){

    $from = request('from');
    $to = request('to');
    $Store = request('Store');
    $Client = request('Client');
    $Recipient = request('Recipient');
    $Eng = request('Eng');
    $Branch = request('Branch');
    $code = request('code');
    $User = request('User');

    return Excel::download(new ExportMaintanceSalesReport(['from'=>$from,'to'=>$to , 'Store'=>$Store,'Client'=>$Client,'Recipient'=>$Recipient,'Eng'=>$Eng , 'Branch'=>$Branch,'code'=>$code,'User'=>$User]), 'ExportMaintanceSalesReport.xlsx');


    }

    public function ExportMaintenance_Tune(){

    $from = request('from');
    $to = request('to');
    $Store = request('Store');
    $Recipient = request('Recipient');
    $Eng = request('Eng');
    $Branch = request('Branch');
    $Group = request('Group');
    $Brand = request('Brand');
    $User = request('User');
    $code = request('code');
    $Name = request('Name');

    return Excel::download(new ExportMaintenance_Tune(['from'=>$from,'to'=>$to , 'Store'=>$Store,'Recipient'=>$Recipient,'Eng'=>$Eng,'Branch'=>$Branch , 'Group'=>$Group,'Brand'=>$Brand,'User'=>$User,'code'=>$code,'Name'=>$Name]), 'ExportMaintenance_Tune.xlsx');


    }





    // ============= Export Sechdule ==============


    public function ExportAllProducts(){


        return Excel::download(new ExportAllProducts(), 'Products.xlsx');


    }

    public function ExportAllVendors(){


        return Excel::download(new ExportAllVendors(), 'Vendors.xlsx');


    }

    public function ExportAllPaymentVoucher(){


        return Excel::download(new ExportAllPaymentVoucher(), 'PaymentVouchers.xlsx');


    }

    public function ExportAllJournalizing(){


        return Excel::download(new ExportAllJournalizing(), 'Journalizing.xlsx');


    }

    public function ExportAllOpeningEntries(){


        return Excel::download(new ExportAllOpeningEntries(), 'OpeningEntries.xlsx');


    }

    public function ExportAllSettlement(){


        return Excel::download(new ExportAllSettlement(), 'Settlement.xlsx');


    }
    public function ExportAllReceiptVoucher(){


        return Excel::download(new ExportAllReceiptVoucher(), 'ReciptVouchers.xlsx');


    }

    public function ExportAllClients(){


        return Excel::download(new ExportAllClients(), 'Clients.xlsx');


    }

    public function ExportAllEmployees(){


        return Excel::download(new ExportAllEmployees(), 'Employees.xlsx');


    }




    // ============= End Export Sechdule ==============


    //Import  =======================================================================================


    function ImportProducts(Request $request)
    {
        try {
            DB::beginTransaction();

        $this->validate($request, [
            'File' => 'required|mimes:xls,xlsx'

        ],

            [
                'File.required' => trans('admin.FileRequired'),
            ]);

        $file = $request->File;
        Excel::import(new ProductFile,$file);

        $Products=ImportNewProds::where('Num',1)->get();
        foreach($Products as $pro){


            $ID = DB::table('products')->insertGetId(

                array(

                    'P_Type' => $pro->Type,
                    'P_Ar_Name' => $pro->Name,
                    'P_En_Name' => $pro->Name,
                    'Brand' => $pro->Brand,
                    'Group' => $pro->Group,
                    'Code_Type' => $pro->Code_Type,
                    'World_Code' => $pro->World_Code,
                    'Weight' => $pro->Weight,
                    'SearchCode1' => $pro->Search_Code,
                    'Tax' => 1,
                    'Validity' => 1,
                    'Store_Show' => 0,
                    'Status' => 0,

                )
            );


            $uu['Rate']=$pro->Rate;
            $uu['Barcode']=$pro->Barcode;
            $uu['Price']=$pro->Price_1;
            $uu['Price_Two']=$pro->Price_2;
            $uu['Price_Three']=$pro->Price_3;
            $uu['Def']=$pro->Def;
            $uu['P_Ar_Name']=$pro->Name;
            $uu['P_En_Name']=$pro->Name;
            $uu['P_Type']=$pro->Type;
            $uu['Unit']=$pro->Unit;
            $uu['Product']=$ID;
            $uu['Brand']=$pro->Brand;
            $uu['Group']=$pro->Group;
            ProductUnits::create($uu);

            $Pro2=ImportNewProds::where('Name',$pro->Name)
                ->where('Num',2)->first();

            if(!empty($Pro2)){
                $uu['Rate']=$Pro2->Rate;
                $uu['Barcode']=$Pro2->Barcode;
                $uu['Price']=$Pro2->Price_1;
                $uu['Price_Two']=$Pro2->Price_2;
                $uu['Price_Three']=$Pro2->Price_3;
                $uu['Def']=$Pro2->Def;
                $uu['P_Ar_Name']=$Pro2->Name;
                $uu['P_En_Name']=$Pro2->Name;
                $uu['P_Type']=$Pro2->Type;
                $uu['Unit']=$Pro2->Unit;
                $uu['Product']=$ID;
                $uu['Brand']=$pro->Brand;
                $uu['Group']=$pro->Group;
                ProductUnits::create($uu);
            }

            $Pro3=ImportNewProds::where('Name',$pro->Name)
                ->where('Num',3)->first();

            if(!empty($Pro3)){
                $uu['Rate']=$Pro3->Rate;
                $uu['Barcode']=$Pro3->Barcode;
                $uu['Price']=$Pro3->Price_1;
                $uu['Price_Two']=$Pro3->Price_2;
                $uu['Price_Three']=$Pro3->Price_3;
                $uu['Def']=$Pro3->Def;
                $uu['P_Ar_Name']=$Pro3->Name;
                $uu['P_En_Name']=$Pro3->Name;
                $uu['P_Type']=$Pro3->Type;
                $uu['Unit']=$Pro3->Unit;
                $uu['Product']=$ID;
                $uu['Brand']=$pro->Brand;
                $uu['Group']=$pro->Group;
                ProductUnits::create($uu);

            }


            $Pro4=ImportNewProds::where('Name',$pro->Name)
                ->where('Num',4)->first();

            if(!empty($Pro4)){
                $uu['Rate']=$Pro4->Rate;
                $uu['Barcode']=$Pro4->Barcode;
                $uu['Price']=$Pro4->Price_1;
                $uu['Price_Two']=$Pro4->Price_2;
                $uu['Price_Three']=$Pro4->Price_3;
                $uu['Def']=$Pro4->Def;
                $uu['P_Ar_Name']=$Pro4->Name;
                $uu['P_En_Name']=$Pro4->Name;
                $uu['P_Type']=$Pro4->Type;
                $uu['Unit']=$Pro4->Unit;
                $uu['Product']=$ID;
                $uu['Brand']=$pro->Brand;
                $uu['Group']=$pro->Group;
                ProductUnits::create($uu);

            }



            $move['Date']=date('Y-m-d');
            $move['Type']='رصيد سابق';
            $move['TypeEn']='Previous Balance';
            $move['Bill_Num']=0;
            $move['Incom']=0;
            $move['Outcom']=0;
            $move['Current']=0;
            $move['CostIn']=0;
            $move['CostOut']=0;
            $move['CostCurrent']=0;
            $move['P_Ar_Name']=$pro->Name;
            $move['P_En_Name']=$pro->Name;
            $move['P_Code']=null;
            $move['Unit']=null;
            $move['Group']=$pro->Group;
            $move['Store']=null;
            $move['Product']=$ID;
            $move['V1']=null;
            $move['V2']=null;
            $move['User']=1;
            $move['Brand']=$pro->Brand;
            $move['Safe']=null;
            $move['Branch']=null;
            $move['SalePrice']=null;
            $move['ProductPrice']=null;
            ProductMoves::create($move);




        }

            DB::commit();
        session()->flash('success',trans('admin.Added_Successfully'));
        return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }

    }

    function ImportGroups(Request $request)
    {
        try {
            DB::beginTransaction();

            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);

            $file = $request->File;
            Excel::import(new Groupss,$file);
            DB::commit();
            session()->flash('success',trans('admin.Added_Successfully'));
            return back();
        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }


    }

    function ImportClients(Request $request)
    {

        try {
            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);

            $file = $request->File;
            Excel::import(new Clients,$file);

            $Customers=Customers::where('id','!=',1)->get();
            foreach($Customers as $cust){


                $count=AcccountingManual::orderBy('id','desc')->where('Parent',24)->count();
                $code=AcccountingManual::orderBy('id','desc')->where('Parent',24)->first();
                $codee=AcccountingManual::find(24);

                if($count == 0){

                    $x=$codee->Code.'01';
                    $dataX['Code']=(int) $x ;

                }else{

                    $y=substr($code->Code, strlen($codee->Code));
                    $newY=$y + 1 ;

                    if(strlen($newY) == 1){
                        $NewXY='0'.$newY;
                    }else{
                        $NewXY=$newY;
                    }
                    $x= $codee->Code.$NewXY;
                    $dataX['Code']=(int) $x;

                }

                $dataX['Name']=$cust->Name;
                $dataX['Type']=1;
                $dataX['Parent']=24;
                $dataX['Note']=null;
                $dataX['User']=auth()->guard('admin')->user()->id;
                AcccountingManual::create($dataX);

                $Acc=AcccountingManual::latest('id')->first();

                Customers::where('id',$cust->id)->update(['Account'=>$Acc->id]);

            }

            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }

    public function ImportVendors(Request $request){

        try {
            DB::beginTransaction();
            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);

            $file = $request->File;
            Excel::import(new Vendorss,$file);


            $Vendors=Vendors::whereNotIn('id',[4])->get();

            foreach($Vendors as $vend){

                $count=AcccountingManual::orderBy('id','desc')->where('Parent',37)->count();
                $code=AcccountingManual::orderBy('id','desc')->where('Parent',37)->first();
                $codee=AcccountingManual::find(37);

                if($count == 0){

                    $x=$codee->Code.'01';
                    $data['Code']=(int) $x ;

                }else{

                    $y=substr($code->Code, strlen($codee->Code));
                    $newY=$y + 1 ;

                    if(strlen($newY) == 1){
                        $NewXY='0'.$newY;
                    }else{
                        $NewXY=$newY;
                    }
                    $x= $codee->Code.$NewXY;
                    $data['Code']=(int) $x;

                }

                $data['Name']=$vend->Name;
                $data['Type']=1;
                $data['Parent']=37;
                $data['Note']=null;
                $data['User']=1;
                AcccountingManual::create($data);


                $Acc=AcccountingManual::orderBy('id','desc')->first();

                Vendors::where('id',$vend->id)->update(['Account'=>$Acc->id]);


            }

            DB::commit();
            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }


    }

    public function ImportEmployees(Request $request){

        try {
            DB::beginTransaction();
            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);

            $file = $request->File;
            Excel::import(new EmpExcc,$file);

            $Employess=EmpExc::get();
            foreach($Employess as $emp){



                $Acc=$this->CreateAccount($emp->Name,$emp->Name,$emp->Account,null);
                $mola=$this->CreateAccount($emp->Name.' '.' عموله ',$emp->Name.' '.' Commission ',164,null);
                $ohda=$this->CreateAccount($emp->Name.' '.' عهده ',$emp->Name.' '.' Custody ',121,null);
                $esthkak=$this->CreateAccount($emp->Name.' '.' استحقاق ',$emp->Name.' '.' Merit ',43,null);

                $Code=$this->ReturnCode(Employess::class);

                $data['Image']=null;
                $data['Code']=$Code;
                $data['Name']=$emp->Name ;
                $data['NameEn']=$emp->Name ;
                $data['Emp_Type']=$emp->Emp_Type;
                $data['Salary']=$emp->Salary;
                $data['Attendence']=null;
                $data['Departure']=null;
                $data['Hours_Numbers']=1;
                $data['Days_Numbers']=1;
                $data['Day_Price']=null;
                $data['Precentage_of_Sales']=null;
                $data['Precentage_of_Profits']=null;
                $data['Precentage_of_Execution']=null;
                $data['Note']=null;
                $data['Bank_Account']=null;
                $data['Qualifications']=null;
                $data['Address']=null;
                $data['Social_Status']=null;
                $data['ID_Number']=null;
                $data['Contract_Start']=null;
                $data['Contract_End']=null;
                $data['Phone']=$emp->Phone;
                $data['Phone2']=null;
                $data['Email']=null;
                $data['Password']=null;
                $data['Job']=$emp->Job;
                $data['Department']=$emp->Department;
                $data['Account']=$emp->Account;
                $data['Price_Level']=1;
                $data['Account_Emp']=$Acc;
                $data['Commission']=$mola;
                $data['Covenant']=$ohda;
                $data['Merit']=$esthkak;
                $data['User']=1;
                $data['Bill_Num']=null;
                $data['NumbersOfBill']=null;
                Employess::create($data);

                $IDD=Employess::orderBy('id','desc')->first();

                if(!empty($emp->Store1)){

                    $uu['Store']=$emp->Store1;
                    $uu['Emp']=$IDD->id;
                    EmpPOSStores::create($uu);
                }

                if(!empty($emp->Store2)){

                    $uu['Store']=$emp->Store2;
                    $uu['Emp']=$IDD->id;
                    EmpPOSStores::create($uu);
                }

                if(!empty($emp->Store3)){

                    $uu['Store']=$emp->Store3;
                    $uu['Emp']=$IDD->id;
                    EmpPOSStores::create($uu);
                }

            }

            DB::commit();
            session()->flash('success',trans('admin.Added_Successfully'));
            return back();
        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }

    }

    function ImportProductsWithStart(Request $request,Average $average)
    {

        try {
            DB::beginTransaction();
            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'

            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);



            $file = $request->File;
            Excel::import(new ProductFileStart,$file);

            $Products=ImportNewProdsStart::where('Num',1)->get();

            $Code=$this->ReturnCode(StartPeriods::class);
            $COUNT=ImportNewProdsStart::where('Num',1)->count();
            $TOTQTY=ImportNewProdsStart::where('Num',1)->get()->sum('Qty');
            $TOT=ImportNewProdsStart::where('Num',1)->get()->sum('Total');
            $last=ImportNewProdsStart::where('Num',1)->orderBy('id','desc')->first();
            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $s=Stores::find($last->Store);
            $IDD = DB::table('start_periods')->insertGetId(
                array(

                    'Code' => $Code,
                    'Date' => date('Y-m-d'),
                    'Store' => $last->Store,
                    'Draw' => 1,
                    'Note' => null,
                    'Total_Products' => $COUNT,
                    'Total_Qty' => $TOTQTY,
                    'Total_Price' => $TOT,
                    'Coin' => $Def->Coin,
                    'User' => 1,
                    'Time' => date("h:i:s a", time()),
                    'Branch' => $s->Branch,


                )
            );

            $dataStMove['Date']=date('Y-m-d');
            $dataStMove['Code']=$Code;
            $dataStMove['Time']=date("h:i:s a", time());
            $dataStMove['Branch']=$s->Branch;
            $dataStMove['Store']=$last->Store;
            $dataStMove['Safe']=null;
            $dataStMove['Type']='بدايه فتره';
            $dataStMove['TypeEn']='Start Period';
            $dataStMove['Cost_Center']=null;
            $dataStMove['User']=1;
            $dataStMove['Coin']=$Def->Coin;
            $dataStMove['Note']=null;
            $dataStMove['Total_Qty']=$TOTQTY;
            $dataStMove['Total_Price']=$TOT;
            $dataStMove['Account']=null;
            $dataStMove['Ship']=null;
            $dataStMove['ID']=$IDD;
            StoresMoves::create($dataStMove);

            foreach($Products as $pro){


                $ID = DB::table('products')->insertGetId(

                    array(

                        'P_Type' => $pro->Type,
                        'P_Ar_Name' => $pro->Name,
                        'P_En_Name' => $pro->Name,
                        'Brand' => $pro->Brand,
                        'Group' => $pro->Group,
                        'Code_Type' => $pro->Code_Type,
                        'World_Code' => $pro->World_Code,
                        'Weight' => $pro->Weight,
                        'Tax' => 1,
                        'Validity' => 1,
                        'Store_Show' => 0,
                        'Status' => 0,

                    )
                );


                $uu['Rate']=$pro->Rate;
                $uu['Barcode']=$pro->Barcode;
                $uu['Price']=$pro->Price_1;
                $uu['Price_Two']=$pro->Price_2;
                $uu['Price_Three']=$pro->Price_3;
                $uu['Def']=$pro->Def;
                $uu['P_Ar_Name']=$pro->Name;
                $uu['P_En_Name']=$pro->Name;
                $uu['P_Type']=$pro->Type;
                $uu['Unit']=$pro->Unit;
                $uu['Product']=$ID;
                $uu['Brand']=$pro->Brand;
                $uu['Group']=$pro->Group;
                ProductUnits::create($uu);

                $Pro2=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',2)->first();

                if(!empty($Pro2)){
                    $uu['Rate']=$Pro2->Rate;
                    $uu['Barcode']=$Pro2->Barcode;
                    $uu['Price']=$Pro2->Price_1;
                    $uu['Price_Two']=$Pro2->Price_2;
                    $uu['Price_Three']=$Pro2->Price_3;
                    $uu['Def']=$Pro2->Def;
                    $uu['P_Ar_Name']=$Pro2->Name;
                    $uu['P_En_Name']=$Pro2->Name;
                    $uu['P_Type']=$Pro2->Type;
                    $uu['Unit']=$Pro2->Unit;
                    $uu['Product']=$ID;
                    $uu['Brand']=$pro->Brand;
                    $uu['Group']=$pro->Group;


                    ProductUnits::create($uu);
                }

                $Pro3=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',3)->first();

                if(!empty($Pro3)){
                    $uu['Rate']=$Pro3->Rate;
                    $uu['Barcode']=$Pro3->Barcode;
                    $uu['Price']=$Pro3->Price_1;
                    $uu['Price_Two']=$Pro3->Price_2;
                    $uu['Price_Three']=$Pro3->Price_3;
                    $uu['Def']=$Pro3->Def;
                    $uu['P_Ar_Name']=$Pro3->Name;
                    $uu['P_En_Name']=$Pro3->Name;
                    $uu['P_Type']=$Pro3->Type;
                    $uu['Unit']=$Pro3->Unit;
                    $uu['Product']=$ID;
                    $uu['Brand']=$pro->Brand;
                    $uu['Group']=$pro->Group;
                    ProductUnits::create($uu);

                }


                $Pro4=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',4)->first();

                if(!empty($Pro4)){
                    $uu['Rate']=$Pro4->Rate;
                    $uu['Barcode']=$Pro4->Barcode;
                    $uu['Price']=$Pro4->Price_1;
                    $uu['Price_Two']=$Pro4->Price_2;
                    $uu['Price_Three']=$Pro4->Price_3;
                    $uu['Def']=$Pro4->Def;
                    $uu['P_Ar_Name']=$Pro4->Name;
                    $uu['P_En_Name']=$Pro4->Name;
                    $uu['P_Type']=$Pro4->Type;
                    $uu['Unit']=$Pro4->Unit;
                    $uu['Product']=$ID;
                    $uu['Brand']=$pro->Brand;
                    $uu['Group']=$pro->Group;
                    ProductUnits::create($uu);

                }

                $move['Date']=date('Y-m-d');
                $move['Type']='رصيد سابق';
                $move['TypeEn']='Previous Balance';
                $move['Bill_Num']=0;
                $move['Incom']=0;
                $move['Outcom']=0;
                $move['Current']=0;
                $move['CostIn']=0;
                $move['CostOut']=0;
                $move['CostCurrent']=0;
                $move['P_Ar_Name']=$pro->Name;
                $move['P_En_Name']=$pro->Name;
                $move['P_Code']=null;
                $move['Unit']=null;
                $move['Group']=$pro->Group;
                $move['Store']=null;
                $move['Product']=$ID;
                $move['V1']=null;
                $move['V2']=null;
                $move['User']=1;
                $move['Brand']=$pro->Brand;
                $move['Safe']=null;
                $move['Branch']=null;
                $move['SalePrice']=null;
                $move['ProductPrice']=null;
                ProductMoves::create($move);

                //Start Period

                $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();
                $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();



                $uu['P_Code']=$pro->Barcode;
                $uu['SmallCode']=$plow->Barcode;
                $uu['Qty']=$pro->Qty;
                $uu['SmallQty']=$pro->Qty * $pp->Rate;
                $uu['Price']=$pro->CostPrice;
                $uu['Total']=$pro->Total;
                $uu['Old_Qty']=$pro->Qty;
                $uu['Exp_Date']=null;
                $uu['SP_ID']=$IDD;
                $uu['Date']=date('Y-m-d');
                $uu['Store']=$pro->Store;
                $uu['User']=1;
                $uu['Unit']=$pro->Unit;
                $uu['P_Ar_Name']=$pro->Name;
                $uu['P_En_Name']=$pro->Name;
                $uu['V_Name']=null;
                $uu['VV_Name']=null;
                $uu['Product']=$ID;
                $uu['Patch_Number']=null;
                $uu['V1']=null;
                $uu['V2']=null;

                ProductsStartPeriods::create($uu);


                $prooooo=Products::find($ID);

                $plow=ProductUnits::where('Product',$ID)->where('Def',1)->first();
                $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();

                $newQQty=$pro->Qty * $pp->Rate;
                $ty=$average->AverageCost($pro->Total,$newQQty,$ID,$plow->Barcode,$pro->Store,date('Y-m-d'),$plow->Price);

                $newQQty=$pro->Qty * $pp->Rate;

                if($ty != 0){
                    $in=($pro->Qty * $pp->Rate) * $ty ;
                    $out=0;
                    $current=($pro->Qty * $pp->Rate) * $ty ;
                }else{
                    $in=($pro->Qty * $pp->Rate) * 1;
                    $out=0;
                    $current=($pro->Qty * $pp->Rate) * 1;
                }




                $RR=StartPeriods::find($IDD);
                $move['Date']=date('Y-m-d');
                $move['Type']='بدايه فتره';
                $move['TypeEn']='Start Period';
                $move['Bill_Num']=$RR->Code;
                $move['Incom']=$pro->Qty * $pp->Rate;
                $move['Outcom']=0;
                $move['Current']=$pro->Qty * $pp->Rate;
                $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                $move['P_Ar_Name']=$pro->Name;
                $move['P_En_Name']=$pro->Name;
                $move['P_Code']=$pro->Barcode;
                $move['Unit']=$pro->Unit;
                $move['QTY']=$pro->Qty;
                $move['Group']=$prooooo->Group;
                $move['Store']=$pro->Store;
                $move['Product']=$ID;
                $move['V1']=null;
                $move['V2']=null;
                $move['User']=1;
                $Sro=Stores::find($pro->Store);
                $move['Brand']=$prooooo->Brand;
                $move['Safe']=null;
                $move['Branch']=$Sro->Branch;
                $move['SalePrice']=null;
                $move['ProductPrice']=null;
                ProductMoves::create($move);

                $id_store = DB::table('products_stores')->insertGetId(

                    array(

                        'P_Ar_Name' => $pro->Name,
                        'P_En_Name' => $pro->Name,
                        'P_Code' => $pro->Barcode,
                        'Exp_Date' => null,
                        'Product' => $ID,
                        'Store' =>$pro->Store,
                        'V1' => null,
                        'V2' => null,
                        'V_Name' => null,
                        'VV_Name' => null,

                    )
                );

                $pqty['P_Ar_Name']=$pro->Name;
                $pqty['Price_Sale']=$pro->Price_1;
                $pqty['P_En_Name']=$pro->Name;
                $pqty['Qty']=$pro->Qty * $pp->Rate;
                $pqty['Price']=$pro->CostPrice;
                $pqty['TotalCost']=$pro->Total;
                $pqty['Pro_Stores']=$id_store;
                $pqty['Store']=$pro->Store;
                $pqty['Unit']=$pro->Unit;
                $pqty['Exp_Date']=null;
                $pqty['Low_Unit']=$plow->Unit;
                $pqty['Product']=$ID;
                $pqty['Patch_Number']=null;
                $pqty['V1']=null;
                $pqty['V2']=null;
                $pqty['V_Name']=null;
                $pqty['VV_Name']=null;
                $pqty['P_Code']=$pro->Barcode;
                $pqty['Group']=$pro->Group;
                $pqty['Brand']=$pro->Brand;
                $branch=Stores::find($pro->Store);
                $pqty['Branch']=$branch->Branch;

                $Pro2=ImportNewProdsStart::where('Name',$pro->Name)->where('Num',2)->first();
                $Pro3=ImportNewProdsStart::where('Name',$pro->Name)->where('Num',3)->first();
                $Pro4=ImportNewProdsStart::where('Name',$pro->Name)->where('Num',4)->first();

                if(!empty($Pro2)){
                    $pqty['PP_Code']=$Pro2->Barcode;
                }else{
                    $pqty['PP_Code']=null;
                }

                if(!empty($Pro3)){
                    $pqty['PPP_Code']=$Pro3->Barcode;
                }else{
                    $pqty['PPP_Code']=null;
                }

                if(!empty($Pro4)){
                    $pqty['PPPP_Code']=$Pro4->Barcode;
                }else{
                    $pqty['PPPP_Code']=null;
                }


                ProductsQty::create($pqty);


            }
            $RR=StartPeriods::find($IDD);



            $JunID = DB::table('journalizings')->insertGetId(

                array(

                    'Type' => 'اصناف بداية فترة',
                    'TypeEn' => 'Start Period Products',
                    'Code_Type' => $RR->Code,
                    'Date' => date('Y-m-d'),
                    'Draw' => 1,
                    'Coin' => $Def->Coin,
                    'Cost_Center' => null,
                    'Total_Debaitor' => $TOT,
                    'Total_Creditor' => $TOT,
                    'Note' => null,

                )
            );

            $Code=Journalizing::find($JunID)->Code;
            $store=Stores::find($last->Store);

            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=$TOT;
            $PRODUCTSS['Creditor']=0;
            $PRODUCTSS['Account']=$store->Account;
            $PRODUCTSS['Statement']=null;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$RR->Code;
            $Gen['Date']=date('Y-m-d');
            $Gen['Type']= 'اصناف بداية فترة';
            $Gen['TypeEn']='Start Period Products';
            $Gen['Debitor']=$TOT;
            $Gen['Creditor']=0;
            $Gen['Statement']=null;
            $Gen['Draw']=1;
            $Gen['Debitor_Coin']= 1 * $TOT;
            $Gen['Creditor_Coin']=1 * 0;
            $Gen['Account']=$store->Account;
            $Gen['Coin']= $Def->Coin;
            $Gen['Cost_Center']=null;
            $Gen['userr']= 1;

            GeneralDaily::create($Gen);


            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=0;
            $PRODUCTSS['Creditor']=$TOT;
            $PRODUCTSS['Account']=45;
            $PRODUCTSS['Statement']=null;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$RR->Code;
            $Gen['Date']=date('Y-m-d');
            $Gen['Type']= 'اصناف بداية فترة';
            $Gen['TypeEn']='Start Period Products';
            $Gen['Debitor']=0;
            $Gen['Creditor']=$TOT;
            $Gen['Statement']=null;
            $Gen['Draw']=1;
            $Gen['Debitor_Coin']= 1 * 0;
            $Gen['Creditor_Coin']=1 * $TOT;
            $Gen['Account']=45;
            $Gen['Coin']= $Def->Coin;
            $Gen['Cost_Center']= null;
            $Gen['userr']= 1;

            GeneralDaily::create($Gen);


            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }


    }


    public function ImportReceipt_Voucher(Request $request){

        try {
            DB::beginTransaction();
            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);



            $file = $request->File;
            Excel::import(new Voucher,$file);

            $Vouchers=Vouchers::get();



            $Coder=$this->ReturnCode(ReciptVoucher::class);
            foreach($Vouchers as $voucher){

                $IDD = DB::table('recipt_vouchers')->insertGetId(

                    array(

                        'Code' => $Coder,
                        'Date' => date('Y-m-d'),
                        'Draw' => $voucher->Draw,
                        'Coin' => $voucher->Coin,
                        'Safe' => $voucher->Safe,
                        'Cost_Center' => null,
                        'Total_Creditor' =>$voucher->Creditor,
                        'Note' => null,

                    )
                );

                $PRODUCTS['RV_ID']=$IDD;
                $PRODUCTS['Creditor']=$voucher->Creditor;
                $PRODUCTS['Account']=$voucher->Account;
                $PRODUCTS['Statement']=$voucher->Statement;

                ReciptVoucherDetails::create($PRODUCTS);

                $ID = DB::table('journalizings')->insertGetId(

                    array(

                        'Type' => 'سند قبض',
                        'TypeEn' => 'Receipt Voucher',
                        'Code_Type' => $Coder,
                        'Date' => date('Y-m-d'),
                        'Draw' => $voucher->Draw,
                        'Coin' => $voucher->Coin,
                        'Cost_Center' => null,
                        'Total_Debaitor' => $voucher->Debitor,
                        'Total_Creditor' => $voucher->Creditor,
                        'Note' => null,

                    )
                );

                $Code=Journalizing::find($ID)->Code;

                $PRODUCTSS['Joun_ID']=$ID;
                $PRODUCTSS['Debitor']=0;
                $PRODUCTSS['Creditor']=$voucher->Creditor;
                $PRODUCTSS['Account']=$voucher->Account;
                $PRODUCTSS['Statement']=$voucher->Statement;


                JournalizingDetails::create($PRODUCTSS);

                $Gen['Code']=$Code;
                $Gen['Code_Type']=$Coder;
                $Gen['Date']=date('Y-m-d');
                $Gen['Type']= 'سند قبض';
                $Gen['TypeEn']='Receipt Voucher';
                $Gen['Debitor']=0;
                $Gen['Creditor']=$voucher->Creditor;
                $Gen['Statement']=$voucher->Statement;
                $Gen['Draw']=$voucher->Draw;
                $Gen['Debitor_Coin']= $voucher->Draw * 0;
                $Gen['Creditor_Coin']=$voucher->Draw * $voucher->Creditor;
                $Gen['Account']=$voucher->Account;
                $Gen['Coin']= $voucher->Coin;
                $Gen['Cost_Center']= null;
                $Gen['userr']=1;
                GeneralDaily::create($Gen);



                $PRODUCTSSS['Joun_ID']=$ID;
                $PRODUCTSSS['Debitor']=$voucher->Creditor;
                $PRODUCTSSS['Creditor']=0;
                $PRODUCTSSS['Account']=$voucher->Safe;
                $PRODUCTSSS['Statement']=$voucher->Statement;
                JournalizingDetails::create($PRODUCTSSS);

                $Genn['Code']=$Code;
                $Genn['Code_Type']=$Coder;
                $Genn['Date']=date('Y-m-d');
                $Genn['Type']= 'سند قبض';
                $Genn['TypeEn']='Receipt Voucher';
                $Genn['Debitor']=$voucher->Creditor;
                $Genn['Creditor']=0;
                $Genn['Statement']=null;
                $Genn['Draw']=$voucher->Draw;
                $Genn['Debitor_Coin']=$voucher->Draw * $voucher->Creditor;
                $Genn['Creditor_Coin']=$voucher->Draw * 0;
                $Genn['Account']=$voucher->Safe;
                $Genn['Coin']= $voucher->Coin;
                $Genn['Cost_Center']= null;
                $Genn['userr']=1;

                GeneralDaily::create($Genn);

            }

            DB::commit();
            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }




    }


    public function ImportPayment_Voucher(Request $request){

        try {
            DB::beginTransaction();
            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);



            $file = $request->File;
            Excel::import(new Voucher,$file);

            $Vouchers=Vouchers::get();



            $Coder=$this->ReturnCode(PaymentVoucher::class);


            foreach($Vouchers as $voucher){

                $IDD = DB::table('payment_vouchers')->insertGetId(

                    array(

                        'Code' => $Coder,
                        'Date' => date('Y-m-d'),
                        'Draw' => $voucher->Draw,
                        'Coin' => $voucher->Coin,
                        'Safe' => $voucher->Safe,
                        'Cost_Center' => null,
                        'Total_Debaitor' => $voucher->Debitor,
                        'Note' => null,

                    )
                );




                $PRODUCTS['PV_ID']=$IDD;
                $PRODUCTS['Debitor']=$voucher->Debitor;
                $PRODUCTS['Account']=$voucher->Account;
                $PRODUCTS['Statement']=$voucher->Statement;


                PaymentVoucherDetails::create($PRODUCTS);



                $ID = DB::table('journalizings')->insertGetId(

                    array(


                        'Type' => 'سند صرف',
                        'TypeEn' =>'Payment Voucher',

                        'Code_Type' => $Coder,
                        'Date' => date('Y-m-d'),
                        'Draw' => $voucher->Draw,
                        'Coin' => $voucher->Coin,
                        'Cost_Center' => null,
                        'Total_Debaitor' => $voucher->Debitor,
                        'Total_Creditor' => $voucher->Debitor,
                        'Note' => null,

                    )
                );

                $Code=Journalizing::find($ID)->Code;
                $PRODUCTSS['Joun_ID']=$ID;
                $PRODUCTSS['Debitor']=$voucher->Debitor;
                $PRODUCTSS['Creditor']=0;
                $PRODUCTSS['Account']=$voucher->Account;
                $PRODUCTSS['Statement']=$voucher->Statement;


                JournalizingDetails::create($PRODUCTSS);

                $Gen['Code']=$Code;
                $Gen['Code_Type']=$Coder;
                $Gen['Date']=date('Y-m-d');
                $Gen['Type']= 'سند صرف';
                $Gen['TypeEn']='Payment Voucher';
                $Gen['Debitor']=$voucher->Debitor;
                $Gen['Creditor']=0;
                $Gen['Statement']=$voucher->Statement;
                $Gen['Draw']=$voucher->Draw;
                $Gen['Debitor_Coin']= $voucher->Draw * $voucher->Debitor;
                $Gen['Creditor_Coin']=$voucher->Draw * 0;
                $Gen['Account']=$voucher->Account;
                $Gen['Coin']= $voucher->Coin;
                $Gen['Cost_Center']= null;
                $Gen['userr']= 1;

                GeneralDaily::create($Gen);



                $PRODUCTSSS['Joun_ID']=$ID;
                $PRODUCTSSS['Debitor']=0;
                $PRODUCTSSS['Creditor']=$voucher->Debitor;
                $PRODUCTSSS['Account']=$voucher->Safe;
                $PRODUCTSSS['Statement']=null;
                JournalizingDetails::create($PRODUCTSSS);

                $Genn['Code']=$Code;
                $Genn['Code_Type']=$Coder;
                $Genn['Date']=date('Y-m-d');
                $Genn['Type']= 'سند صرف';
                $Genn['TypeEn']='Payment Voucher';
                $Genn['Debitor']=0;
                $Genn['Creditor']=$voucher->Debitor;
                $Genn['Statement']=null;
                $Genn['Draw']=$voucher->Draw;
                $Genn['Debitor_Coin']= $voucher->Draw * 0;
                $Genn['Creditor_Coin']=$voucher->Draw * $voucher->Debitor;
                $Genn['Account']=$voucher->Safe;
                $Genn['Coin']= $voucher->Coin;
                $Genn['Cost_Center']= null;
                $Genn['userr']= 1;

                GeneralDaily::create($Genn);

            }
            DB::commit();
            session()->flash('success',trans('admin.Added_Successfully'));
            return back();


        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }


    }


    function ImportCustomersGroup(Request $request)
    {

        try {
            DB::beginTransaction();
            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);

            $file = $request->File;
            Excel::import(new CustGroupss,$file);

            DB::commit();
            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }


    }

    function ImportBrands(Request $request)
    {
        try {
            DB::beginTransaction();

            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);

            $file = $request->File;
            Excel::import(new ImpBrands,$file);
            DB::commit();
            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }


    }


    function ImportAccountingManual(Request $request)
    {

        try {
            DB::beginTransaction();
            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);

            $file = $request->File;
            Excel::import(new ImportAccountingManual,$file);

            $Accountings=DB::table('upload_accountings')->get();

            foreach($Accountings as $acc){


                if(!empty($acc->Parent)){
                    $data['Parent']=$acc->Parent;

                    $count=AcccountingManual::orderBy('Code','desc')->where('Parent',$acc->Parent)->count();
                    $code=AcccountingManual::orderBy('Code','desc')->where('Parent',$acc->Parent)->first();
                    $codee=AcccountingManual::find($acc->Parent);

                    if($count == 0){

                        $x=$codee->Code.'01';
                        $data['Code']=(int) $x ;

                    }else{

                        $y=substr($code->Code, strlen($codee->Code));
                        $newY=$y + 1 ;

                        if(strlen($newY) == 1){
                            $NewXY='0'.$newY;
                        }else{
                            $NewXY=$newY;
                        }
                        $x= $codee->Code.$NewXY;
                        $data['Code']=(int) $x;

                    }


                }else{

                    $data['Parent']=0;
                    $code=AcccountingManual::orderBy('id','desc')->where('Parent',0)->first();

                    if(!empty($code)){
                        $data['Code']=$code->Code + 1 ;
                    }else{

                        $data['Code']=1;
                    }

                }



                $data['Name']=$acc->Name;
                $data['Type']=$acc->Type;
                $data['Note']=$acc->Note;
                $data['Account_Code']=$acc->Account_Code;
                $data['User']=$acc->User;
                AcccountingManual::create($data);


                if($acc->Parent == 28){
                    $Acc=AcccountingManual::orderBy('id','desc')->first();

                    $res=SafesBanks::orderBy('id','desc')->first();

                    if(!empty($res->Code)){

                        $Code=$res->Code + 1 ;

                    }else{

                        $Code=1;

                    }


                    $dataa['Code']=$Code;
                    $dataa['Date']=date('Y-m-d');
                    $dataa['Name']=$acc->Name;
                    $dataa['Type']=1;
                    $dataa['Note']=$acc->Note;
                    $dataa['Account']=$Acc->id;
                    $dataa['User']=$acc->User;

                    SafesBanks::create($dataa);
                }elseif($acc->Parent == 29){

                    $Acc=AcccountingManual::orderBy('id','desc')->first();

                    $res=SafesBanks::orderBy('id','desc')->first();

                    if(!empty($res->Code)){

                        $Code=$res->Code + 1 ;

                    }else{

                        $Code=1;

                    }


                    $dataa['Code']=$Code;
                    $dataa['Date']=date('Y-m-d');
                    $dataa['Name']=$acc->Name;
                    $dataa['Type']=2;
                    $dataa['Note']=$acc->Note;
                    $dataa['Account']=$Acc->id;
                    $dataa['User']=$acc->User;
                    SafesBanks::create($dataa);

                }


                if($acc->Parent == 27){
                    $Acc=AcccountingManual::orderBy('id','desc')->first();

                    $res=Stores::orderBy('id','desc')->first();

                    if(!empty($res->Code)){

                        $Code=$res->Code + 1 ;

                    }else{

                        $Code=1;

                    }


                    $dataa['Code']=$Code;
                    $dataa['Date']=date('Y-m-d');
                    $dataa['Time']=date("h:i:s a", time());
                    $dataa['Name']=$acc->Name;
                    $dataa['Phone']=null;
                    $dataa['Address']=null;
                    $dataa['Account']=$Acc->id;
                    $dataa['User']=$acc->User;

                    Stores::create($dataa);
                }


                if($acc->Parent == 37){
                    $Acc=AcccountingManual::orderBy('id','desc')->first();

                    $res=Vendors::orderBy('id','desc')->first();

                    if(!empty($res->Code)){

                        $Code=$res->Code + 1 ;

                    }else{

                        $Code=1;

                    }


                    $dataa['Code']=$Code;
                    $dataa['Name']=$acc->Name;
                    $dataa['Phone']=null;
                    $dataa['Phone2']=null;
                    $dataa['Commercial_Register']=null;
                    $dataa['Tax_Card']=null;
                    $dataa['Price_Level']=1;
                    $dataa['Account']=$Acc->id;
                    $dataa['User']=$acc->User;

                    Vendors::create($dataa);
                }


                if($acc->Parent == 24){
                    $Acc=AcccountingManual::orderBy('id','desc')->first();

                    $res=Customers::orderBy('id','desc')->first();

                    if(!empty($res->Code)){

                        $Code=$res->Code + 1 ;

                    }else{

                        $Code=1;

                    }


                    $dataa['Code']=$Code;
                    $dataa['Name']=$acc->Name;
                    $dataa['Price_Level']=1;
                    $dataa['Account']=$Acc->id;
                    $dataa['User']=$acc->User;

                    Customers::create($dataa);
                }

                if($acc->Parent == 97){
                    $Acc=AcccountingManual::orderBy('id','desc')->first();

                    $dataa['Name']=$acc->Name;
                    $dataa['Account']=$Acc->id;

                    ShippingCompany::create($dataa);
                }

                if($acc->Parent == 39){
                    $Acc=AcccountingManual::orderBy('id','desc')->first();

                    $res=Taxes::orderBy('id','desc')->first();

                    if(!empty($res->Code)){

                        $Code=$res->Code + 1 ;

                    }else{

                        $Code=1;

                    }

                    $data['Code']=$Code;
                    $data['Name']=$acc->Name;
                    $data['Rate']=0;
                    $data['Type']=2;
                    $data['Hide']=0;
                    $data['Account']=$Acc->id;

                    Taxes::create($data);
                }




            }


            DB::commit();
            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }


    function ImportAssets(Request $request)
    {
        try {
            DB::beginTransaction();


            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);

            $file = $request->File;
            Excel::import(new ImportAssets,$file);
            $lasts=Assets::get();
            foreach($lasts as $last){
                $count=AcccountingManual::orderBy('id','desc')->where('Parent',$last->Main_Account)->count();
                $code=AcccountingManual::orderBy('id','desc')->where('Parent',$last->Main_Account)->first();
                $codee=AcccountingManual::find($last->Main_Account);

                if($count == 0){

                    $x=$codee->Code.'01';
                    $data['Code']=(int) $x ;

                }else{

                    $y=substr($code->Code, strlen($codee->Code));
                    $newY=$y + 1 ;

                    if(strlen($newY) == 1){
                        $NewXY='0'.$newY;
                    }else{
                        $NewXY=$newY;
                    }
                    $x= $codee->Code.$NewXY;
                    $data['Code']=(int) $x;

                }

                $data['Name']=$last->Name;
                $data['Type']=1;
                $data['Parent']=$last->Main_Account;
                $data['Note']=null;
                $data['User']=$last->User;
                AcccountingManual::create($data);


                $Acc=AcccountingManual::orderBy('id','desc')->first();

                $dataa['Code']=$last->Code;
                $dataa['Name']=$last->Name;
                $dataa['Asset_Type']=$last->Asset_Type;
                $dataa['Depreciation_Method']=$last->Depreciation_Method;
                $dataa['Purchases_Date']=$last->Purchases_Date;
                $dataa['Operation_Date']=$last->Operation_Date;
                $dataa['Cost']=$last->Cost;
                $dataa['Previous_Depreciation']=$last->Previous_Depreciation;
                $dataa['Asset_Net']=$last->Asset_Net;
                $dataa['Annual_Depreciation_Ratio']=$last->Annual_Depreciation_Ratio;
                $dataa['Annual_Depreciation']=$last->Annual_Depreciation;
                $dataa['Life_Span']=$last->Life_Span;
                $dataa['Note']=$last->Note;
                $dataa['Depreciation_Expenses']=$last->Depreciation_Expenses;
                $dataa['Depreciation_Complex']=$last->Depreciation_Complex;
                $dataa['Main_Account']=$last->Main_Account;
                $dataa['Draw']=$last->Draw;
                $dataa['Coin']=$last->Coin;
                $dataa['Branch']=$last->Branch;
                $dataa['Cost_Center']=$last->Cost_Center;
                $dataa['Sort_Asset']=$last->Sort_Asset;
                $dataa['Vendor']=$last->Vendor;
                $dataa['Safe']=$last->Safe;
                $dataa['Ehlak']=$last->Ehlak;
                $dataa['Payment_Method']=$last->Payment_Method;
                $dataa['Account']=$Acc->id;
                $dataa['User']=$last->User;

                Assets::where('id',$last->id)->update($dataa);




                if($last->Asset_Type == 'consumer'){

                    $money=$last->Asset_Net;

                }else{

                    $money= $last->Cost;
                }


                if($last->Sort_Asset == 1){
                    $ID = DB::table('journalizings')->insertGetId(

                        array(


                            'Type' => 'شراء أصل',
                            'TypeEn' =>'Purchases Asset',
                            'Code_Type' =>$last->Code,
                            'Date' =>$last->Purchases_Date,
                            'Draw' =>$last->Draw,
                            'Coin' =>$last->Coin,
                            'Cost_Center' =>$last->Cost_Center,
                            'Total_Debaitor' => $money,
                            'Total_Creditor' => $money,
                            'Note' =>$last->Note,

                        )
                    );


                    $PRODUCTSS['Joun_ID']=$ID;
                    $PRODUCTSS['Debitor']=$money;
                    $PRODUCTSS['Creditor']=0;
                    $PRODUCTSS['Account']=$Acc->id;
                    $PRODUCTSS['Statement']=null;


                    JournalizingDetails::create($PRODUCTSS);


                    $Code=Journalizing::findOrFail($ID)->Code;

                    $Gen['Code']=$Code;
                    $Gen['Code_Type']=$last->Code;
                    $Gen['Date']=$last->Purchases_Date;
                    $Gen['Type']='شراء أصل';
                    $Gen['TypeEn']='Purchases Asset';
                    $Gen['Debitor']=$money;
                    $Gen['Creditor']=0;
                    $Gen['Statement']=null;
                    $Gen['Draw']=$last->Draw;
                    $Gen['Debitor_Coin']= $last->Draw * $money;
                    $Gen['Creditor_Coin']=$last->Draw * 0;
                    $Gen['Account']=$Acc->id;
                    $Gen['Coin']= $last->Coin;
                    $Gen['Cost_Center']= $last->Cost_Center;
                    $Gen['userr']= $last->User;

                    GeneralDaily::create($Gen);



                    $PRODUCTSSS['Joun_ID']=$ID;
                    $PRODUCTSSS['Debitor']=0;
                    $PRODUCTSSS['Creditor']=$money;
                    $PRODUCTSSS['Account']=45;
                    $PRODUCTSSS['Statement']=null;
                    JournalizingDetails::create($PRODUCTSSS);

                    $Genn['Code']=$Code;
                    $Genn['Code_Type']=$last->Code;
                    $Genn['Date']=$last->Purchases_Date;
                    $Genn['Type']='شراء أصل';
                    $Genn['TypeEn']='Purchases Asset';
                    $Genn['Debitor']=0;
                    $Genn['Creditor']=$money;
                    $Genn['Statement']=null;
                    $Genn['Draw']=$last->Draw;
                    $Genn['Debitor_Coin']= $last->Draw * 0;
                    $Genn['Creditor_Coin']=$last->Draw * $money;
                    $Genn['Account']=45;
                    $Genn['Coin']= $last->Coin;
                    $Genn['Cost_Center']= $last->Cost_Center;
                    $Genn['userr']= $last->User;

                    GeneralDaily::create($Genn);

                }elseif($last->Sort_Asset == 2){

                    $ID = DB::table('journalizings')->insertGetId(

                        array(


                            'Type' => 'شراء أصل',
                            'TypeEn' =>'Purchases Asset',
                            'Code_Type' =>$last->Code,
                            'Date' =>$last->Purchases_Date,
                            'Draw' =>$last->Draw,
                            'Coin' =>$last->Coin,
                            'Cost_Center' =>$last->Cost_Center,
                            'Total_Debaitor' => $money,
                            'Total_Creditor' => $money,
                            'Note' =>$last->Note,

                        )
                    );




     $Code=Journalizing::findOrFail($ID)->Code;

                    $PRODUCTSS['Joun_ID']=$ID;
                    $PRODUCTSS['Debitor']=$money;
                    $PRODUCTSS['Creditor']=0;
                    $PRODUCTSS['Account']=$last->Vendor;
                    $PRODUCTSS['Statement']=null;



                    JournalizingDetails::create($PRODUCTSS);

                    $Gen['Code']=$Code;
                    $Gen['Code_Type']=$last->Code;
                    $Gen['Date']=$last->Purchases_Date;
                    $Gen['Type']='شراء أصل';
                    $Gen['TypeEn']='Purchases Asset';
                    $Gen['Debitor']=$money;
                    $Gen['Creditor']=0;
                    $Gen['Statement']=null;
                    $Gen['Draw']=$last->Draw;
                    $Gen['Debitor_Coin']= $last->Draw * $money;
                    $Gen['Creditor_Coin']=$last->Draw * 0;
                    $Gen['Account']=$last->Vendor;
                    $Gen['Coin']= $last->Coin;
                    $Gen['Cost_Center']= $last->Cost_Center;
                    $Gen['userr']= $last->User;

                    GeneralDaily::create($Gen);



                    $PRODUCTSSS['Joun_ID']=$ID;
                    $PRODUCTSSS['Debitor']=0;
                    $PRODUCTSSS['Creditor']=$money;
                    $PRODUCTSSS['Account']=$last->Safe;
                    $PRODUCTSSS['Statement']=null;
                    JournalizingDetails::create($PRODUCTSSS);

                    $Genn['Code']=$Code;
                    $Genn['Code_Type']=$last->Code;
                    $Genn['Date']=$last->Purchases_Date;
                    $Genn['Type']='شراء أصل';
                    $Genn['TypeEn']='Purchases Asset';
                    $Genn['Debitor']=0;
                    $Genn['Creditor']=$money;
                    $Genn['Statement']=null;
                    $Genn['Draw']=$last->Draw;
                    $Genn['Debitor_Coin']= $last->Draw * 0;
                    $Genn['Creditor_Coin']=$last->Draw * $money;
                    $Genn['Account']=$last->Safe;
                    $Genn['Coin']= $last->Coin;
                    $Genn['Cost_Center']= $last->Cost_Center;
                    $Genn['userr']= $last->User;

                    GeneralDaily::create($Genn);




                    $PRODUCTSS['Joun_ID']=$ID;
                    $PRODUCTSS['Debitor']=0;
                    $PRODUCTSS['Creditor']=$money;
                    $PRODUCTSS['Account']=$last->Vendor;
                    $PRODUCTSS['Statement']=null;

                    JournalizingDetails::create($PRODUCTSS);

                    $Gen['Code']=$Code;
                    $Gen['Code_Type']=$last->Code;
                    $Gen['Date']=$last->Purchases_Date;
                    $Gen['Type']='شراء أصل';
                    $Gen['TypeEn']='Purchases Asset';
                    $Gen['Debitor']=0;
                    $Gen['Creditor']=$money;
                    $Gen['Statement']=null;
                    $Gen['Draw']=$last->Draw;
                    $Gen['Debitor_Coin']= $last->Draw * 0;
                    $Gen['Creditor_Coin']=$last->Draw * $money;
                    $Gen['Account']=$last->Vendor;
                    $Gen['Coin']= $last->Coin;
                    $Gen['Cost_Center']= $last->Cost_Center;
                    $Gen['userr']= $last->User;

                    GeneralDaily::create($Gen);



                    $PRODUCTSSS['Joun_ID']=$ID;
                    $PRODUCTSSS['Debitor']=$money;
                    $PRODUCTSSS['Creditor']=0;
                    $PRODUCTSSS['Account']=$Acc->id;
                    $PRODUCTSSS['Statement']=null;
                    JournalizingDetails::create($PRODUCTSSS);

                    $Genn['Code']=$Code;
                    $Genn['Code_Type']=$last->Code;
                    $Genn['Date']=$last->Purchases_Date;
                    $Genn['Type']='شراء أصل';
                    $Genn['TypeEn']='Purchases Asset';
                    $Genn['Debitor']=$money;
                    $Genn['Creditor']=0;
                    $Genn['Statement']=null;
                    $Genn['Draw']=$last->Draw;
                    $Genn['Debitor_Coin']= $last->Draw * $money;
                    $Genn['Creditor_Coin']=$last->Draw * 0;
                    $Genn['Account']=$Acc->id;
                    $Genn['Coin']= $last->Coin;
                    $Genn['Cost_Center']= $last->Cost_Center;
                    $Genn['userr']= $last->User;

                    GeneralDaily::create($Genn);


                }


            }
            DB::commit();
            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }

    function ImportExporting_Checks(Request $request)
    {
        try {
            DB::beginTransaction();


            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);

            $file = $request->File;
            Excel::import(new ImportExporting_Checks,$file);

            $DATAs=DB::table('export_checks')->get();

            foreach($DATAs as $data){



                $ID = DB::table('journalizings')->insertGetId(

                    array(


                        'Type' => 'الشيكات الصادرة',
                        'TypeEn' =>'Exporting Checks',
                        'Code_Type' => $data->Code,
                        'Date' => $data->Date,
                        'Draw' => $data->Draw,
                        'Coin' => $data->Coin,
                        'Cost_Center' => $data->Cost_Center,
                        'Total_Debaitor' => $data->Amount,
                        'Total_Creditor' => $data->Amount,
                        'Note' => $data->Note,

                    )
                );


                $Code=Journalizing::findOrFail($ID)->Code;

                $PRODUCTSS['Joun_ID']=$ID;
                $PRODUCTSS['Debitor']=$data->Amount;
                $PRODUCTSS['Creditor']=0;
                $PRODUCTSS['Account']=$data->Account;
                $PRODUCTSS['Statement']=$data->Note;


                JournalizingDetails::create($PRODUCTSS);

                $Gen['Code']=$Code;
                $Gen['Code_Type']=$data->Code;
                $Gen['Date']=$data->Date;
                $Gen['Type']='الشيكات الصادرة';
                $Gen['TypeEn']='Exporting Checks';
                $Gen['Debitor']=$data->Amount;
                $Gen['Creditor']=0;
                $Gen['Statement']=$data->Note;
                $Gen['Draw']=$data->Draw;
                $Gen['Debitor_Coin']= $data->Draw * $data->Amount;
                $Gen['Creditor_Coin']=$data->Draw * 0;
                $Gen['Account']=$data->Account;
                $Gen['Coin']=$data->Coin;
                $Gen['Cost_Center']=$data->Cost_Center;
                $Gen['userr']=$data->User;

                GeneralDaily::create($Gen);


                $PRODUCTSS['Joun_ID']=$ID;
                $PRODUCTSS['Debitor']=0;
                $PRODUCTSS['Creditor']=$data->Amount;
                $PRODUCTSS['Account']=42;
                $PRODUCTSS['Statement']=$data->Note;


                JournalizingDetails::create($PRODUCTSS);

                $Gen['Code']=$Code;
                $Gen['Code_Type']=$data->Code;
                $Gen['Date']=$data->Date;
                $Gen['Type']='الشيكات الصادرة';
                $Gen['TypeEn']='Exporting Checks';
                $Gen['Debitor']=0;
                $Gen['Creditor']=$data->Amount;
                $Gen['Statement']=$data->Note;
                $Gen['Draw']=$data->Draw;
                $Gen['Debitor_Coin']= $data->Draw * 0;
                $Gen['Creditor_Coin']=$data->Draw * $data->Amount;
                $Gen['Account']=42;
                $Gen['Coin']= $data->Coin;
                $Gen['Cost_Center']= $data->Cost_Center;
                $Gen['userr']= $data->User;

                GeneralDaily::create($Gen);


            }

            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();


        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }


    function ImportIncoming_checks(Request $request)
    {

        try {
            DB::beginTransaction();

            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);

            $file = $request->File;
            Excel::import(new ImportIncoming_checks,$file);

            $DATAs=DB::table('incom_checks')->get();

            foreach($DATAs as $data){



                $ID = DB::table('journalizings')->insertGetId(

                    array(


                        'Type' => 'الشيكات الواردة',
                        'TypeEn' => 'Incoming checks',
                        'Code_Type' => $data->Code,
                        'Date' => $data->Date,
                        'Draw' => $data->Draw,
                        'Coin' => $data->Coin,
                        'Cost_Center' => $data->Cost_Center,
                        'Total_Debaitor' => $data->Amount,
                        'Total_Creditor' => $data->Amount,
                        'Note' => $data->Note,

                    )
                );


                $Code=Journalizing::findOrFail($ID)->Code;


                $PRODUCTSS['Joun_ID']=$ID;
                $PRODUCTSS['Debitor']=0;
                $PRODUCTSS['Creditor']=$data->Amount;
                $PRODUCTSS['Account']=$data->Account;
                $PRODUCTSS['Statement']=$data->Note;


                JournalizingDetails::create($PRODUCTSS);

                $Gen['Code']=$Code;
                $Gen['Code_Type']=$data->Code;
                $Gen['Date']=$data->Date;
                $Gen['Type']='الشيكات الواردة';
                $Gen['TypeEn']='Incoming checks';
                $Gen['Debitor']=0;
                $Gen['Creditor']=$data->Amount;
                $Gen['Statement']=$data->Note;
                $Gen['Draw']=$data->Draw;
                $Gen['Debitor_Coin']= $data->Draw * 0;
                $Gen['Creditor_Coin']=$data->Draw * $data->Amount;
                $Gen['Account']=$data->Account;
                $Gen['Coin']=$data->Coin;
                $Gen['Cost_Center']=$data->Cost_Center;
                $Gen['userr']=$data->User;

                GeneralDaily::create($Gen);


                $PRODUCTSS['Joun_ID']=$ID;
                $PRODUCTSS['Debitor']=$data->Amount;
                $PRODUCTSS['Creditor']=0;
                $PRODUCTSS['Account']=35;
                $PRODUCTSS['Statement']=$data->Note;


                JournalizingDetails::create($PRODUCTSS);

                $Gen['Code']=$Code;
                $Gen['Code_Type']=$data->Code;
                $Gen['Date']=$data->Date;
                $Gen['Type']='الشيكات الواردة';
                $Gen['TypeEn']='Incoming checks';
                $Gen['Debitor']=$data->Amount;
                $Gen['Creditor']=0;
                $Gen['Statement']=$data->Note;
                $Gen['Draw']=$data->Draw;
                $Gen['Debitor_Coin']= $data->Draw * $data->Amount;
                $Gen['Creditor_Coin']=$data->Draw * 0;
                $Gen['Account']=35;
                $Gen['Coin']= $data->Coin;
                $Gen['Cost_Center']=$data->Cost_Center;
                $Gen['userr']=$data->User;

                GeneralDaily::create($Gen);



            }
            DB::commit();
            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }


    function ImportInsurance_Paper(Request $request)
    {
        try {
            DB::beginTransaction();

            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);

            $file = $request->File;
            Excel::import(new ImportInsurance_Paper,$file);

            $DATAs=DB::table('insurance_papers')->get();

            foreach($DATAs as $data){


                $ID = DB::table('journalizings')->insertGetId(

                    array(


                        'Type' => 'وصل أمانة',
                        'TypeEn' => 'Insurance Paper',
                        'Code_Type' => $data->Code,
                        'Date' => $data->Date,
                        'Draw' => $data->Draw,
                        'Coin' => $data->Coin,
                        'Cost_Center' => $data->Cost_Center,
                        'Total_Debaitor' => $data->Amount,
                        'Total_Creditor' => $data->Amount,
                        'Note' => $data->Note,
                    )
                );

                $Code=Journalizing::findOrFail($ID)->Code;

                $PRODUCTSS['Joun_ID']=$ID;
                $PRODUCTSS['Debitor']=0;
                $PRODUCTSS['Creditor']=$data->Amount;
                $PRODUCTSS['Account']=$data->Account;
                $PRODUCTSS['Statement']=$data->Note;


                JournalizingDetails::create($PRODUCTSS);

                $Gen['Code']=$Code;
                $Gen['Code_Type']=$data->Code;
                $Gen['Date']=$data->Date;
                $Gen['Type']='وصل أمانة';
                $Gen['TypeEn']='Insurance Paper';
                $Gen['Debitor']=0;
                $Gen['Creditor']=$data->Amount;
                $Gen['Statement']=$data->Note;
                $Gen['Draw']=$data->Draw;
                $Gen['Debitor_Coin']= $data->Draw * 0;
                $Gen['Creditor_Coin']=$data->Draw * $data->Amount;
                $Gen['Account']=$data->Account;
                $Gen['Coin']=$data->Coin;
                $Gen['Cost_Center']=$data->Cost_Center;
                $Gen['userr']=$data->User;

                GeneralDaily::create($Gen);


                $PRODUCTSS['Joun_ID']=$ID;
                $PRODUCTSS['Debitor']=$data->Amount;
                $PRODUCTSS['Creditor']=0;
                $PRODUCTSS['Account']=35;
                $PRODUCTSS['Statement']=$data->Note;


                JournalizingDetails::create($PRODUCTSS);

                $Gen['Code']=$Code;
                $Gen['Code_Type']=$data->Code;
                $Gen['Date']=$data->Date;
                $Gen['Type']='وصل أمانة';
                $Gen['TypeEn']='Insurance Paper';
                $Gen['Debitor']=$data->Amount;
                $Gen['Creditor']=0;
                $Gen['Statement']=$data->Note;
                $Gen['Draw']=$data->Draw;
                $Gen['Debitor_Coin']= $data->Draw * $data->Amount;
                $Gen['Creditor_Coin']=$data->Draw * 0;
                $Gen['Account']=35;
                $Gen['Coin']= $data->Coin;
                $Gen['Cost_Center']=$data->Cost_Center;
                $Gen['userr']=$data->User;

                GeneralDaily::create($Gen);


            }
            DB::commit();
            session()->flash('success',trans('admin.Added_Successfully'));
            return back();
        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }


    }


    function ImportCustomerFollowUp(Request $request)
    {
        try {
            DB::beginTransaction();
            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);



            $file = $request->File;
            Excel::import(new ImportCustomerFollowUp,$file);

            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }


    function ImportAttendance(Request $request)
    {
        try {
            DB::beginTransaction();

            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);


            $file = $request->File;
            Excel::import(new AttendImport,$file);

            $Atteds=AttendDepartureImport::get();
            $AttedsFF=AttendDepartureImport::orderBy('id','desc')->first();

            $Code=$this->ReturnCode(Departure::class);

            $ID = DB::table('departures')->insertGetId(

                array(

                    'Code' => $Code,
                    'Date' => $AttedsFF->Date,
                    'Month' => $AttedsFF->Month,
                    'Note' => $AttedsFF->Note,
                    'Attend' => $AttedsFF->Attend,
                    'User' =>1,
                )
            );

            Attendance::where('id',$AttedsFF->Attend)->update(['Status'=>1]);
            foreach($Atteds as $att){


                $emp['In_Time']=$att->In_Time;
                $emp['Date']=$att->Date;
                $emp['Month']=$att->Month;
                $emp['Note']=$att->Note;
                $emp['Attend']=$att->Attend;
                $emp['Emp']=$att->Emp;
                AttendanceEmp::create($emp);



                $Mwzf=Employess::find($att->Emp);

                $Att = new DateTime($Mwzf->Attendence);
                $AttTime = new DateTime($att->In_Time);
                $DifTimeAtt = $Att->diff($AttTime);



                $Dep = new DateTime($Mwzf->Departure);
                $DepTime = new DateTime($att->Out_Time);
                $DifTimeDep = $DepTime->diff($Dep);

                $x=$DifTimeAtt->format("%h:%i:%s");
                $y=$DifTimeDep->format("%h:%i:%s");



                $tAtt = explode(':', $x);
                $tDep = explode(':', $y);
                $CountMinAtt= ($tAtt[0]*60) + ($tAtt[1]) + ($tAtt[2]/60);
                $CountMinDep= ($tDep[0]*60) + ($tDep[1]) + ($tDep[2]/60);



                $AttValue=AttendencePolicyEmp::where('Emp',$att->Emp)
                    ->where('From','<=',$CountMinAtt) ->where('To','>=',$CountMinAtt)
                    ->get()
                    ->sum('Discount');

                $DepartValue=DepaarturePolicyEmp::where('Emp',$att->Emp)
                    ->where('From','<=',$CountMinDep) ->where('To','>=',$CountMinDep)
                    ->get()
                    ->sum('Discount');




                //#ayz mo3dlt tar7 wakt mn wakt



                $timestampOut = strtotime($att->Out_Time);


                $timestampIn = strtotime($att->In_Time);


                $Hours_Number = $timestampOut - $timestampIn;



                $empo['In_Time']=$att->In_Time;
                $empo['Date']=$att->Date;
                $empo['Month']=$att->Month;
                $empo['Note']=$att->Note;
                $empo['Out_Time']=$att->Out_Time;
                $empo['Hours_Number']=$Hours_Number;
                $empo['Departure']=$ID;
                $empo['Emp']=$att->Emp;

                $empo['Disc_Late']=$AttValue;
                $empo['Disc_Early']=$DepartValue;

                DepartureEmp::create($empo);


            }
            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }





    //Governrate
    function ImportGovernrate(Request $request)
    {
        try {
            DB::beginTransaction();

            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);


            $file = $request->File;
            Excel::import(new GovImport,$file);

            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }

//ImportCity
        function ImportCity(Request $request)
    {
        try {
            DB::beginTransaction();

            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);


            $file = $request->File;
            Excel::import(new CityImport,$file);

            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }

//ImportPlace
    function ImportPlace(Request $request)
    {
        try {
            DB::beginTransaction();

            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);


            $file = $request->File;
            Excel::import(new PlaceImport,$file);

            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }


    //ImportTest
    function ImportTest(Request $request)
    {
        try {
            DB::beginTransaction();

            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'
            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);


            $file = $request->File;
            Excel::import(new TestImport,$file);

            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }




//Canceled
    function ImportProductRepeat(Request $request)
    {

        try {
            DB::beginTransaction();

            $this->validate($request, [
                'File' => 'required|mimes:xls,xlsx'

            ],

                [
                    'File.required' => trans('admin.FileRequired'),
                ]);



            $file = $request->File;
            Excel::import(new ProductFileStart,$file);

            $Products=ImportNewProdsStart::where('Num',1)->get();



            $res=StartPeriods::orderBy('id','desc')->first();

            if(!empty($res->Code)){

                $Code=$res->Code + 1 ;

            }else{

                $Code=1;

            }

            $COUNT=ImportNewProdsStart::count();
            $TOTQTY=ImportNewProdsStart::get()->sum('Qty');
            $TOT=ImportNewProdsStart::get()->sum('Total');
            $last=ImportNewProdsStart::orderBy('id','desc')->first();
            $Def=StoresDefaultData::orderBy('id','desc')->first();
            $s=Stores::find($last->Store);
            $IDD = DB::table('start_periods')->insertGetId(
                array(

                    'Code' => $Code,
                    'Date' => date('Y-m-d'),
                    'Store' => $last->Store,
                    'Draw' => 1,
                    'Note' => null,
                    'Total_Products' => $COUNT,
                    'Total_Qty' => $TOTQTY,
                    'Total_Price' => $TOT,
                    'Coin' => $Def->Coin,
                    'User' => 1,
                    'Time' => date("h:i:s a", time()),
                    'Branch' => $s->Branch,


                )
            );

            $dataStMove['Date']=date('Y-m-d');
            $dataStMove['Code']=$Code;
            $dataStMove['Time']=date("h:i:s a", time());
            $dataStMove['Branch']=$s->Branch;
            $dataStMove['Store']=$last->Store;
            $dataStMove['Safe']=null;
            $dataStMove['Type']='بدايه فتره';
            $dataStMove['Cost_Center']=null;
            $dataStMove['User']=1;
            $dataStMove['Coin']=$Def->Coin;
            $dataStMove['Note']=null;
            $dataStMove['Total_Qty']=$TOTQTY;
            $dataStMove['Total_Price']=$TOT;
            $dataStMove['Account']=null;
            $dataStMove['Ship']=null;
            $dataStMove['ID']=$IDD;
            StoresMoves::create($dataStMove);

            foreach($Products as $pro){


                $ID = DB::table('products')->insertGetId(

                    array(

                        'P_Type' => $pro->Type,
                        'P_Ar_Name' => $pro->Name,
                        'P_En_Name' => $pro->Name,
                        'Brand' => $pro->Brand,
                        'Group' => $pro->Group,
                        'Code_Type' => $pro->Code_Type,
                        'World_Code' => $pro->World_Code,
                        'Tax' => 1,
                        'Validity' => 1,
                        'Store_Show' => 0,
                        'Status' => 0,

                    )
                );


                $uu['Rate']=$pro->Rate;
                $uu['Barcode']=$pro->Barcode;
                $uu['Price']=$pro->Price_1;
                $uu['Price_Two']=$pro->Price_2;
                $uu['Price_Three']=$pro->Price_3;
                $uu['Def']=$pro->Def;
                $uu['P_Ar_Name']=$pro->Name;
                $uu['P_En_Name']=$pro->Name;
                $uu['P_Type']=$pro->Type;
                $uu['Unit']=$pro->Unit;
                $uu['Product']=$ID;
                $uu['Brand']=$pro->Brand;
                $uu['Group']=$pro->Group;
                ProductUnits::create($uu);

                $Pro2=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',2)->first();


                $Pro3=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',3)->first();


                $Pro4=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',4)->first();

                $Pro5=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',5)->first();

                $Pro6=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',6)->first();

                $Pro7=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',7)->first();

                $Pro8=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',8)->first();

                $Pro9=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',9)->first();

                $Pro10=ImportNewProdsStart::where('Name',$pro->Name)
                    ->where('Num',10)->first();


                if(!empty($Pro2)){

                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();
                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();



                    $uu['P_Code']=$Pro2->Barcode;
                    $uu['SmallCode']=$plow->Barcode;
                    $uu['Qty']=$Pro2->Qty;
                    $uu['SmallQty']=$Pro2->Qty * $pp->Rate;
                    $uu['Price']=$Pro2->CostPrice;
                    $uu['Total']=$Pro2->Total;
                    $uu['Old_Qty']=$Pro2->Qty;
                    $uu['Exp_Date']=null;
                    $uu['SP_ID']=$IDD;
                    $uu['Date']=date('Y-m-d');
                    $uu['Store']=$Pro2->Store;
                    $uu['User']=1;
                    $uu['Unit']=$Pro2->Unit;
                    $uu['P_Ar_Name']=$Pro2->Name;
                    $uu['P_En_Name']=$Pro2->Name;
                    $uu['V_Name']=null;
                    $uu['VV_Name']=null;
                    $uu['Product']=$ID;
                    $uu['Patch_Number']=null;
                    $uu['V1']=null;
                    $uu['V2']=null;

                    ProductsStartPeriods::create($uu);


                    $prooooo=Products::find($ID);

                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();
                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();

                    $purchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro2->Store)->get()->sum('Total_Bf_Tax');
                    $countPurchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro2->Store)->get()->sum('SmallQty');

                    $purchsStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro2->Store)->get()->sum('Total');

                    $countStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro2->Store)->get()->sum('SmallQty');
                    $storesTransfer=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro2->Store)->get()->sum('Total');

                    $storesTransferCount=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro2->Store)->get()->sum('SmallTrans_Qty');


                    $OUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro2->Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');

                    $countOUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro2->Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');


                    $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME;
                    $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

                    if($CollectCount != 0){
                        $ty= $Collect / $CollectCount ;
                    }else{

                        $ty= $Collect;
                    }



                    $in=($Pro2->Qty * $pp->Rate) * $ty ;
                    $out=0 ;
                    $current=($Pro2->Qty * $pp->Rate) * $ty ;

                    $RR=StartPeriods::find($IDD);
                    $move['Date']=date('Y-m-d');
                    $move['Type']='بدايه فتره';
                    $move['Bill_Num']=$RR->Code;
                    $move['Incom']=$Pro2->Qty * $pp->Rate;
                    $move['Outcom']=0;
                    $move['Current']=$Pro2->Qty * $pp->Rate;
                    $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                    $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                    $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                    $move['P_Ar_Name']=$Pro2->Name;
                    $move['P_En_Name']=$Pro2->Name;
                    $move['P_Code']=$Pro2->Barcode;
                    $move['Unit']=$Pro2->Unit;
                    $move['QTY']=$Pro2->Qty;
                    $move['Group']=$prooooo->Group;
                    $move['Store']=$Pro2->Store;
                    $move['Product']=$ID;
                    $move['V1']=null;
                    $move['V2']=null;
                    $move['User']=1;
                    $Sro=Stores::find($Pro2->Store);

                    $move['Brand']=$prooooo->Brand;
                    $move['Safe']=null;
                    $move['Branch']=$Sro->Branch;
                    $move['SalePrice']=null;
                    $move['ProductPrice']=null;
                    ProductMoves::create($move);

                    $id_store = DB::table('products_stores')->insertGetId(

                        array(

                            'P_Ar_Name' => $Pro2->Name,
                            'P_En_Name' => $Pro2->Name,
                            'P_Code' => $Pro2->Barcode,
                            'Exp_Date' => null,
                            'Product' => $ID,
                            'Store' =>$Pro2->Store,
                            'V1' => null,
                            'V2' => null,
                            'V_Name' => null,
                            'VV_Name' => null,

                        )
                    );



                    $pqty['P_Ar_Name']=$Pro2->Name;
                    $pqty['Price_Sale']=$Pro2->Price;
                    $pqty['P_En_Name']=$Pro2->Name;
                    $pqty['Qty']=$Pro2->Qty * $pp->Rate;
                    $pqty['Price']=$Pro2->Price;
                    $pqty['TotalCost']=$Pro2->Price;
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$Pro2->Store;
                    $pqty['Unit']=$Pro2->Unit;
                    $pqty['Exp_Date']=null;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$ID;
                    $pqty['Patch_Number']=null;
                    $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;
                    $pqty['P_Code']=$Pro2->Barcode;
                    $pqty['PP_Code']=null;
                    $pqty['PPP_Code']=null;
                    $pqty['PPPP_Code']=null;
                    ProductsQty::create($pqty);






                }

                if(!empty($Pro3)){

                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();
                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();



                    $uu['P_Code']=$Pro3->Barcode;
                    $uu['SmallCode']=$plow->Barcode;
                    $uu['Qty']=$Pro3->Qty;
                    $uu['SmallQty']=$Pro3->Qty * $pp->Rate;
                    $uu['Price']=$Pro3->CostPrice;
                    $uu['Total']=$Pro3->Total;
                    $uu['Old_Qty']=$Pro3->Qty;
                    $uu['Exp_Date']=null;
                    $uu['SP_ID']=$IDD;
                    $uu['Date']=date('Y-m-d');
                    $uu['Store']=$Pro3->Store;
                    $uu['User']=1;
                    $uu['Unit']=$Pro3->Unit;
                    $uu['P_Ar_Name']=$Pro3->Name;
                    $uu['P_En_Name']=$Pro3->Name;
                    $uu['V_Name']=null;
                    $uu['VV_Name']=null;
                    $uu['Product']=$ID;
                    $uu['Patch_Number']=null;
                    $uu['V1']=null;
                    $uu['V2']=null;

                    ProductsStartPeriods::create($uu);


                    $prooooo=Products::find($ID);

                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();
                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();

                    $purchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro3->Store)->get()->sum('Total_Bf_Tax');
                    $countPurchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro3->Store)->get()->sum('SmallQty');

                    $purchsStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro3->Store)->get()->sum('Total');

                    $countStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro3->Store)->get()->sum('SmallQty');
                    $storesTransfer=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro3->Store)->get()->sum('Total');

                    $storesTransferCount=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro3->Store)->get()->sum('SmallTrans_Qty');


                    $OUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro3->Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');

                    $countOUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro3->Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');


                    $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME;
                    $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

                    if($CollectCount != 0){
                        $ty= $Collect / $CollectCount ;
                    }else{

                        $ty= $Collect;
                    }



                    $in=($Pro3->Qty * $pp->Rate) * $ty ;
                    $out=0 ;
                    $current=($Pro3->Qty * $pp->Rate) * $ty ;

                    $RR=StartPeriods::find($IDD);
                    $move['Date']=date('Y-m-d');
                    $move['Type']='بدايه فتره';
                    $move['Bill_Num']=$RR->Code;
                    $move['Incom']=$Pro3->Qty * $pp->Rate;
                    $move['Outcom']=0;
                    $move['Current']=$Pro3->Qty * $pp->Rate;
                    $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                    $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                    $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                    $move['P_Ar_Name']=$Pro3->Name;
                    $move['P_En_Name']=$Pro3->Name;
                    $move['P_Code']=$Pro3->Barcode;
                    $move['Unit']=$Pro3->Unit;
                    $move['QTY']=$Pro3->Qty;
                    $move['Group']=$prooooo->Group;
                    $move['Store']=$Pro3->Store;
                    $move['Product']=$ID;
                    $move['V1']=null;
                    $move['V2']=null;
                    $move['User']=1;
                    $Sro=Stores::find($Pro3->Store);

                    $move['Brand']=$prooooo->Brand;
                    $move['Safe']=null;
                    $move['Branch']=$Sro->Branch;
                    $move['SalePrice']=null;
                    $move['ProductPrice']=null;
                    ProductMoves::create($move);

                    $id_store = DB::table('products_stores')->insertGetId(

                        array(

                            'P_Ar_Name' => $Pro3->Name,
                            'P_En_Name' => $Pro3->Name,
                            'P_Code' => $Pro3->Barcode,
                            'Exp_Date' => null,
                            'Product' => $ID,
                            'Store' =>$Pro3->Store,
                            'V1' => null,
                            'V2' => null,
                            'V_Name' => null,
                            'VV_Name' => null,

                        )
                    );



                    $pqty['P_Ar_Name']=$Pro3->Name;
                    $pqty['Price_Sale']=$Pro3->Price;
                    $pqty['P_En_Name']=$Pro3->Name;
                    $pqty['Qty']=$Pro3->Qty * $pp->Rate;
                    $pqty['Price']=$Pro3->Price;
                    $pqty['TotalCost']=$Pro3->Price;
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$Pro3->Store;
                    $pqty['Unit']=$Pro3->Unit;
                    $pqty['Exp_Date']=null;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$ID;
                    $pqty['Patch_Number']=null;
                    $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;
                    $pqty['P_Code']=$Pro3->Barcode;
                    $pqty['PP_Code']=null;
                    $pqty['PPP_Code']=null;
                    $pqty['PPPP_Code']=null;
                    ProductsQty::create($pqty);






                }
                if(!empty($Pro4)){

                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();
                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();



                    $uu['P_Code']=$Pro4->Barcode;
                    $uu['SmallCode']=$plow->Barcode;
                    $uu['Qty']=$Pro4->Qty;
                    $uu['SmallQty']=$Pro4->Qty * $pp->Rate;
                    $uu['Price']=$Pro4->CostPrice;
                    $uu['Total']=$Pro4->Total;
                    $uu['Old_Qty']=$Pro4->Qty;
                    $uu['Exp_Date']=null;
                    $uu['SP_ID']=$IDD;
                    $uu['Date']=date('Y-m-d');
                    $uu['Store']=$Pro4->Store;
                    $uu['User']=1;
                    $uu['Unit']=$Pro4->Unit;
                    $uu['P_Ar_Name']=$Pro4->Name;
                    $uu['P_En_Name']=$Pro4->Name;
                    $uu['V_Name']=null;
                    $uu['VV_Name']=null;
                    $uu['Product']=$ID;
                    $uu['Patch_Number']=null;
                    $uu['V1']=null;
                    $uu['V2']=null;

                    ProductsStartPeriods::create($uu);


                    $prooooo=Products::find($ID);

                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();
                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();

                    $purchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro4->Store)->get()->sum('Total_Bf_Tax');
                    $countPurchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro4->Store)->get()->sum('SmallQty');

                    $purchsStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro4->Store)->get()->sum('Total');

                    $countStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro4->Store)->get()->sum('SmallQty');
                    $storesTransfer=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro4->Store)->get()->sum('Total');

                    $storesTransferCount=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro4->Store)->get()->sum('SmallTrans_Qty');


                    $OUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro4->Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');

                    $countOUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro4->Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');


                    $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME;
                    $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

                    if($CollectCount != 0){
                        $ty= $Collect / $CollectCount ;
                    }else{

                        $ty= $Collect;
                    }



                    $in=($Pro4->Qty * $pp->Rate) * $ty ;
                    $out=0 ;
                    $current=($Pro4->Qty * $pp->Rate) * $ty ;

                    $RR=StartPeriods::find($IDD);
                    $move['Date']=date('Y-m-d');
                    $move['Type']='بدايه فتره';
                    $move['Bill_Num']=$RR->Code;
                    $move['Incom']=$Pro4->Qty * $pp->Rate;
                    $move['Outcom']=0;
                    $move['Current']=$Pro4->Qty * $pp->Rate;
                    $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                    $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                    $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                    $move['P_Ar_Name']=$Pro4->Name;
                    $move['P_En_Name']=$Pro4->Name;
                    $move['P_Code']=$Pro4->Barcode;
                    $move['Unit']=$Pro4->Unit;
                    $move['QTY']=$Pro4->Qty;
                    $move['Group']=$prooooo->Group;
                    $move['Store']=$Pro4->Store;
                    $move['Product']=$ID;
                    $move['V1']=null;
                    $move['V2']=null;
                    $move['User']=1;
                    $Sro=Stores::find($Pro4->Store);

                    $move['Brand']=$prooooo->Brand;
                    $move['Safe']=null;
                    $move['Branch']=$Sro->Branch;
                    $move['SalePrice']=null;
                    $move['ProductPrice']=null;
                    ProductMoves::create($move);

                    $id_store = DB::table('products_stores')->insertGetId(

                        array(

                            'P_Ar_Name' => $Pro4->Name,
                            'P_En_Name' => $Pro4->Name,
                            'P_Code' => $Pro4->Barcode,
                            'Exp_Date' => null,
                            'Product' => $ID,
                            'Store' =>$Pro4->Store,
                            'V1' => null,
                            'V2' => null,
                            'V_Name' => null,
                            'VV_Name' => null,

                        )
                    );



                    $pqty['P_Ar_Name']=$Pro4->Name;
                    $pqty['Price_Sale']=$Pro4->Price;
                    $pqty['P_En_Name']=$Pro4->Name;
                    $pqty['Qty']=$Pro4->Qty * $pp->Rate;
                    $pqty['Price']=$Pro4->Price;
                    $pqty['TotalCost']=$Pro4->Price;
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$Pro4->Store;
                    $pqty['Unit']=$Pro4->Unit;
                    $pqty['Exp_Date']=null;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$ID;
                    $pqty['Patch_Number']=null;
                    $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;
                    $pqty['P_Code']=$Pro4->Barcode;
                    $pqty['PP_Code']=null;
                    $pqty['PPP_Code']=null;
                    $pqty['PPPP_Code']=null;
                    ProductsQty::create($pqty);






                }

                if(!empty($Pro5)){

                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();
                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();



                    $uu['P_Code']=$Pro5->Barcode;
                    $uu['SmallCode']=$plow->Barcode;
                    $uu['Qty']=$Pro5->Qty;
                    $uu['SmallQty']=$Pro5->Qty * $pp->Rate;
                    $uu['Price']=$Pro5->CostPrice;
                    $uu['Total']=$Pro5->Total;
                    $uu['Old_Qty']=$Pro5->Qty;
                    $uu['Exp_Date']=null;
                    $uu['SP_ID']=$IDD;
                    $uu['Date']=date('Y-m-d');
                    $uu['Store']=$Pro5->Store;
                    $uu['User']=1;
                    $uu['Unit']=$Pro5->Unit;
                    $uu['P_Ar_Name']=$Pro5->Name;
                    $uu['P_En_Name']=$Pro5->Name;
                    $uu['V_Name']=null;
                    $uu['VV_Name']=null;
                    $uu['Product']=$ID;
                    $uu['Patch_Number']=null;
                    $uu['V1']=null;
                    $uu['V2']=null;

                    ProductsStartPeriods::create($uu);


                    $prooooo=Products::find($ID);

                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();
                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();

                    $purchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro5->Store)->get()->sum('Total_Bf_Tax');
                    $countPurchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro5->Store)->get()->sum('SmallQty');

                    $purchsStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro5->Store)->get()->sum('Total');

                    $countStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro5->Store)->get()->sum('SmallQty');
                    $storesTransfer=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro5->Store)->get()->sum('Total');

                    $storesTransferCount=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro5->Store)->get()->sum('SmallTrans_Qty');


                    $OUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro5->Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');

                    $countOUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro5->Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');


                    $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME;
                    $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

                    if($CollectCount != 0){
                        $ty= $Collect / $CollectCount ;
                    }else{

                        $ty= $Collect;
                    }



                    $in=($Pro5->Qty * $pp->Rate) * $ty ;
                    $out=0 ;
                    $current=($Pro5->Qty * $pp->Rate) * $ty ;

                    $RR=StartPeriods::find($IDD);
                    $move['Date']=date('Y-m-d');
                    $move['Type']='بدايه فتره';
                    $move['Bill_Num']=$RR->Code;
                    $move['Incom']=$Pro5->Qty * $pp->Rate;
                    $move['Outcom']=0;
                    $move['Current']=$Pro5->Qty * $pp->Rate;
                    $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                    $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                    $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                    $move['P_Ar_Name']=$Pro5->Name;
                    $move['P_En_Name']=$Pro5->Name;
                    $move['P_Code']=$Pro5->Barcode;
                    $move['Unit']=$Pro5->Unit;
                    $move['QTY']=$Pro5->Qty;
                    $move['Group']=$prooooo->Group;
                    $move['Store']=$Pro5->Store;
                    $move['Product']=$ID;
                    $move['V1']=null;
                    $move['V2']=null;
                    $move['User']=1;
                    $Sro=Stores::find($Pro5->Store);

                    $move['Brand']=$prooooo->Brand;
                    $move['Safe']=null;
                    $move['Branch']=$Sro->Branch;
                    $move['SalePrice']=null;
                    $move['ProductPrice']=null;
                    ProductMoves::create($move);

                    $id_store = DB::table('products_stores')->insertGetId(

                        array(

                            'P_Ar_Name' => $Pro5->Name,
                            'P_En_Name' => $Pro5->Name,
                            'P_Code' => $Pro5->Barcode,
                            'Exp_Date' => null,
                            'Product' => $ID,
                            'Store' =>$Pro5->Store,
                            'V1' => null,
                            'V2' => null,
                            'V_Name' => null,
                            'VV_Name' => null,

                        )
                    );



                    $pqty['P_Ar_Name']=$Pro5->Name;
                    $pqty['Price_Sale']=$Pro5->Price;
                    $pqty['P_En_Name']=$Pro5->Name;
                    $pqty['Qty']=$Pro5->Qty * $pp->Rate;
                    $pqty['Price']=$Pro5->Price;
                    $pqty['TotalCost']=$Pro5->Price;
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$Pro5->Store;
                    $pqty['Unit']=$Pro5->Unit;
                    $pqty['Exp_Date']=null;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$ID;
                    $pqty['Patch_Number']=null;
                    $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;
                    $pqty['P_Code']=$Pro5->Barcode;
                    $pqty['PP_Code']=null;
                    $pqty['PPP_Code']=null;
                    $pqty['PPPP_Code']=null;
                    ProductsQty::create($pqty);






                }

                if(!empty($Pro6)){

                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();
                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();



                    $uu['P_Code']=$Pro6->Barcode;
                    $uu['SmallCode']=$plow->Barcode;
                    $uu['Qty']=$Pro6->Qty;
                    $uu['SmallQty']=$Pro6->Qty * $pp->Rate;
                    $uu['Price']=$Pro6->CostPrice;
                    $uu['Total']=$Pro6->Total;
                    $uu['Old_Qty']=$Pro6->Qty;
                    $uu['Exp_Date']=null;
                    $uu['SP_ID']=$IDD;
                    $uu['Date']=date('Y-m-d');
                    $uu['Store']=$Pro6->Store;
                    $uu['User']=1;
                    $uu['Unit']=$Pro6->Unit;
                    $uu['P_Ar_Name']=$Pro6->Name;
                    $uu['P_En_Name']=$Pro6->Name;
                    $uu['V_Name']=null;
                    $uu['VV_Name']=null;
                    $uu['Product']=$ID;
                    $uu['Patch_Number']=null;
                    $uu['V1']=null;
                    $uu['V2']=null;

                    ProductsStartPeriods::create($uu);


                    $prooooo=Products::find($ID);

                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();
                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();

                    $purchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro6->Store)->get()->sum('Total_Bf_Tax');
                    $countPurchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro6->Store)->get()->sum('SmallQty');

                    $purchsStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro6->Store)->get()->sum('Total');

                    $countStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro6->Store)->get()->sum('SmallQty');
                    $storesTransfer=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro6->Store)->get()->sum('Total');

                    $storesTransferCount=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro6->Store)->get()->sum('SmallTrans_Qty');


                    $OUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro6->Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');

                    $countOUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro6->Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');


                    $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME;
                    $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

                    if($CollectCount != 0){
                        $ty= $Collect / $CollectCount ;
                    }else{

                        $ty= $Collect;
                    }



                    $in=($Pro6->Qty * $pp->Rate) * $ty ;
                    $out=0 ;
                    $current=($Pro6->Qty * $pp->Rate) * $ty ;

                    $RR=StartPeriods::find($IDD);
                    $move['Date']=date('Y-m-d');
                    $move['Type']='بدايه فتره';
                    $move['Bill_Num']=$RR->Code;
                    $move['Incom']=$Pro6->Qty * $pp->Rate;
                    $move['Outcom']=0;
                    $move['Current']=$Pro6->Qty * $pp->Rate;
                    $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                    $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                    $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                    $move['P_Ar_Name']=$Pro6->Name;
                    $move['P_En_Name']=$Pro6->Name;
                    $move['P_Code']=$Pro6->Barcode;
                    $move['Unit']=$Pro6->Unit;
                    $move['QTY']=$Pro6->Qty;
                    $move['Group']=$prooooo->Group;
                    $move['Store']=$Pro6->Store;
                    $move['Product']=$ID;
                    $move['V1']=null;
                    $move['V2']=null;
                    $move['User']=1;
                    $Sro=Stores::find($Pro6->Store);

                    $move['Brand']=$prooooo->Brand;
                    $move['Safe']=null;
                    $move['Branch']=$Sro->Branch;
                    $move['SalePrice']=null;
                    $move['ProductPrice']=null;
                    ProductMoves::create($move);

                    $id_store = DB::table('products_stores')->insertGetId(

                        array(

                            'P_Ar_Name' => $Pro6->Name,
                            'P_En_Name' => $Pro6->Name,
                            'P_Code' => $Pro6->Barcode,
                            'Exp_Date' => null,
                            'Product' => $ID,
                            'Store' =>$Pro6->Store,
                            'V1' => null,
                            'V2' => null,
                            'V_Name' => null,
                            'VV_Name' => null,

                        )
                    );



                    $pqty['P_Ar_Name']=$Pro6->Name;
                    $pqty['Price_Sale']=$Pro6->Price;
                    $pqty['P_En_Name']=$Pro6->Name;
                    $pqty['Qty']=$Pro6->Qty * $pp->Rate;
                    $pqty['Price']=$Pro6->Price;
                    $pqty['TotalCost']=$Pro6->Price;
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$Pro6->Store;
                    $pqty['Unit']=$Pro6->Unit;
                    $pqty['Exp_Date']=null;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$ID;
                    $pqty['Patch_Number']=null;
                    $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;
                    $pqty['P_Code']=$Pro6->Barcode;
                    $pqty['PP_Code']=null;
                    $pqty['PPP_Code']=null;
                    $pqty['PPPP_Code']=null;
                    ProductsQty::create($pqty);






                }

                if(!empty($Pro7)){

                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();
                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();



                    $uu['P_Code']=$Pro7->Barcode;
                    $uu['SmallCode']=$plow->Barcode;
                    $uu['Qty']=$Pro7->Qty;
                    $uu['SmallQty']=$Pro7->Qty * $pp->Rate;
                    $uu['Price']=$Pro7->CostPrice;
                    $uu['Total']=$Pro7->Total;
                    $uu['Old_Qty']=$Pro7->Qty;
                    $uu['Exp_Date']=null;
                    $uu['SP_ID']=$IDD;
                    $uu['Date']=date('Y-m-d');
                    $uu['Store']=$Pro7->Store;
                    $uu['User']=1;
                    $uu['Unit']=$Pro7->Unit;
                    $uu['P_Ar_Name']=$Pro7->Name;
                    $uu['P_En_Name']=$Pro7->Name;
                    $uu['V_Name']=null;
                    $uu['VV_Name']=null;
                    $uu['Product']=$ID;
                    $uu['Patch_Number']=null;
                    $uu['V1']=null;
                    $uu['V2']=null;

                    ProductsStartPeriods::create($uu);


                    $prooooo=Products::find($ID);

                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();
                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();

                    $purchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro7->Store)->get()->sum('Total_Bf_Tax');
                    $countPurchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro7->Store)->get()->sum('SmallQty');

                    $purchsStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro7->Store)->get()->sum('Total');

                    $countStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro7->Store)->get()->sum('SmallQty');
                    $storesTransfer=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro7->Store)->get()->sum('Total');

                    $storesTransferCount=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro7->Store)->get()->sum('SmallTrans_Qty');


                    $OUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro7->Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');

                    $countOUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro7->Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');


                    $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME;
                    $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

                    if($CollectCount != 0){
                        $ty= $Collect / $CollectCount ;
                    }else{

                        $ty= $Collect;
                    }



                    $in=($Pro7->Qty * $pp->Rate) * $ty ;
                    $out=0 ;
                    $current=($Pro7->Qty * $pp->Rate) * $ty ;

                    $RR=StartPeriods::find($IDD);
                    $move['Date']=date('Y-m-d');
                    $move['Type']='بدايه فتره';
                    $move['Bill_Num']=$RR->Code;
                    $move['Incom']=$Pro7->Qty * $pp->Rate;
                    $move['Outcom']=0;
                    $move['Current']=$Pro7->Qty * $pp->Rate;
                    $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                    $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                    $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                    $move['P_Ar_Name']=$Pro7->Name;
                    $move['P_En_Name']=$Pro7->Name;
                    $move['P_Code']=$Pro7->Barcode;
                    $move['Unit']=$Pro7->Unit;
                    $move['QTY']=$Pro7->Qty;
                    $move['Group']=$prooooo->Group;
                    $move['Store']=$Pro7->Store;
                    $move['Product']=$ID;
                    $move['V1']=null;
                    $move['V2']=null;
                    $move['User']=1;
                    $Sro=Stores::find($Pro7->Store);

                    $move['Brand']=$prooooo->Brand;
                    $move['Safe']=null;
                    $move['Branch']=$Sro->Branch;
                    $move['SalePrice']=null;
                    $move['ProductPrice']=null;
                    ProductMoves::create($move);

                    $id_store = DB::table('products_stores')->insertGetId(

                        array(

                            'P_Ar_Name' => $Pro7->Name,
                            'P_En_Name' => $Pro7->Name,
                            'P_Code' => $Pro7->Barcode,
                            'Exp_Date' => null,
                            'Product' => $ID,
                            'Store' =>$Pro7->Store,
                            'V1' => null,
                            'V2' => null,
                            'V_Name' => null,
                            'VV_Name' => null,

                        )
                    );



                    $pqty['P_Ar_Name']=$Pro7->Name;
                    $pqty['Price_Sale']=$Pro7->Price;
                    $pqty['P_En_Name']=$Pro7->Name;
                    $pqty['Qty']=$Pro7->Qty * $pp->Rate;
                    $pqty['Price']=$Pro7->Price;
                    $pqty['TotalCost']=$Pro7->Price;
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$Pro7->Store;
                    $pqty['Unit']=$Pro7->Unit;
                    $pqty['Exp_Date']=null;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$ID;
                    $pqty['Patch_Number']=null;
                    $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;
                    $pqty['P_Code']=$Pro7->Barcode;
                    $pqty['PP_Code']=null;
                    $pqty['PPP_Code']=null;
                    $pqty['PPPP_Code']=null;
                    ProductsQty::create($pqty);






                }

                if(!empty($Pro8)){

                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();
                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();



                    $uu['P_Code']=$Pro8->Barcode;
                    $uu['SmallCode']=$plow->Barcode;
                    $uu['Qty']=$Pro8->Qty;
                    $uu['SmallQty']=$Pro8->Qty * $pp->Rate;
                    $uu['Price']=$Pro8->CostPrice;
                    $uu['Total']=$Pro8->Total;
                    $uu['Old_Qty']=$Pro8->Qty;
                    $uu['Exp_Date']=null;
                    $uu['SP_ID']=$IDD;
                    $uu['Date']=date('Y-m-d');
                    $uu['Store']=$Pro8->Store;
                    $uu['User']=1;
                    $uu['Unit']=$Pro8->Unit;
                    $uu['P_Ar_Name']=$Pro8->Name;
                    $uu['P_En_Name']=$Pro8->Name;
                    $uu['V_Name']=null;
                    $uu['VV_Name']=null;
                    $uu['Product']=$ID;
                    $uu['Patch_Number']=null;
                    $uu['V1']=null;
                    $uu['V2']=null;

                    ProductsStartPeriods::create($uu);


                    $prooooo=Products::find($ID);

                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();
                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();

                    $purchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro8->Store)->get()->sum('Total_Bf_Tax');
                    $countPurchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro8->Store)->get()->sum('SmallQty');

                    $purchsStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro8->Store)->get()->sum('Total');

                    $countStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro8->Store)->get()->sum('SmallQty');
                    $storesTransfer=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro8->Store)->get()->sum('Total');

                    $storesTransferCount=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro8->Store)->get()->sum('SmallTrans_Qty');


                    $OUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro8->Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');

                    $countOUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro8->Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');


                    $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME;
                    $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

                    if($CollectCount != 0){
                        $ty= $Collect / $CollectCount ;
                    }else{

                        $ty= $Collect;
                    }



                    $in=($Pro8->Qty * $pp->Rate) * $ty ;
                    $out=0 ;
                    $current=($Pro8->Qty * $pp->Rate) * $ty ;

                    $RR=StartPeriods::find($IDD);
                    $move['Date']=date('Y-m-d');
                    $move['Type']='بدايه فتره';
                    $move['Bill_Num']=$RR->Code;
                    $move['Incom']=$Pro8->Qty * $pp->Rate;
                    $move['Outcom']=0;
                    $move['Current']=$Pro8->Qty * $pp->Rate;
                    $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                    $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                    $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                    $move['P_Ar_Name']=$Pro8->Name;
                    $move['P_En_Name']=$Pro8->Name;
                    $move['P_Code']=$Pro8->Barcode;
                    $move['Unit']=$Pro8->Unit;
                    $move['QTY']=$Pro8->Qty;
                    $move['Group']=$prooooo->Group;
                    $move['Store']=$Pro8->Store;
                    $move['Product']=$ID;
                    $move['V1']=null;
                    $move['V2']=null;
                    $move['User']=1;
                    $Sro=Stores::find($Pro8->Store);

                    $move['Brand']=$prooooo->Brand;
                    $move['Safe']=null;
                    $move['Branch']=$Sro->Branch;
                    $move['SalePrice']=null;
                    $move['ProductPrice']=null;
                    ProductMoves::create($move);

                    $id_store = DB::table('products_stores')->insertGetId(

                        array(

                            'P_Ar_Name' => $Pro8->Name,
                            'P_En_Name' => $Pro8->Name,
                            'P_Code' => $Pro8->Barcode,
                            'Exp_Date' => null,
                            'Product' => $ID,
                            'Store' =>$Pro8->Store,
                            'V1' => null,
                            'V2' => null,
                            'V_Name' => null,
                            'VV_Name' => null,

                        )
                    );



                    $pqty['P_Ar_Name']=$Pro8->Name;
                    $pqty['Price_Sale']=$Pro8->Price;
                    $pqty['P_En_Name']=$Pro8->Name;
                    $pqty['Qty']=$Pro8->Qty * $pp->Rate;
                    $pqty['Price']=$Pro8->Price;
                    $pqty['TotalCost']=$Pro8->Price;
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$Pro8->Store;
                    $pqty['Unit']=$Pro8->Unit;
                    $pqty['Exp_Date']=null;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$ID;
                    $pqty['Patch_Number']=null;
                    $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;
                    $pqty['P_Code']=$Pro8->Barcode;
                    $pqty['PP_Code']=null;
                    $pqty['PPP_Code']=null;
                    $pqty['PPPP_Code']=null;
                    ProductsQty::create($pqty);






                }

                if(!empty($Pro9)){

                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();
                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();



                    $uu['P_Code']=$Pro9->Barcode;
                    $uu['SmallCode']=$plow->Barcode;
                    $uu['Qty']=$Pro9->Qty;
                    $uu['SmallQty']=$Pro9->Qty * $pp->Rate;
                    $uu['Price']=$Pro9->CostPrice;
                    $uu['Total']=$Pro9->Total;
                    $uu['Old_Qty']=$Pro9->Qty;
                    $uu['Exp_Date']=null;
                    $uu['SP_ID']=$IDD;
                    $uu['Date']=date('Y-m-d');
                    $uu['Store']=$Pro9->Store;
                    $uu['User']=1;
                    $uu['Unit']=$Pro9->Unit;
                    $uu['P_Ar_Name']=$Pro9->Name;
                    $uu['P_En_Name']=$Pro9->Name;
                    $uu['V_Name']=null;
                    $uu['VV_Name']=null;
                    $uu['Product']=$ID;
                    $uu['Patch_Number']=null;
                    $uu['V1']=null;
                    $uu['V2']=null;

                    ProductsStartPeriods::create($uu);


                    $prooooo=Products::find($ID);

                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();
                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();

                    $purchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro9->Store)->get()->sum('Total_Bf_Tax');
                    $countPurchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro9->Store)->get()->sum('SmallQty');

                    $purchsStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro9->Store)->get()->sum('Total');

                    $countStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro9->Store)->get()->sum('SmallQty');
                    $storesTransfer=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro9->Store)->get()->sum('Total');

                    $storesTransferCount=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro9->Store)->get()->sum('SmallTrans_Qty');


                    $OUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro9->Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');

                    $countOUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro9->Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');


                    $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME;
                    $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

                    if($CollectCount != 0){
                        $ty= $Collect / $CollectCount ;
                    }else{

                        $ty= $Collect;
                    }



                    $in=($Pro9->Qty * $pp->Rate) * $ty ;
                    $out=0 ;
                    $current=($Pro9->Qty * $pp->Rate) * $ty ;

                    $RR=StartPeriods::find($IDD);
                    $move['Date']=date('Y-m-d');
                    $move['Type']='بدايه فتره';
                    $move['Bill_Num']=$RR->Code;
                    $move['Incom']=$Pro9->Qty * $pp->Rate;
                    $move['Outcom']=0;
                    $move['Current']=$Pro9->Qty * $pp->Rate;
                    $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                    $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                    $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                    $move['P_Ar_Name']=$Pro9->Name;
                    $move['P_En_Name']=$Pro9->Name;
                    $move['P_Code']=$Pro9->Barcode;
                    $move['Unit']=$Pro9->Unit;
                    $move['QTY']=$Pro9->Qty;
                    $move['Group']=$prooooo->Group;
                    $move['Store']=$Pro9->Store;
                    $move['Product']=$ID;
                    $move['V1']=null;
                    $move['V2']=null;
                    $move['User']=1;
                    $Sro=Stores::find($Pro9->Store);

                    $move['Brand']=$prooooo->Brand;
                    $move['Safe']=null;
                    $move['Branch']=$Sro->Branch;
                    $move['SalePrice']=null;
                    $move['ProductPrice']=null;
                    ProductMoves::create($move);

                    $id_store = DB::table('products_stores')->insertGetId(

                        array(

                            'P_Ar_Name' => $Pro9->Name,
                            'P_En_Name' => $Pro9->Name,
                            'P_Code' => $Pro9->Barcode,
                            'Exp_Date' => null,
                            'Product' => $ID,
                            'Store' =>$Pro9->Store,
                            'V1' => null,
                            'V2' => null,
                            'V_Name' => null,
                            'VV_Name' => null,

                        )
                    );



                    $pqty['P_Ar_Name']=$Pro9->Name;
                    $pqty['Price_Sale']=$Pro9->Price;
                    $pqty['P_En_Name']=$Pro9->Name;
                    $pqty['Qty']=$Pro9->Qty * $pp->Rate;
                    $pqty['Price']=$Pro9->Price;
                    $pqty['TotalCost']=$Pro9->Price;
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$Pro9->Store;
                    $pqty['Unit']=$Pro9->Unit;
                    $pqty['Exp_Date']=null;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$ID;
                    $pqty['Patch_Number']=null;
                    $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;
                    $pqty['P_Code']=$Pro9->Barcode;
                    $pqty['PP_Code']=null;
                    $pqty['PPP_Code']=null;
                    $pqty['PPPP_Code']=null;
                    ProductsQty::create($pqty);






                }

                if(!empty($Pro10)){

                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();
                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();



                    $uu['P_Code']=$Pro10->Barcode;
                    $uu['SmallCode']=$plow->Barcode;
                    $uu['Qty']=$Pro10->Qty;
                    $uu['SmallQty']=$Pro10->Qty * $pp->Rate;
                    $uu['Price']=$Pro10->CostPrice;
                    $uu['Total']=$Pro10->Total;
                    $uu['Old_Qty']=$Pro10->Qty;
                    $uu['Exp_Date']=null;
                    $uu['SP_ID']=$IDD;
                    $uu['Date']=date('Y-m-d');
                    $uu['Store']=$Pro10->Store;
                    $uu['User']=1;
                    $uu['Unit']=$Pro10->Unit;
                    $uu['P_Ar_Name']=$Pro10->Name;
                    $uu['P_En_Name']=$Pro10->Name;
                    $uu['V_Name']=null;
                    $uu['VV_Name']=null;
                    $uu['Product']=$ID;
                    $uu['Patch_Number']=null;
                    $uu['V1']=null;
                    $uu['V2']=null;

                    ProductsStartPeriods::create($uu);


                    $prooooo=Products::find($ID);

                    $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();
                    $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();

                    $purchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro10->Store)->get()->sum('Total_Bf_Tax');
                    $countPurchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro10->Store)->get()->sum('SmallQty');

                    $purchsStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro10->Store)->get()->sum('Total');

                    $countStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$Pro10->Store)->get()->sum('SmallQty');
                    $storesTransfer=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro10->Store)->get()->sum('Total');

                    $storesTransferCount=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$Pro10->Store)->get()->sum('SmallTrans_Qty');


                    $OUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro10->Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');

                    $countOUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$Pro10->Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');


                    $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME;
                    $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

                    if($CollectCount != 0){
                        $ty= $Collect / $CollectCount ;
                    }else{

                        $ty= $Collect;
                    }



                    $in=($Pro10->Qty * $pp->Rate) * $ty ;
                    $out=0 ;
                    $current=($Pro10->Qty * $pp->Rate) * $ty ;

                    $RR=StartPeriods::find($IDD);
                    $move['Date']=date('Y-m-d');
                    $move['Type']='بدايه فتره';
                    $move['Bill_Num']=$RR->Code;
                    $move['Incom']=$Pro10->Qty * $pp->Rate;
                    $move['Outcom']=0;
                    $move['Current']=$Pro10->Qty * $pp->Rate;
                    $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                    $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                    $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                    $move['P_Ar_Name']=$Pro10->Name;
                    $move['P_En_Name']=$Pro10->Name;
                    $move['P_Code']=$Pro10->Barcode;
                    $move['Unit']=$Pro10->Unit;
                    $move['QTY']=$Pro10->Qty;
                    $move['Group']=$prooooo->Group;
                    $move['Store']=$Pro10->Store;
                    $move['Product']=$ID;
                    $move['V1']=null;
                    $move['V2']=null;
                    $move['User']=1;
                    $Sro=Stores::find($Pro10->Store);

                    $move['Brand']=$prooooo->Brand;
                    $move['Safe']=null;
                    $move['Branch']=$Sro->Branch;
                    $move['SalePrice']=null;
                    $move['ProductPrice']=null;
                    ProductMoves::create($move);

                    $id_store = DB::table('products_stores')->insertGetId(

                        array(

                            'P_Ar_Name' => $Pro10->Name,
                            'P_En_Name' => $Pro10->Name,
                            'P_Code' => $Pro10->Barcode,
                            'Exp_Date' => null,
                            'Product' => $ID,
                            'Store' =>$Pro10->Store,
                            'V1' => null,
                            'V2' => null,
                            'V_Name' => null,
                            'VV_Name' => null,

                        )
                    );



                    $pqty['P_Ar_Name']=$Pro10->Name;
                    $pqty['Price_Sale']=$Pro10->Price;
                    $pqty['P_En_Name']=$Pro10->Name;
                    $pqty['Qty']=$Pro10->Qty * $pp->Rate;
                    $pqty['Price']=$Pro10->Price;
                    $pqty['TotalCost']=$Pro10->Price;
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$Pro10->Store;
                    $pqty['Unit']=$Pro10->Unit;
                    $pqty['Exp_Date']=null;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$ID;
                    $pqty['Patch_Number']=null;
                    $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;
                    $pqty['P_Code']=$Pro10->Barcode;
                    $pqty['PP_Code']=null;
                    $pqty['PPP_Code']=null;
                    $pqty['PPPP_Code']=null;
                    ProductsQty::create($pqty);






                }

                $move['Date']=date('Y-m-d');
                $move['Type']='رصيد سابق';
                $move['Bill_Num']=0;
                $move['Incom']=0;
                $move['Outcom']=0;
                $move['Current']=0;
                $move['CostIn']=0;
                $move['CostOut']=0;
                $move['CostCurrent']=0;
                $move['P_Ar_Name']=$pro->Name;
                $move['P_En_Name']=$pro->Name;
                $move['P_Code']=null;
                $move['Unit']=null;
                $move['Group']=$pro->Group;
                $move['Store']=null;
                $move['Product']=$ID;
                $move['V1']=null;
                $move['V2']=null;
                $move['User']=1;
                $move['Brand']=$pro->Brand;
                $move['Safe']=null;
                $move['Branch']=null;
                $move['SalePrice']=null;
                $move['ProductPrice']=null;
                ProductMoves::create($move);

                //Start Period

                $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();
                $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();



                $uu['P_Code']=$pro->Barcode;
                $uu['SmallCode']=$plow->Barcode;
                $uu['Qty']=$pro->Qty;
                $uu['SmallQty']=$pro->Qty * $pp->Rate;
                $uu['Price']=$pro->CostPrice;
                $uu['Total']=$pro->Total;
                $uu['Old_Qty']=$pro->Qty;
                $uu['Exp_Date']=null;
                $uu['SP_ID']=$IDD;
                $uu['Date']=date('Y-m-d');
                $uu['Store']=$pro->Store;
                $uu['User']=1;
                $uu['Unit']=$pro->Unit;
                $uu['P_Ar_Name']=$pro->Name;
                $uu['P_En_Name']=$pro->Name;
                $uu['V_Name']=null;
                $uu['VV_Name']=null;
                $uu['Product']=$ID;
                $uu['Patch_Number']=null;
                $uu['V1']=null;
                $uu['V2']=null;

                ProductsStartPeriods::create($uu);


                $prooooo=Products::find($ID);

                $plow=ProductUnits::where('Product',$ID)->where('Rate',1)->first();
                $pp=ProductUnits::where('Product',$ID)->where('Unit',$pro->Unit)->first();

                $purchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$pro->Store)->get()->sum('Total_Bf_Tax');
                $countPurchs=ProductsPurchases::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$pro->Store)->get()->sum('SmallQty');

                $purchsStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$pro->Store)->get()->sum('Total');

                $countStart=ProductsStartPeriods::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('Store',$pro->Store)->get()->sum('SmallQty');
                $storesTransfer=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$pro->Store)->get()->sum('Total');

                $storesTransferCount=ProductsStoresTransfers::where('Product',$ID)->where('SmallCode',$plow->Barcode)->where('To_Store',$pro->Store)->get()->sum('SmallTrans_Qty');


                $OUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$pro->Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');

                $countOUTCOME=OutcomManufacturingModel::where('Product',$ID)->where('Store',$pro->Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');


                $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME;
                $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

                if($CollectCount != 0){
                    $ty= $Collect / $CollectCount ;
                }else{

                    $ty= $Collect;
                }



                $in=($pro->Qty * $pp->Rate) * $ty ;
                $out=0 ;
                $current=($pro->Qty * $pp->Rate) * $ty ;

                $RR=StartPeriods::find($IDD);
                $move['Date']=date('Y-m-d');
                $move['Type']='بدايه فتره';
                $move['Bill_Num']=$RR->Code;
                $move['Incom']=$pro->Qty * $pp->Rate;
                $move['Outcom']=0;
                $move['Current']=$pro->Qty * $pp->Rate;
                $move['CostIn']=number_format((float)abs($in), 2, '.', '');
                $move['CostOut']=number_format((float)abs($out), 2, '.', '');
                $move['CostCurrent']=number_format((float)abs($current), 2, '.', '');
                $move['P_Ar_Name']=$pro->Name;
                $move['P_En_Name']=$pro->Name;
                $move['P_Code']=$pro->Barcode;
                $move['Unit']=$pro->Unit;
                $move['QTY']=$pro->Qty;
                $move['Group']=$prooooo->Group;
                $move['Store']=$pro->Store;
                $move['Product']=$ID;
                $move['V1']=null;
                $move['V2']=null;
                $move['User']=1;
                $Sro=Stores::find($pro->Store);

                $move['Brand']=$prooooo->Brand;
                $move['Safe']=null;
                $move['Branch']=$Sro->Branch;
                $move['SalePrice']=null;
                $move['ProductPrice']=null;
                ProductMoves::create($move);

                $id_store = DB::table('products_stores')->insertGetId(

                    array(

                        'P_Ar_Name' => $pro->Name,
                        'P_En_Name' => $pro->Name,
                        'P_Code' => $pro->Barcode,
                        'Exp_Date' => null,
                        'Product' => $ID,
                        'Store' =>$pro->Store,
                        'V1' => null,
                        'V2' => null,
                        'V_Name' => null,
                        'VV_Name' => null,

                    )
                );



                $pqty['P_Ar_Name']=$pro->Name;
                $pqty['Price_Sale']=$pro->Price;
                $pqty['P_En_Name']=$pro->Name;
                $pqty['Qty']=$pro->Qty * $pp->Rate;
                $pqty['Price']=$pro->Price;
                $pqty['TotalCost']=$pro->Price;
                $pqty['Pro_Stores']=$id_store;
                $pqty['Store']=$pro->Store;
                $pqty['Unit']=$pro->Unit;
                $pqty['Exp_Date']=null;
                $pqty['Low_Unit']=$plow->Unit;
                $pqty['Product']=$ID;
                $pqty['Patch_Number']=null;
                $pqty['V1']=null;
                $pqty['V2']=null;
                $pqty['V_Name']=null;
                $pqty['VV_Name']=null;
                $pqty['P_Code']=$pro->Barcode;
                $pqty['PP_Code']=null;
                $pqty['PPP_Code']=null;
                $pqty['PPPP_Code']=null;
                ProductsQty::create($pqty);


            }
            $RR=StartPeriods::find($IDD);

            $res=Journalizing::orderBy('id','desc')->first();

            if(!empty($res->Code)){

                $Code=$res->Code + 1 ;
            }else{
                $Code=1;

            }

            $JunID = DB::table('journalizings')->insertGetId(

                array(

                    'Code' => $Code,
                    'Type' => trans('admin.Start_Period_Products'),
                    'Code_Type' => $RR->Code,
                    'Date' => date('Y-m-d'),
                    'Draw' => 1,
                    'Coin' => $Def->Coin,
                    'Cost_Center' => null,
                    'Total_Debaitor' => $TOT,
                    'Total_Creditor' => $TOT,
                    'Note' => null,

                )
            );


            $store=Stores::find($last->Store);

            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=$TOT;
            $PRODUCTSS['Creditor']=0;
            $PRODUCTSS['Account']=$store->Account;
            $PRODUCTSS['Statement']=null;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$RR->Code;
            $Gen['Date']=date('Y-m-d');
            $Gen['Type']=trans('admin.Start_Period_Products');
            $Gen['Debitor']=$TOT;
            $Gen['Creditor']=0;
            $Gen['Statement']=null;
            $Gen['Draw']=1;
            $Gen['Debitor_Coin']= 1 * $TOT;
            $Gen['Creditor_Coin']=1 * 0;
            $Gen['Account']=$store->Account;
            $Gen['Coin']= $Def->Coin;
            $Gen['Cost_Center']=null;
            $Gen['userr']= 1;

            GeneralDaily::create($Gen);


            $PRODUCTSS['Joun_ID']=$JunID;
            $PRODUCTSS['Debitor']=0;
            $PRODUCTSS['Creditor']=$TOT;
            $PRODUCTSS['Account']=45;
            $PRODUCTSS['Statement']=null;


            JournalizingDetails::create($PRODUCTSS);

            $Gen['Code']=$Code;
            $Gen['Code_Type']=$RR->Code;
            $Gen['Date']=date('Y-m-d');
            $Gen['Type']=trans('admin.Start_Period_Products');
            $Gen['Debitor']=0;
            $Gen['Creditor']=$TOT;
            $Gen['Statement']=null;
            $Gen['Draw']=1;
            $Gen['Debitor_Coin']= 1 * 0;
            $Gen['Creditor_Coin']=1 * $TOT;
            $Gen['Account']=45;
            $Gen['Coin']= $Def->Coin;
            $Gen['Cost_Center']= null;
            $Gen['userr']= 1;

            GeneralDaily::create($Gen);


            DB::commit();

            session()->flash('success',trans('admin.Added_Successfully'));
            return back();

        }catch(\Exception $ex){


            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }catch(\Error $ex){



            DB::rollBack();
            Log::channel('custom')->error(' Message => '. $ex->getMessage() ." Line => ".$ex->getLine() . "\n");

            session()->flash('error',trans('admin.There_is_Something_Wrong_Happen'));
            return back();

        }



    }



    //=============================================================================================================================================================================




}
