<?php

    use App\Fun\Fun;
    use App\Model\account\AccountChartModel;
use App\Model\account\JournalModel;
use App\Model\CurrencyModel;
    use App\Model\payment\PaymentDetailModel;
    use App\Model\people\CustomerModel;
    use App\Model\people\DriverModel;
    use App\Model\people\SupplierModel;
    use App\Model\people\TailorModel;
    use App\Model\pos\SaleDetailsModel;
    use App\Model\pos\SaleModel;
    use App\Model\product\BrandModel;
    use App\Model\product\CategoryModel;
    use App\Model\product\ColorModel;
    use App\Model\product\ProductImageModel;
    use App\Model\product\ProductModel;
    use App\Model\product\ProductUnitModel;
    use App\Model\product\SizeModel;
    use App\Model\product\UnitModel;
    use App\Model\production\cutting\CuttingDetailModel;
    use App\Model\purchase_order\PurchaseOrderDetailModel;
    use App\Model\purchase_order\PurchaseOrderModel;
    use App\Model\setup\BranchModel;
    use App\Model\setup\MemberModel;
    use App\Model\setup\MemberTypeModel;
    use App\Model\setup\SupplierTypeModel;
    use App\Model\setup\WarehouseModel;
    use App\Model\stock_inventory\PurchaseDetailsModel;
    use App\Model\stock_inventory\PurchaseModel;
    use App\Model\stock_inventory\StockModel;
    use App\User;
    use Illuminate\Support\Facades\Auth;
    use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

function if_kh()
    {
        return (app()->getLocale() == 'km');
    }

// get total amount from sale_id
    function total_amount($id)
    {
        return $total = DB::table('nso007_sale_details')->where('sale_id', $id)
            ->select(DB::raw('SUM(sale_price - (sale_price*dis/100)) as total_sales'))
            ->first()->total_sales;
    }

    function warehouse()
    {
        return WarehouseModel::where('status', 1)->get()
            ->pluck('full_name', 'id');
    }

    function findWarehouse($id)
    {
        return WarehouseModel::find($id);
    }

    function findDriver($id)
    {
        return DriverModel::find($id);
    }

    function getSellerType()
    {
        $type = ['in_shop' => __('administrator.in_shop'), 'out_shop' => __('administrator.out_shop')];
        return $type;
    }

    function getCurrency()
    {
        return CurrencyModel::pluck('name', 'id');
    }

    function getRate($code = '')
    {
        $rate = CurrencyModel::where(function ($q) use ($code) {
            $q->where('id', 1);
        })->first();
        return $rate ? $rate->rate : 0;
    }

    function findCustomer($id)
    {
        return CustomerModel::find($id);
    }

    function findBranch($id)
    {
        return BranchModel::find($id);
    }

    function ImagesBase64($image)
    {
        if ($image && $image->getClientOriginalExtension() == 'svg') {
            $data = 'data:image/svg+xml;base64,' . base64_encode(file_get_contents($image));
        } elseif ($image && $image->getClientOriginalExtension() == 'png') {
            $data = 'data:image/png;base64,' . base64_encode(file_get_contents($image));
        } elseif ($image && $image->getClientOriginalExtension() == 'jpg') {
            $data = 'data:image/jpeg;base64,' . base64_encode(file_get_contents($image));
        } elseif ($image && $image->getClientOriginalExtension() == 'jpeg') {
            $data = 'data:image/jpeg;base64,' . base64_encode(file_get_contents($image));
        }
        return @$data;
    }

    function findDiscount($id)
    {
        return DiscountModel::find($id);
    }

    function getDiscount()
    {
        return DiscountModel::pluck('name', 'id');
    }

    function getCustomerNoDiscount()
    {
        $dis = CustomerDiscountModel::pluck('customer_id');
        $customer = CustomerModel::whereNotin('id', $dis)->where('branch_id', Auth::user()->branch_id)->pluck('customer_name', 'id');
        return $customer;
    }

    function getMainWarehouse($type = '')
    {
        $branch_id = Auth::user()->user_type == 'seller' ? 'arigato' : Auth::user()->branch_id;
        $wh = WarehouseModel::where('branch_id', $branch_id)->count();
        $wh = WarehouseModel::where(function ($q) use ($branch_id, $wh) {
            if ($wh > 1) {
                $q->where('main', 1);
            }
        })
            ->where('branch_id', $branch_id)
            ->where(function ($q) use ($type) {
                if ($type) {
                    $q->where('warehouse_type', $type);
                }
            })
            ->first();
        return $wh;
    }

    function findImg($img)
    {
        $file = asset($img);
        if (file_exists($img)) {
            return $file;
        }
        return asset('images/default.jpg');
    }

    function helper_getProQty($id, $unit, $qty)
    { // normal item
        $sale_qty = $qty;
        $stock = StockModel::where(['product_id' => $id, 'warehouse_id' => getMainWarehouse()->id])->first();
        $child_unit = ProductUnitModel::where(['product_id' => $id, 'type' => 'child'])->first();
        $product_unit = ProductUnitModel::where(['product_id' => $id, 'unit_id' => $unit])->first();
        if ($product_unit->type == 'parent') {
            $stock_qty = $child_unit != null ? ($stock->stock_qty / $child_unit->qty_per_unit) : $stock->stock_qty;
            $stock_qty = intval($stock_qty);
        } else {
            $stock_qty = $stock->stock_qty;
        }
        if ($sale_qty > $stock_qty) {
            $sale_qty = $stock_qty > 0 ? $stock_qty : 0;
        }
        return $sale_qty;
    }

    function get_clothes_balance($product_id, $qty, $size, $color)
    { // clothes
        $sale_qty = $qty;
        $stock = StockModel::where([
            'product_id' => $product_id,
            'size_code' => $size,
            'color_code' => $color,
            'warehouse_id' => getMainWarehouse()->id
        ])->first();
        if ($stock) {
            if ($stock->stock_qty < $sale_qty) {
                $sale_qty = $stock->stock_qty;
            }
        }
        return $sale_qty;
    }

    function getProductById($id)
    {
        return ProductModel::find($id);
    }

    function generate_inv($tb, $pre)
    {
        $cur_year = date('Y');
        $count = DB::table($tb)->where('year', date('Y'))->count();
        if ($count) {
            $dd =  $pre . $cur_year . sprintf('%02d', Auth::user()->id) . '' . sprintf('%06d', ($count + 1));
        }else{
            $dd =  $pre . $cur_year . sprintf('%02d', Auth::user()->id) . '000001';
        }
        return $dd;
    }

    function getSaleDetail($sale_id)
    {
        return SaleDetailsModel::where('sale_id', $sale_id)->get();
    }

    function findSale($sale_id)
    {
        return SaleModel::find($sale_id);
    }

    function findUnit($id)
    {
        return UnitModel::find($id);
    }

    function findCurrency($id)
    {
        return CurrencyModel::find($id);
    }

    function findPurchase($purchase_id)
    {
        return PurchaseModel::find($purchase_id);
    }

    function getBranch()
    {
        if (Auth::user()->branch_id) {
            $br = BranchModel::find(Auth::user()->branch_id);
        } else {
            $br = BranchModel::where('main', 1)->first();
        }

        return $br;
    }

    function getMainBranch()
    {
        return BranchModel::where('main', 1)->first();
    }

    function getBranches()
    {
        $check = BranchModel::where('main', 1)->where('id', Auth::user()->branch_id)->first();
        if ($check) {
            $br = BranchModel::pluck('name', 'id');
        } else {
            $br = BranchModel::where('id', Auth::user()->branch_id)->first();
        }

        return $br;
    }

    function findUser($id)
    {
        return User::find($id);
    }

    function findProductCurrency($product_id)
    {
        $product = getProductById($product_id);
        if ($product->currency == '1') {
            $currency = '៛';
        } else if ($product->currency == '2') {
            $currency = '$';
        } else {
            $currency = '฿';
        }
        return $currency;
    }


    function getPurchaseOrderDetail($po_id)
    {
        return PurchaseOrderDetailModel::where('purchase_id', $po_id)->get();
    }


// sale Table
    function generateTotal($detail)
    { // sale Detail
        if ($detail->status == 1) {
            $total = $detail->sale_price * $detail->qty;
            $total = $total - ($total * $detail->dis / 100);
            return $total;
        }
        return 0;
    }

    function generateSubTotal($sale)
    {
        $total = 0;
        $saledetail = getSaleDetail($sale->id);
        foreach ($saledetail as $key => $value) {
            $total += generateTotal($value);
        }

        return $total;
    }

    function generateGrandTotal($sale)
    {
        $subtotal = generateSubTotal($sale);
        if ($sale->delivery_fee_by == 2) {
            $delivery_fee = $sale->delivery_fee;
            $subtotal += ($delivery_fee);
        }
        $refund_amount = $sale->refund_amount;
        $subtotal += $refund_amount;
        return $subtotal - $sale->discount;
    }

//purchase order
    function generatePOTotal($detail)
    {
        $product = getProductById($detail->product_id);
        $total = $detail->sale_price * $detail->qty;
        $total = $total - ($total * $detail->dis / 100);
        if ($product->currency == '1') {
            $currency = '៛';
        } else if ($product->currency == '2') {
            $currency = '$';
        } else {
            $currency = '฿';
        }
        return $currency . $total;
    }

    function generatePOSubTotal($sale)
    {
        $total_kh = 0;
        $total_usd = 0;
        $total_baht = 0;
        $detail = getPurchaseOrderDetail($sale->id);
        foreach ($detail as $key => $value) {
            $currency = findCurrency(getProductById($value->product_id)->currency)->symbol;
            if ($currency == '$') {
                $total = generatePOTotal($value);
                $total = str_replace('$', '', $total);
                $total_usd += $total;
            } else if ($currency == '៛') {
                $total = generatePOTotal($value);
                $total = str_replace('៛', '', $total);
                $total_kh += $total;
            } else {
                $total = generatePOTotal($value);
                $total = str_replace('฿', '', $total);
                $total_baht += $total;
            }
        }
        $g_total = ($total_kh > 0 ? ($total_kh / $sale->rate) : 0) + $total_usd + ($total_baht > 0 ? ($total_baht / $sale->rate_baht) : 0);
        return $g_total;
    }

    function generatePOGrandTotal($sale)
    {
        $subtotal = generatePOSubTotal($sale);
        return $subtotal - ($subtotal * $sale->discount) / 100;
    }

//purchase

    function getPurchaseTotal($purchase)
    {
        $g_total = 0;
        $purchase_details = PurchaseDetailsModel::where('purchase_id', $purchase->id)->get();
        foreach ($purchase_details as $key => $value) {
            $amount = $value->qty * $value->cost;
            $total = $amount - ($value->dis * $amount / 100);
            $g_total += $total;
        }
        return $g_total;
    }


    function generatePurchaseGrandTotal($purchase)
    {
        $subtotal = getPurchaseTotal($purchase);
        return $subtotal - ($subtotal * $purchase->discount) / 100;
    }

    function generatePaymentRefund($payment_id)
    {
        $p_detail = PaymentDetailModel::where(['payment_id' => $payment_id, 'type' => 'refund'])->get();
        $total = 0;
        foreach ($p_detail as $row) {
            $total += $row->paid_amount;
        }
        return $total;
    }

    function getCustomerByParent()
    {
        return CustomerModel::where('agent_id', Auth::user()->id)->where('status', 1)->get();
    }

    function getPaymentStatus($key = '')
    {
        Fun::lang();
        $payment = ['due' => __('administrator.due'), 'partial' => __('administrator.partial'), 'paid' => __('administrator.paid')];
        if ($key) {
            return $payment[$key];
        }
        return $payment;
    }

    function getRequestStatus()
    {
        Fun::lang();
        return ['0' => __('administrator.pending'), '1' => __('administrator.approve'), '2' => __('administrator.reject')];
    }

    function getSupplier($item_or_material = null, $array = null)
    {
        return SupplierModel::where(function ($q) use ($item_or_material) {
            if ($item_or_material) {
                $q->where('type', $item_or_material);
            }
        })
            ->where(function ($q) use ($array) {

                if (($array)) {
                    if (count($array) > 0) {
                        $q->whereIn('id', $array);
                    }
                }
            })
            ->get();
    }

    function findSupplier($id)
    {
        return SupplierModel::find($id);
    }

    function findSupplierType($id)
    {
        $sup = SupplierModel::find($id);
        return SupplierTypeModel::where('id', $sup->supplier_type_id)->first();
    }

    function LogoImage()
    {
        return asset('images/logo.jpg');
    }

    function BgImage()
    {
        return asset('images/bg.jpg');
    }

    function headerlogo()
    {
        return asset('images/header.jpg');
    }

    function findTarget($id)
    {
        return TargetNestbirdModel::find($id);
    }

    function pluckAllUser($condition = null)
    {
        Fun::lang();
        $user = StaffTargetModel::pluck('staff_id');
        $all = User::selectRaw('	CONCAT(name,(CASE
WHEN is_role = "in_shop" THEN
	" (' . __('administrator.in_shop') . ')"
WHEN is_role = "out_shop" THEN
	" (' . __('administrator.out_shop') . ')"
WHEN is_role = "coporator" THEN
	" (' . __('administrator.coporator') . ')"
ELSE
	" (' . __('administrator.user') . ')"
END)) as user_name,id')
            ->where(function ($q) use ($condition, $user) {
                if ($condition) {
                    $q->whereNotIn('id', $user);
                }
            })
            ->where('status', 1)
            ->pluck('user_name', 'id');
        return $all;
    }

    function pluckStaffTarget($if_want_current_user_insert_anything = null)
    {
        Fun::lang();
        $user = StaffTargetModel::pluck('staff_id');
        $id = Auth::user()->id;
        $all = User::selectRaw('	CONCAT(name,(CASE
WHEN is_role = "in_shop" THEN
	" (' . __('administrator.in_shop') . ')"
WHEN is_role = "out_shop" THEN
	" (' . __('administrator.out_shop') . ')"
WHEN is_role = "coporator" THEN
	" (' . __('administrator.coporator') . ')"
ELSE
	" (' . __('administrator.user') . ')"
END)) as user_name,id')
            ->where(function ($q) use ($if_want_current_user_insert_anything, $user, $id) {
                if ($if_want_current_user_insert_anything) {
                    $q->where('id', $id);
                } else {
                    $q->whereIn('id', $user);
                }
            })
            ->where('status', 1)
            ->pluck('user_name', 'id');
        return $all;
    }

    function getAllTarget()
    {
        return TargetNestbirdModel::pluck('name', 'id');
    }

    function pluckAllCustomer()
    {
        return CustomerModel::where('status', 1)->pluck('customer_name', 'id');
    }

    function getAllProduct()
    {
        return ProductModel::where('status', 1)->get();
    }

    function generateTargetCommission($month, $year, $user_id, $target_id)
    {
        $from = $year . '-' . $month . '-' . '01';
        $to = $year . '-' . $month . '-' . date('t', strtotime($from));
        $earn_amount = getStaffEarnAmountByDate($user_id, $from, $to);
        $user_target = TargetNestbirdModel::find($target_id);
        $commission = 0;
        if ($user_target != null) {
            $val1 = $user_target->target1;
            $val2 = $user_target->target2;
            $val3 = $user_target->target3;
            $val4 = $user_target->target4;
            $val5 = $user_target->target5;
            if ($earn_amount > $val1 && ($val2 > 0 ? ($earn_amount <= $val2) : (1 == 1))) {
                $commission = $user_target->commission1;
            }
            if ($val2 > 0 || $val2 != null) {
                if ($earn_amount > $val2 && ($val3 > 0 ? ($earn_amount <= $val3) : (1 == 1))) {
                    $commission = $user_target->commission2;
                }
            }
            if ($val3 > 0 || $val3 != null) {
                if ($earn_amount > $val3 && ($val4 > 0 ? ($earn_amount <= $val4) : (1 == 1))) {
                    $commission = $user_target->commission3;
                }
            }
            if ($val4 > 0 || $val4 != null) {
                if ($earn_amount > $val4 && ($user_target->gval5 > 0 ? ($earn_amount <= $user_target->gval5) : (1 == 1))) {
                    $commission = $user_target->commission4;
                }
            }
            if ($val5 > 0 || $val5 != null) {
                if ($earn_amount > $val5) {
                    $commission = $user_target->commission5;
                }
            }
        }
        return $commission;
    }

    function getStaffEarnAmountByDate($user_id, $from, $to)
    {
        $sale = SaleModel::where(['user_id' => $user_id, 'status' => 1])
            ->whereBetween('nso007_sales.sale_date', [$from, $to])
            ->get();
        $earn_amount = 0;
        foreach ($sale as $row) {
            $earn_amount += generateGrandTotal($row);
        }
        return $earn_amount;
    }

    function getAllMonth()
    {
        Fun::lang();
        $month = array(
            '01' => __('administrator.January'),
            '02' => __('administrator.February'),
            '03' => __('administrator.March'),
            '04' => __('administrator.April'),
            '05' => __('administrator.May'),
            '06' => __('administrator.June'),
            '07' => __('administrator.July'),
            '08' => __('administrator.August'),
            '09' => __('administrator.September'),
            '10' => __('administrator.October'),
            '11' => __('administrator.November'),
            '12' => __('administrator.December'),
        );
        return $month;
    }

    function findParentProductUnit($product_id)
    {
        return ProductUnitModel::where('product_id', $product_id)->where('type', 'parent')->first();
    }

    function findChildProductUnit($product_id)
    {
        return ProductUnitModel::where('product_id', $product_id)->where('type', 'child')->where('qty_per_unit', '>', 1)->first();
    }

    function findCategory($id)
    {
        return CategoryModel::find($id);
    }

    function findPurchaseOrder($id)
    {
        return PurchaseOrderModel::find($id);
    }

    function getAllSomeUser($if_normal_user_put_something = '')
    {
        $id = Auth::user()->id;
        $all = User::where(function ($q) use ($if_normal_user_put_something, $id) {
            if ($if_normal_user_put_something) {
                $q->where('id', $id);
            }
        })
            ->where('status', 1)
            ->pluck('name', 'id');
        return $all;
    }

    function generatePurchaseOrderCutQty($purchase_order_detail)
    {
        $child_unit = ProductUnitModel::where(['product_id' => $purchase_order_detail->product_id, 'type' => 'child'])->first();
        $product_unit = ProductUnitModel::where(['product_id' => $purchase_order_detail->product_id, 'unit_id' => $purchase_order_detail->unit_id])->first();
        if ($product_unit->type == 'parent') {
            // if buy unit is parent convert to child qty
            $cut_qty = ($child_unit != null ? ($purchase_order_detail->qty * $child_unit->qty_per_unit) : $purchase_order_detail->qty);
            $cut_qty = intval($cut_qty);
        } else {
            $cut_qty = $purchase_order_detail->qty;
        }
        return $cut_qty;
    }

    function generateSaleCutQty($saleDetail, $isMaterial = '')
    {
        $child_unit = ProductUnitModel::where(['product_id' => ($isMaterial ? $saleDetail->material_id : $saleDetail->product_id), 'type' => 'child'])->first();
        $product_unit = ProductUnitModel::where(['product_id' => ($isMaterial ? $saleDetail->material_id : $saleDetail->product_id), 'unit_id' => $saleDetail->unit_id])->first();
        if ($product_unit->type == 'parent') {
            // if buy unit is parent convert to child qty
            $cut_qty = ($child_unit != null ? ($saleDetail->qty * $child_unit->qty_per_unit) : $saleDetail->qty);
            $cut_qty = intval($cut_qty);
        } else {
            $cut_qty = $saleDetail->qty;
        }
        return $cut_qty;
    }

    function checkRequestStatus($status)
    {
        $status_ = '';
        Fun::lang();
        if (($status) == 0) {
            $status_ = '<span class="label label-warning">' . __('administrator.pending') . '</span>'; // request pending
        }
        if (($status) == 1) {
            $status_ = '<span class="label label-success">' . __('administrator.approve') . '</span>';
        }
        if (($status) == 2) {
            $status_ = '<span class="label label-danger">' . __('administrator.reject') . '</span>';
        }
        if (($status) == 3) {
            $status_ = '<span class="label label-danger">' . __('administrator.pending') . '</span>'; // return pending
        }
        if (($status) == 4) {
            $status_ = '<span class="label label-danger">' . __('administrator.return') . '</span>';
        }
        return $status_;
    }

    function deliveryChangeStatus($delivery_status)
    {
        $delivery_ = '';
        Fun::lang();
        if (($delivery_status) == 0) {
            $delivery_ = '<span class="label label-warning">' . __('administrator.pending') . '</span>';
        }
        if (($delivery_status) == 1) {
            $delivery_ = '<span class="label label-info">' . __('administrator.on_process') . '</span>';
        }
        if (($delivery_status) == 2) {
            $delivery_ = '<span class="label label-danger">' . __('administrator.reject') . '</span>';
        }
        if (($delivery_status) == 3) {
            $delivery_ = '<span class="label label-success">' . __('administrator.done') . '</span>';
        }
        if (($delivery_status) == 4) {
            $delivery_ = '<span class="label label-warning">' . __('administrator.return') . '</span>';
        }
        if (($delivery_status) == 5) {
            $delivery_ = '<span class="label label-danger">' . __('administrator.returned') . '</span>';
        }
        if (($delivery_status) == 6) {
            $delivery_ = '<span class="label label-danger">' . __('administrator.reject') . '</span>';
        }

        return $delivery_;
    }

    function checkPaymentStatusByAmount($total, $paid, $type = '')
    {
        if ($paid >= $total) {
            $payment_status = 'paid';
        } else {
            if ($paid > 0) {
                $payment_status = 'partial';
            } else {
                $payment_status = 'due';
            }
        }
        if ($type) {
            return checkPaymentStatus($payment_status);
        }
        return $payment_status;
    }

    function checkPaymentStatus($payment_status)
    {
        Fun::lang();
        $status = '';
        if (strtolower($payment_status) == 'due') {
            $status = '<span class="label label-danger">' . __('administrator.due') . '</span>';
        }
        if (strtolower($payment_status) == 'partial') {
            $status = '<span class="label label-warning">' . __('administrator.partial') . '</span>';
        }
        if (strtolower($payment_status) == 'paid') {
            $status = '<span class="label label-success">' . __('administrator.paid') . '</span>';
        }
        if (strtolower($payment_status) == 'return') {
            $status = '<span class="label label-danger">' . __('administrator.return') . '</span>';
        }
        if (strtolower($payment_status) == 'reject') {
            $status = '<span class="label label-danger">' . __('administrator.reject') . '</span>';
        }
        return $status;
    }

    function getUnit($product_or_material = '')
    {
        $unit = UnitModel::where(function ($q) use ($product_or_material) {
            if ($product_or_material) {
                $q->where('type', $product_or_material);
            }
        });
        return $unit;
    }

    function getCategory($product_or_material = '')
    {
        $category = CategoryModel::where(function ($q) use ($product_or_material) {
            if ($product_or_material) {
                $q->where('type', $product_or_material);
            }
        });
        return $category;
    }

    function getBrand()
    {
        return BrandModel::where('status', 1);
    }

    function getColor()
    {
        return ColorModel::where('status', 1);
    }

    function getSize()
    {
        return SizeModel::where('status', 1);
    }

    function findBrand($brand_id)
    {
        return BrandModel::find($brand_id);
    }

    function findColor($color_code)
    {
        return ColorModel::where('code', $color_code)->first();
    }

    function findSize($size_code)
    {
        return SizeModel::where('code', $size_code)->first();
    }

    function getItemType()
    {
        Fun::lang();
        return [
            'product' => __('administrator.items'),
            'material' => __('administrator.material'),
            'fabric' => __('administrator.fabric')
        ];
    }

    function getProduct($item_or_material = null)
    {
        $dd = ProductModel::where(function ($q) use ($item_or_material) {
            if ($item_or_material) {
                $q->where('type', $item_or_material);
            }
        });
        return $dd;
    }

    function getProductItem()
    {
        return ProductModel::where('type', 'product')
            ->where('status', 1);
    }

    function getTailor($ifExternal = '')
    {
        return TailorModel::where(function ($q) use ($ifExternal) {
            if ($ifExternal) {
                $q->where('type', $ifExternal);
            }
        });
    }

    function findTailor($tailor_id)
    {
        return TailorModel::find($tailor_id);
    }

    function getWarehouse($type = '', $type1 = '')
    {
        return WarehouseModel::
        //        where('branch_id', Auth::user()->branch_id)
        where(function ($q) use ($type, $type1) {
            if ($type) {
                $q->where('warehouse_type', $type);
            }
            if ($type1) {
                $q->orwhere('warehouse_type', $type1);
            }
        })
            ->orderBy('main', 'DESC');
    }

    function profileImg()
    {
        return findImg(Auth::user()->photo);
    }

    function getWarehouseByBranch($selectAll = '', $type = 'item')
    {
        $branch = WarehouseModel::where(function ($q) use ($selectAll, $type) {
            if (!$selectAll) {
                $q->where('branch_id', Auth::user()->branch_id);
            }
            if ($type) {
                $q->where('warehouse_type', $type);
            }
        })->orderBy('warehouse_type', 'ASC')->get();
        return $branch;
    }

    function branchMenu()
    {
        $user = Auth::user();
        if ($user->user_type === 'seller') {
            return 'layouts.app-seller';
        } else {
            $branch = findBranch($user->branch_id);
            if ($branch->main == 1) {
                return 'layouts.app';
            } else {
                return 'layouts.app-branch';
            }
        }
    }

    function runSQL($query)
    {
        return DB::statement($query);
    }

    function getTable($query)
    {
        return collect(DB::select($query))->map(function ($x) {
            return (array)$x;
        })->toArray();
    }

    function getOneRow($sql)
    {
        $getTable = getTable($sql);
        if (count($getTable) > 0) {
            return $getTable[0];
        } else {
            return [];
        }
    }

    function getOne($sql)
    {
        $getOneRow = getOneRow($sql);
        if (count($getOneRow) > 0) {
            return reset($getOneRow);
        } else {
            return '';
        }
    }

// ===================FOR MATERIAL==============
    function findQtyPerUnit($product_id, $unit_id)
    {
        $punit = ProductUnitModel::where('product_id', $product_id)
            ->where('unit_id', $unit_id)
            ->first();
        $qty_per_unit = 1;
        if ($punit) {
            if ($punit->type == 'parent') {
                $child = ProductUnitModel::where('product_id', $product_id)
                    ->where('type', 'child')
                    ->where('qty_per_unit', '>', 1)
                    ->first();
                if ($child) {
                    $qty_per_unit = $child->qty_per_unit;
                }
            }
        }
        return $qty_per_unit;
    }

    function alert_outstock()
    {
        $balance = StockModel::get();
        $stock_alert = 0;
        $outof_stock = 0;
        $qty_alert = 0;
        foreach ($balance as $row) {
            $pro = getProductById($row->product_id);
            if ($pro) {
                $qty_alert = ($pro->qty_alert > 0 ? $pro->qty_alert : 0);
                if ($row->stock_qty <= $qty_alert && $row->stock_qty > 0) {
                    $stock_alert++;
                }
                if ($row->stock_qty == 0) {
                    $outof_stock++;
                }
            }
        }
        $obj = new stdClass();
        $obj->alert_stock = $qty_alert;
        $obj->outof_stock = $outof_stock;

        return $obj;
    }

    function convert_to_user_currency($product_id, $price)
    {  //for pos

        $my_p = getProductById($product_id);
        $rate_kh = getRate();
        $rate_baht = getRate(1);

        $user_currency = user_currency();

        if ($my_p->currency != $user_currency->id) {
            if ($my_p->currency == 1) {
                $price = $price / $rate_kh;
            }
            if ($my_p->currency == 3) {
                $price = $price / $rate_baht;
            }
            if ($user_currency->id == 1) {
                $price = $price * $rate_kh;
            }
            if ($user_currency->id == 3) {
                $price = $price * $rate_baht;
            }
        }

        return $price;
    }

    function convery_currency($sale_id, $price)
    {

        $sale = findSale($sale_id);
        $rate_baht = $sale->rate_baht;
        $user_currency = user_currency();
        if ($sale->currency_id != $user_currency->id) {
            if ($sale->currency_id == 3) {
                $price = $price / $rate_baht;
            }
            if ($user_currency->id == 3) {
                $price = $price * $rate_baht;
            }
        }
        return $price;
    }


    function convert_sale_detail_to_user_currency($detail)
    { //sale detail

        $rate_kh = findSale($detail->sale_id)->rate;
        $rate_baht = findSale($detail->sale_id)->rate_baht;
        $user_currency = user_currency();
        $price = $detail->sale_price;

        if ($detail->currency_id != $user_currency->id) {

            if ($detail->currency_id == 1) {
                $price = $price / $rate_kh;
            }

            if ($detail->currency_id == 3) {
                $price = $price / $rate_baht;
            }

            if ($user_currency->id == 1) {
                $price = $price * $rate_kh;
            }

            if ($user_currency->id == 3) {
                $price = $price * $rate_baht;
            }
        }
        return $price;
    }

    function findProductUnitByCode($barcode, $type = null)
    {

        $product_unit = ProductUnitModel::select('nso007_products.type as product_type', 'nso007_product_unit.*')
            ->join('nso007_products', 'nso007_products.id', 'nso007_product_unit.product_id')
            ->where(function ($q) use ($type) {
                if ($type) {
                    $q->where('nso007_products.type', $type);
                }
            })
            ->where('nso007_product_unit.barcode', $barcode)
            ->first();
        return $product_unit;
    }

    function user_currency()
    {
        $chh = null;
        $curr = Auth::user()->currency_id;
        $currency = findCurrency($curr);
        if (!$currency) {
            $currency = CurrencyModel::where('default', 1)->first();
        }
        return $currency;
    }

    function find_total_cutting_template($cutting_id)
    {
        return CuttingDetailModel::selectRaw('SUM(size_qty) as qty')->where('cutting_id', $cutting_id)->groupby('cutting_id')->first();
    }

    function generate_paid($sale)
    {
        $rate_kh = $sale->rate;
        $rate_baht = $sale->rate_baht;
        $paid = $sale->paid_amount;
        $user_currency = user_currency();
        $total = $paid;
        if ($user_currency->id == 1) {
            $total = $total * $rate_kh;
        }
        if ($user_currency->id == 3) {
            $total = $total * $rate_baht;
        }
        return $total;
    }

    function covert_delivery_fee($data)
    {
        $detail = SaleDetailsModel::where('sale_id', $data->id)->first();
        $fee = $data->delivery_fee;
        if ($fee) {
            if ($detail) {
                if ($detail->currency_id == 1) {
                    $fee = $fee / $data->rate;
                }
                if ($detail->currency_id == 3) {
                    $fee = $fee / $data->rate_baht;
                }
            }
            if (user_currency()->id == 1) {
                $fee = $data->rate * $fee;
            }
            if (user_currency()->id == 3) {
                $fee = $data->rate_baht * $fee;
            }
            return $fee;
        }
        return 0;
    }

    function convert_amount_to_user_amount($amount, $currency, $rate_kh, $rate_baht)
    {
        $user_currency = user_currency();
        if ($user_currency->id != $currency) {
            if ($amount) {
                if ($currency == 1) {
                    $amount = $amount / $rate_kh;
                }
                if ($currency == 3) {
                    $amount = $amount / $rate_baht;
                }

                if ($user_currency->id == 1) {
                    $amount = $amount * $rate_kh;
                }
                if ($user_currency->id == 3) {
                    $amount = $amount * $rate_baht;
                }
            }
        }
        return $amount;
    }


    function getPaymentMethod()
    {
        $payment_method = AccountChartModel::where('acctype', '11002')->orWhere('id', '11001')->orWhere('id', '11002')->pluck('acc_name', 'id');
        return $payment_method;
    }

    function getFeeBy($index = '')
    {
        Fun::lang();
        $fee_by = ['1' => __('administrator.shop_pay'), '2' => __('administrator.client_pay_shop'), '3' => __('administrator.client_pay_client')];
        if ($index) {
            return $fee_by[$index];
        } else {
            return $fee_by;
        }
    }

    function getWarehouseType($index = '')
    {
        $wh_type = [
            'item' => __('administrator.item_warehouse'),
            'material' => __('administrator.material_warehouse'),
            'fabric' => __('administrator.fabric_warehouse'),
            'cut_piece' => __('administrator.cut_piece_warehouse'),
            'tailor' => __('administrator.tailor_warehouse')
        ];
        if ($index) {
            return @$wh_type[$index];
        } else {
            return $wh_type;
        }
    }

    function generate_voucher_number($number_ref, $digit)
    {
        return str_pad($number_ref, $digit, "0", STR_PAD_LEFT);
    }

    function getVoucherType($key = '')
    {
        $type =
            [
                '1' => 'Cash Receipt',
                '2' => 'Cash Disbursement',
                '3' => 'Cash Reimbursement',
                '4' => 'Cash Advance',
                '5' => 'Advance Settlement',
                '6' => 'Journal Entry/Adjustment'
            ];
        if ($key) {
            return @$type[$key];
        }
        return $type;
    }

    function getTailorType($key = '')
    {
        $type =
            [
                'in' => __('administrator.internal'),
                'ex' => __('administrator.external'),
            ];
        if ($key) {
            return @$type[$key];
        }
        return $type;
    }

    function getStockData($product_id, $warehouse_id, $unit_id, $qty)
    { //material
        $stock = StockModel::where(['product_id' => $product_id, 'warehouse_id' => $warehouse_id, 'type' => 'material'])->first();
        $pro_unit = ProductUnitModel::where(['product_id' => $product_id, 'unit_id' => $unit_id])->first();
        $cut_qty = $qty * $pro_unit->qty_per_unit;
        return [$stock, $cut_qty];
    }

    function getStockSomeItem($warehouse_id, $barcode, $type)
    {
        return StockModel::where(['warehouse_id' => $warehouse_id, 'barcode' => $barcode, 'type' => $type])->first();
    }

    function check_stock_cut_piece($warehouse_id, $barcode, $tqty)
    {
        $stock = getStockSomeItem($warehouse_id, $barcode, 'cut_piece');
        $text = '';
        if ($stock) {
            if ($tqty > $stock->stock_qty) {
                $text = $barcode . ' មានចំនួនមិនគ្រប់គ្រាន់ !!';
            }
        } else {
            $text = $barcode . ' មិនមានក្នុងឃ្លាំង !!';
        }
        return $text;
    }

    function check_stock_material($warehouse_id, $product_id, $unit_id, $qty)
    {
        $get = getStockData($product_id, $warehouse_id, $unit_id, $qty);
        $product = getProductById($product_id);
        [$stock, $cut_qty] = $get;
        $arr = '';
        if ($stock) {
            if ($stock->stock_qty < $cut_qty) {
                $arr = $product->product_name . ' មិនមានគ្រប់ចនួន។';
            }
        } else {
            $arr = $product->product_name . ' មិនមានក្នុងឃ្លាំង។';
        }
        return $arr;
    }

    function cut_stock_material($warehouse_id, $product_id, $unit_id, $qty)
    {
        $get = getStockData($product_id, $warehouse_id, $unit_id, $qty);
        [$stock, $cut_qty] = $get;
        if ($stock) {
            $stock->stock_qty -= $cut_qty;
            $stock->save();
        }
        return 'cut';
    }

    function add_stock_material($warehouse_id, $product_id, $unit_id, $qty)
    {
        $get = (getStockData($product_id, $warehouse_id, $unit_id, $qty));
        $cut_qty = $get[1];
        $to_stock = StockModel::updateOrCreate(array(
            'warehouse_id' => $warehouse_id,
            'product_id' => $product_id,
            'type' => 'material',
        ));
        $to_stock->warehouse_id = $warehouse_id;
        $to_stock->product_id = $product_id;
        $to_stock->type = 'material';
        $to_stock->stock_qty += $cut_qty;
        $to_stock->save();
        return 'add';
    }

    function cut_stock_cut_piece($warehouse_id, $barcode, $qty)
    {
        $stock = getStockSomeItem($warehouse_id, $barcode, 'cut_piece');
        if ($stock) {
            $stock->stock_qty -= $qty;
            $stock->save();
        }
        return 'cut';
    }

    function checkProductExist($barcode, $type = null)
    {
        return ProductUnitModel::join('nso007_products', 'nso007_products.id', 'nso007_product_unit.product_id')
            ->where(['nso007_product_unit.barcode' => $barcode, 'nso007_products.type' => $type ?? 'product'])
            ->select('nso007_product_unit.product_id', 'nso007_product_unit.size_code', 'nso007_product_unit.color_code')
            ->first();
    }

    function add_stock_item($warehouse_id, $barcode, $qty, $type = null)
    {
        $product_unit = checkProductExist($barcode, $type);
        $stock = StockModel::UpdateOrCreate([
            'warehouse_id' => $warehouse_id,
            'barcode' => $barcode,
            'type' =>$type ?? 'product'
        ]);
        $stock->warehouse_id = $warehouse_id;
        $stock->barcode = $barcode;
        $stock->product_id = $product_unit->product_id;
        $stock->size_code = $product_unit->size_code;
        $stock->color_code = $product_unit->color_code;
        $stock->type = $type ?? 'product';
        $stock->stock_qty += $qty;
        $stock->save();
        return 'add';
    }

    function myBranch()
    {
        return BranchModel::find(Auth::user()->branch_id);
    }

    function myWarehouse($branch_id = 0)
    {
        $branch = $branch_id ? $branch_id : (myBranch()->id ?? 0);
        return WarehouseModel::where('branch_id', $branch)->orderBy('main', 'DESC')->first();
    }

    function mainBranch()
    {
        return BranchModel::where('main', 1)->first();
    }

    function getGender($key = null)
    {
        $data = ['male' => __('administrator.male'), 'female' => __('administrator.female')];
        if ($key) {
            return $data[$key];
        }
        return $data;
    }

function getProductPrice($pro_unit, $type, $member_type = null)
{
    $user_currency = user_currency();
    $price = 0;


    if ($type === 'rldf8e7sdf') {
        $member_package = MemberModel::where(['product_id' => $pro_unit->product_id, 'member_type' => $member_type])->first();
        if ($member_package) {
            $price = $user_currency->id == 2 ? $member_package->price_usd : $member_package->price_riel;
        } else {
            $price = $user_currency->id == 2 ? $pro_unit->price_usd : $pro_unit->price_riel;
        }
    }
    if ($type === 'purchase') {
        if ($user_currency->id == 2) {
            $price = $pro_unit->cost_usd;
        } else if ($user_currency->id == 1) {
            $price = $pro_unit->cost_riel;
        }
    }
    return $price;
}

function getMemberType()
{
    return MemberTypeModel::pluck('name', 'id');
}

function myDate($date, $time = 0)
{
    return date('d-m-Y' . ($time ? ' H:i:s' : ''), strtotime($date));
}

function sDate($date, $time = 0)
{
    return date('Y-m-d', strtotime($date)) . ($time ? date(' H:i:s') : '');
}

function findImgByCode($barcode)
{
    $img = ProductImageModel::where('item_code', $barcode)->first();
    return findImg($img->images ?? '');
}


function getDealResult($key = null)
{
    $status = [
        '1' => __('administrator.success'),
        '3' => 'Grade A (Above 50%)',
        '4' => 'Grade B (Below 50%)'
    ];

    if ($key) {
        return $status[$key];
    }
    return $status;
}

function bgDealStatus($key)
{
    switch ($key) {
        case 0:
        case 5:
            $color = 'warning';
            break;
        case 1:
            $color = 'success';
            break;
        case 2:
        case 3:
        case 4:
            $color = 'danger';
            break;
        default:
            $color = 'warning';
    }

    return '<span class="label label-' . $color . '">' . getDealResult($key) . '</span>';
}

function leadSource($key = '')
{
    $data = \DB::table('nso007_crm_lead_source')->pluck('source_name', 'id');
    if ($key) {
        return $data[$key];
    }
    return $data;
}

function getOutCome()
{
    return [
        'Interest' => __('administrator.interest'),
        'Not Interest' => __('administrator.not_interest'),
        'Not Response' => __('administrator.no_response'),
        'Requested more Information' => __('administrator.request_more_info'),
        'Next Time' => __('administrator.next_time'),
    ];
}

function getTaskType($key = '')
{
    Fun::lang();
    $task = ['meeting' => __('administrator.meeting_log'), 'appointment' => __('administrator.appointment_log'), 'call_log' => __('administrator.call_log'), 'chat' => __('administrator.chat')];
    if ($key) {
        return $task[$key];
    }
    return $task;
}

    function dateDiffInDays($date1, $date2)
    {
        // date format 21-09-2022
        // Calculating the difference in timestamps
        $diff = strtotime($date2) - strtotime($date1);
        // 1 day = 24 hours
        // 24 * 60 * 60 = 86400 seconds
        return abs(round($diff / 86400));
    }

 function getStockQty($item_id,$stock_qty)
{
    $text = '';
    $item_uom = ProductUnitModel::where('product_id', $item_id)->orderBy('qty_per_unit', 'desc')->get();
    foreach ($item_uom as $item) {
        if ($stock_qty > 0) {
            $unit = findUnit($item->unit_id)->unit??'';
            $uom = (int)($stock_qty / $item->qty_per_unit);
            $stock_qty -= $item->qty_per_unit * $uom;
            if ($uom > 0)
                $text .= "$uom $unit , ";
        }
    }
    return rtrim($text, ' , ');
}



function addJournal($journal_data)
{
    return JournalModel::create($journal_data);
}

function maxJournalId()
{
    return JournalModel::select(DB::raw("Max(journal_tran_id) as last_id"))->first()->last_id ?? 1;
}
function toFloat($text)
{
    return (double)str_replace(',', "", $text);
}
function throw_error($data)
{
    throw ValidationException::withMessages($data);
}

function uCan($permission){
    return \auth()->user()->can($permission);
}
