<?php
function getPositionKh($pos) {
	if ($pos == "staff") return "បុគ្គលិក";
	return "តំណាងចែកចាយ";
}
/**
 * Function trans gender ot kh
 */
function getGenderKh($gender)
{
	switch ($gender) {
		case 'M':
		case 'Male':
			return "ប្រុស";
			break;
		case 'F':
		case 'Female':
			return "ស្រី";
			break;
		default:
			return "ផ្សេងៗ";
			break;
	}
}

function getField($model,$cri,$field,$param)
{
	if (!empty($field)) {
		$myModel=$model::where($cri,'=',$field)->first();
		if (!empty($myModel)) {
			return $myModel->$param;
		}
		else {
			return " ";
		}

	}
	else {
		return " ";
	}
}
function getCurrencySign($currency = null){
	$baseCurrency = ($currency==null) ? Helper::getConfig('invoice_currency') : $currency ;
	switch ($baseCurrency) {
		case 'usd':
			return "$";
			break;
		case 'riel':
			return "៛";
			break;
		case 'baht':
			return "฿";
			break;
	}
}
function riel_money($amount) {
		$amount = (int) $amount;
		$lt = substr($amount, -2);
		if (strlen($amount) <= 2 && $lt < 50) return 0;
		if ($lt >= 50) {
			$amount = ($amount - $lt) + 100;
		} else {
    	$amount = ($amount - $lt);
		}
    return $amount;
}
function money($amount,$symbol=null)
{
  $amount = (float) $amount;
	if($symbol==null){
		$symbol = getCurrencySign();
	}
	if($amount <= 0) return 0;
    if($symbol=="៛"){
    	$amount = (int) $amount;
      $lt = substr($amount, -2);
      		if ($lt >= 50) {
				$amount = ($amount - $lt) + 100;
			} else {
	    	$amount = ($amount - $lt);
			}
    }
    if($amount && $symbol == "$")
        $amount=number_format($amount,2);
    else
    		$amount=number_format($amount);
    return $symbol. " ". $amount;
}
function moneyR($amount,$symbol = "R")
{
	if($amount==0) return 0;
	$amount=number_format($amount);
	return $symbol." ".$amount;
}
function formatDate($date) {
	$mdate=explode(' ', $date);
	$rearr=explode('-', $mdate[0]);
	$finaldate= $rearr[2]."-".$rearr[1]."-".$rearr[0];
	return $finaldate;
}
function formatDateForDB($date,$explode,$replace) {
	$rearr=explode($explode, $date);
	$finaldate= $rearr[2].$replace.$rearr[0].$replace.$rearr[1];
	return $finaldate;
}
function isAdmin(){
	if (Auth::user()->usertype==="1") {
		return true;
	}
	return false;
}
function debug($data) {
	return "<pre>".var_dump($data)."</pre>";
}
function ifExist($model,$field,$key)
{
	$exist = $model::where($field,$key)->get();
	return (count($exist) >= 1) ? true : false;
}
function ifChanged($model,$id,$field,$key)
{
	$exist = $model::find($id);
	return ($exist->$field <> $key) ? true : false;
}

/*
 * Invoice Helper Class
 */

/*
 * Description Get invoice Number, if invoice is not created, generate one
 * @param stockID id of current branch
 * @return Invoice ID
 */
function getInvoiceID($stockID) {
	$id = $stockID;
	$invoiceID = DB::table('invoice')->where(function($query) use ($id) {
		$query->where('status','open')
				->where('stockID', '=',$id);
	})->first();
	if(!empty($invoiceID->id)){
		return $invoiceID->id;
	}
	else {
		$id = time().uniqid();
		$unikey = time().Session::getId().uniqid();

		$invoice = new Invoice;
		$invoice->id = $id;
		$invoice->unikey = $unikey;
		$invoice->status = 'open';
		$invoice->stockID = $stockID;
		$invoice->total = 0;
		$invoice->recieve = 0;
		$invoice->save();
	}
}
function getSuspenedInvoice($stockID) {
	$invoiceID = DB::table('invoice')->where(function($query) use ($stockID) {
		$query->where('status','suspended')
				->where('stockID', '=',$stockID);
	})->orderBY('pid','DESC')->get();
	return $invoiceID;
}
function switchInvoice($stockID,$switchToInvoice) {
	suspendInvoice($stockID);
	$invoiceID = Invoice::find($switchToInvoice);
	$invoiceID->status = 'open';
	$invoiceID->save();
	return true;
}
function suspendInvoice($stockID) {
	$invoiceID = getInvoiceID($stockID);
	$invoice = Invoice::find($invoiceID);
	$invoice->status = 'suspended';
	$invoice->save();

	return true;
}
function createInvoice($stockID) {
	$checkInvoice = getInvoiceID($stockID);
	if(empty($checkInvoice)) {
		$invoice = new Invoice;
		$invoice->id = $id;
		$invoice->unikey = $unikey;
		$invoice->status = 'open';
		$invoice->stockID = $stockID;
		$invoice->total = 0;
		$invoice->recieve = 0;
		$invoice->save();
	}
	$checkInvoice = getInvoiceID($stockID);
	return $checkInvoice;
}
function calculateDiscount($price,$percent) {
	return ($price*$percent)/100;
}
function getTotal($invoiceID) {
	$items_incart = DB::table('cart')->where('invoiceID',$invoiceID)->get();
	$total_price= 0;
	$total_amount = 0;
	foreach($items_incart as $item) :
		$total_amount += $item->amount;
		$total_price  += $item->price*$item->amount;
	endforeach;
	return $total_price;
}
function updateTotal($invoiceID) {
	$total = getTotal($invoiceID);
	$invoice = Invoice::find($invoiceID);
	$invoice->total = $total;
	$invoice->save();

	return $total;
}
function getSetting($meta_key) {
	$setting = Settings::where('meta_key',$meta_key)->first();
	if(ifExist('Settings','meta_key',$meta_key))
		return $setting->meta_value;
}
function getMemberInfo() {
	$invoiceid = getInvoiceID(Auth::user()->id);
	$memberCardID = DB::table('invoice')->where(function($query) use ($invoiceid) {
		$query->where('status','open')
				->where('id',$invoiceid)
				->where('memberID', '!=','');
	})->first();
	if(!empty($memberCardID)) {
		$cardnumber = $memberCardID->memberID;
		$member = Member::where('cardnumber', $cardnumber)->first();
	}
	else {
		$member = "";
	}
	return $member;
}

function convertInvoiceNumber($invoicenumber) {
	if($invoicenumber == "") return;
	switch(strlen($invoicenumber)) {
		case 1: $invoicenumber="00000".$invoicenumber;
			break;
		case 2: $invoicenumber="0000".$invoicenumber;
			break;
		case 3: $invoicenumber="000".$invoicenumber;
			break;
		case 4: $invoicenumber="00".$invoicenumber;
			break;
	}
	return $invoicenumber;
}

function checkPermission($perm) {
	if(Auth::user()->role == "Admin") {
		return true;
	}
	else {
		if (Auth::user()->$perm == 1) {
			return true;
		}
		else return false;
	}

}
function getMemberBuyAmount($memberID) {
	if(empty($memberID)) return;
	$member = DB::table('invoice')->select(DB::raw('sum(total) as total_amount'))->where(function($query) use($memberID) {
		$query->where('memberID',$memberID)
			->where('status','=','closed');
	})->first();
	return $member->total_amount;
}
function checkIfContains( $needle, $haystack ) {
    return preg_match( '#\b' . preg_quote( $needle, '#' ) . '\b#i', $haystack ) !== 0;
}
function saveImage($base64img,$location,$name){
    define('UPLOAD_DIR', $location);
    $base64img = str_replace('data:image/jpeg;base64,', '', $base64img);
    $data = base64_decode($base64img);
    $file = UPLOAD_DIR . $name;
    file_put_contents($file, $data);
}
function getInvoiceStatus($status)
{
	if ($status == 'open') return "";
	if ($status == 'closed') return "";
	if ($status == 'draft') return "លុប ចោល";
}
function getTypeKh($type)
{
	if ($type == "income") {
		return trans('profits.income');
	} else {
		return trans('profits.expense');
	}
}
/**
 * Covert all reil money
 * @param  string $number
 * @return int
 */
function riel($number)
{
	$riel = $number;
  $length = strlen($riel);
  $two = (int) substr($riel, $length-2,2);
  if ($two >= 50) {
    return ($riel - $two) + 100;
  } else {
    return $riel - $two;
  }
}
function getLimitSize()
{
	return 1048576 * 10;
}
/**
 * Generate Url for print to make
 * Report look and feel better than before
 *
 *
 */
function defaultUrl()
{
	$url  =  URL::current(). '/print';
	$url .= "?start_date=". Input::get('start_date');
	$url .= "&end_date=" . Input::get('end_date');
	return $url;
}
function printProductsInWarehouse()
{
	$url  = defaultUrl();
	$url .= "&start_barcode=" . Input::get('start_barcode');
	$url .= "&end_barcode=" . Input::get('start_barcode');
	if(!empty(Input::get('category'))) {
		foreach (Input::get('category') as $value) {
			$url .= "&category%5B%5D=". $value;
		}
	}
	$url .= "&type=". Input::get('type');
	if (!empty(Input::get('stock'))) {
		$url .= "&stock=". Input::get('stock');
	}
	return $url;
}
function downloadPsExcel()
{
	$url  =  URL::current(). '/download';
	$url .= "?start_date=". Input::get('start_date');
	$url .= "&end_date=" . Input::get('end_date');
	$url .= "&start_barcode=" . Input::get('start_barcode');
	$url .= "&end_barcode=" . Input::get('start_barcode');
	if(!empty(Input::get('category'))) {
		foreach (Input::get('category') as $value) {
			$url .= "&category%5B%5D=". $value;
		}
	}
	if (!empty(Input::get('stock'))) {
		$url .= "&stock=". Input::get('stock');
	}
	return $url;
}
function printProfits()
{
	$url  = defaultUrl();
	$url .= "&type=" . Input::get('type');
	$url .= "&search=true";
	return $url;
}
function printProducts()
{
	$url  = defaultUrl();
	if(!empty(Input::get('group'))) {
		foreach (Input::get('group') as $value) {
			$url .= "&group%5B%5D=". $value;
		}
	}
	$url .= "&type=". Input::get('type');
	return $url;
}
function printTransfer()
{
	$url = defaultUrl();
	if(!empty(Input::get('group'))) {
		foreach (Input::get('group') as $value) {
			$url .= "&group%5B%5D=". $value;
		}
	}
	$url .= "&type=". Input::get('type');
	if(!empty(Input::get('user'))) {
		foreach (Input::get('user') as $value) {
			$url .= "&user%5B%5D=". $value;
		}
	}
	return $url;
}
function printSaleHistory()
{
	$url  = defaultUrl();
	if(!empty(Input::get('user'))){
		foreach (Input::get('user') as $value) {
			$url .= "&user%5B%5D=".$value;
		}
	}
	$url .= "&start_barcode=". Input::get('start_barcode');
	$url .= "&end_barcode=". Input::get('end_barcode');
	$url .= "&stock=" . Input::get('stock');
	if(!empty(Input::get('category'))) {
		foreach (Input::get('category') as $value) {
			$url .= "&category%5B%5D=" . $value;
		}
	}
	return $url;
}
function downloadSaleHistory()
{
	$url  =  URL::current(). '/download';
	$url .= "?start_date=". Input::get('start_date');
	$url .= "&end_date=" . Input::get('end_date');
	if(!empty(Input::get('user'))){
		foreach (Input::get('user') as $value) {
			$url .= "&user%5B%5D=".$value;
		}
	}
	$url .= "&start_barcode=". Input::get('start_barcode');
	$url .= "&end_barcode=". Input::get('end_barcode');
	$url .= "&stock=" . Input::get('stock');
	if(!empty(Input::get('category'))) {
		foreach (Input::get('category') as $value) {
			$url .= "&category%5B%5D=" . $value;
		}
	}
	return $url;
}
function get_second_currency() {
  return Helper::getConfig("second_invoice_currency");
}

function get_config($key) {
    return Helper::getConfig($key);
}
function get_min_return() {
    return get_config('min_amount_return');
}

/**
 * Enable sale product out of stock
 * @return boolean
 */
function enable_owe() {
	return get_config('enable_sale_out_of_stock');
}

function p_stock_amount($pid) {
	$outlet = DB::table('outlets as o')
				->join('products as p', 'o.product_id', '=', 'p.id')
				->where('o.product_id', $pid)
				->select('o.amount')
				->first();
	if ($outlet) return $outlet->amount;
	return 0;
}

function get_c_invoice($id) {
  $customer = DB::table('customers as c')
            ->join('invoices as i', 'i.customer_id', '=',  'c.id')
            ->where('i.id', $id)->first();
  if (empty($customer)) return trans('customers.general');
  return $customer->first_name . " " . $customer->last_name . " (".$customer->tel .")";
}

function owe_amount($pId, $invoiceId) {
	$p = OweProduct::where('invoice_id', $invoiceId)->where('product_id', $pId)->first();
	if ($p) return $p->amount;
	return 0;
}

function get_min_amount() {
	return \DB::select(DB::raw("select `p`.`id`, `p`.`name_kh`, `p`.`name`, `o`.`amount`, `p`.`min_amount` from `products` as `p` inner join `outlets` as `o` on `o`.`product_id` = `p`.`id` where `p`.`min_amount` > `o`.`amount`"));
}

/**
 * Get total product buy from customer
 * @param  int $id invoice ID
 * @return float   total price of buy product
 */

function get_debt_status($status) {
	if ($status == "unpaid") {
		return "<span class='label label-default'>". trans('debts.status.unpaid')."</span>";
	} elseif ($status == "paid") {
		return "<span class='label label-success'>". trans('debts.status.paid')."</span>";
	} else {
		return "<span class='label label-warning'>". trans('debts.status.deposit')."</span>";
	}
}

/**
 * Add Product to stock
 * @param array $data BuyProducts
 */
function addPtoStock($data) {
	$success = false;
	foreach ($data as $p) {
		$outlet = Outlet::where('product_id', $p->product_id)->first();
		if ($outlet) {
			 $outlet->amount += $p->qty;
		   $outlet->available_amount += $p->qty;
		   $outlet->save();
		} else {
			$outlet = Outlet::create([
				'product_id' 	=> $p->product_id,
				'amount'			=> $p->qty,
				'available_amount' => $p->qty,
				'user_id'			=> Auth::user()->id,
				'price'				=> $p->price,
				'sku'					=> $p->sku,
				'stock_id'		=> Auth::user()->stock_id
		  ]);
		}
		$history = new History;
		$history->product_id = $p->product_id;
		$history->amount = $p->qty;
		$history->ref_id = $p->invoice_id;
		$history->operation_type = "in";
		$history->user_id = Auth::user()->id;
		$history->operated_on = "product";
		$history->save();
		$success = true;
	}
	return $success;
}

function getQuotId($cId = null) {
	$quotation = Quotation::where('status', "open")
												->where('customer_id', $cId)
												->first();
  if (!empty($quotation)) return $quotation->id;
  $quotation = new Quotation;
  $quotation->status = "open";
  $quotation->customer_id = $cId;
  $quotation->save();
  return $quotation->id;

}
/**
 * Get Customer name for quotation
 * @param  int $id
 * @return string
 */
function get_c_q($id) {
	$quotation = Quotation::leftJoin('customers', 'customers.id', '=', 'quotations.customer_id')
												->select('quotations.id', 'quotations.customer_id', 'customers.first_name', 'customers.last_name')
												->where('quotations.id', $id)
												->whereIn('status', ['closed', 'approved', 'cancel'])
												->first();
	if ($quotation->customer_id > 0) return $quotation->first_name . " ". $quotation->last_name;
	return trans('customers.general');
}

/**
 * Quotation status
 * @param  string $status
 * @return string
 */
function quot_status($status) {
	$output = "";
	if ($status == "approved") {
		$output = '<span class="label label-success">'. trans('quotations.status.approved').'</span>';
	} else if ($status == "cancel")  {
		$output = '<span class="label label-danger">'. trans('quotations.status.cancel').'</span>';
	} else {
		$output = '<span class="label label-warning">'. trans('quotations.status.closed').'</span>';
	}
	return $output;
}

function count_product_in_brand($id) {
  $number = \DB::table('brands as b')
                ->join('products as p', 'p.brand_id', '=', 'b.id')
                ->where('b.id', $id)->count();
  if ($number > 0) return $number;
  return 0;
}

function s_status($status) {
	$output = "";
	if ($status == "pendding") {
		$output = '<span class="label label-warning">'. trans('services.status.pendding').'</span>';
	} else if ($status == "repairing"){
		$output = '<span class="label label-primary">'. trans('services.status.repairing').'</span>';
	} else if ($status == "completed") {
		$output = '<span class="label label-info">'. trans('services.status.completed').'</span>';
	} else if ($status == "paid") {
		$output = '<span class="label label-success">'. trans('services.status.paid').'</span>';
	}
	return $output;
}
/**
 * Get Second currency sign
 * @return [type] [description]
 */
function gscc() {
	return getCurrencySign(get_second_currency());
}

/**
 * User Can Do something
 * @param  [type] $action [description]
 * @return [type]         [description]
 */
function user_can($action) {
	return \UserRole::has($action);
}

function get_prin_in_sold($id) {
	 $totalPriceIn = 0;
	 $orders = DB::table('products as p')
                ->join('orders as o ', 'o.product_id', '=', 'p.id')
                ->select('p.price_in', 'o.amount')
                ->where('o.sold', true)
                ->where('o.invoice_id', $id)->get();
   if (count($orders) > 0) {
   		foreach ($orders as $order) {
   			$totalPriceIn += $order->price_in * $order->amount;
   		}
   		return $totalPriceIn;
   }
   return 0;

}

function d_format($date) {
	$d = new \Carbon\Carbon($date);
	return $d->format('d/m/Y');
}

function dt_format($date) {
    $d = new \Carbon\Carbon($date);
    return $d->format('d/m/Y H:m:i');
}
function get_price_in_product_sold($start = null, $end = null) {
	$profits = Profit::whereNotNull('invoice_id');
	if (!empty($start) && !empty($end)) {
		$profits->whereBetween('created_at', [$start, $end]);
	}
	$price_in = 0;
	foreach ($profits->get() as $profit) {
	    $orders = DB::table('products as p')
	            ->join('orders as o ', 'o.product_id', '=', 'p.id')
	            ->select('p.price_in', 'o.amount')
	            ->where('o.sold', true)
	            ->where('o.invoice_id', $profit->invoice_id)->get();
	    if (count($orders) > 0) {
	        foreach ($orders as $order) {
	            $price_in += $order->price_in * $order->amount;
	        }
	    }
	}
	return $price_in;
}

/**
 * Get Main Currency
 * @return string name of Currency
 */
function get_currency() {
  return \Helper::getConfig('invoice_currency');
}

function get_thb_rate() {
	return get_config('thb_rate');
}

function get_usd_rate() {
	return get_config('usd_rate');
}

function get_sc_sign() {
	return getCurrencySign(get_second_currency());
}

/**
 * Return Mixxx
 */
function get_q_line($string) {
	$length = strlen($string);
	if ($length <= 35) return 1;
	return round(($length / 35));
}
function get_i_line($string) {
	$length = strlen($string);
	if ($length <= 27) return 1;
	return round(($length / 27	));
}

function get_day_kh($d) {
    $day = "";
    switch ($d) {
        case 'Monday':
            $day = trans('installments.days.monday');
            break;
        case 'Tuesday':
            $day = trans('installments.days.tuesday');
            break;
        case 'Wednesday':
            $day = trans('installments.days.wednesday');
            break;
        case 'Thursday':
            $day = trans('installments.days.thursday');
            break;
        case 'Friday':
            $day = trans('installments.days.friday');
            break;
        case 'Saturday':
            $day = trans('installments.days.saturday');
            break;
        case 'Sunday':
            $day = trans('installments.days.sunday');
            break;
        default:
            $day = "";
            break;
    }
    return $day;
}


function format_date_installment($date, $i =0) {
    $dmy = new \Carbon\Carbon($date);
    $d = $dmy->day;
    $m = $dmy->month;
    $endDay = new \Carbon\Carbon($date);
    $endDay->endOfMonth();
    $e = $endDay->day;
    if ($m==2 && ($e == 28 || $e == 29)) {
    	$dmy->addMonth($i);
    	return $dmy->format('d/m/Y');
    }
    if ($i > 0) {
    	// if ($d == 31) {
    	// 	// $i += 1;
    	// 	$dmy->day = 1;
    	// 	return "31";
    	// }
    	if ($m ==2 && $d != $e) {
    		$dmy->day = $e;
    	}
        $dmy->addMonth($i);
    }
    if ($m==2 && ($e == 28 || $e == 29)) {
    	return "1";
    }
    return $dmy->format('d/m/Y');
}

function get_day_week($date) {
    $day = new \Carbon\Carbon($date);
    return get_day_kh($day->format('l'));
}

function checkPayment($date) {
    $date = new Carbon\Carbon($date);
    $endDate = new Carbon\Carbon($date);
    $now = Carbon\Carbon::now();
    if ($date->month == $now->month && $date->year == $now->year)  return true;
    return false;
}

function lateDay($pay, $status) {
	// $payment = Payment::find($id);
	if ($pay->is_paid == false && $status == "completed"){
		return 0;
	}
    $date = new Carbon\Carbon($pay->payment_date);
    $feeDate = new Carbon\Carbon($pay->fee_date);
    $now = Carbon\Carbon::now();
    if ($now > $date && $pay->is_paid == false) {
        $days = $date->diffInDays($now);
        return $days;
    } else {
    	return $pay->fee_late;
    }
}

function getLatePayments()
{
    $today = Carbon\Carbon::today();
    $payments = Payment::join("installments", "installments.id", "=", "payments.installment_id")
    									->where('payment_date', '<', $today)
    									->where("installments.status", "<>", "completed")
    									->where('is_paid', false)
    									->get();
    return $payments;
}

/**
 * Get total Priciple Payment
 * @return float amount of priciple payment
 */
function get_total_payment_priciple()
{
	$payments = Installment::join("payments", "installments.id", "=", "payments.installment_id")
                          ->select("installments.*")
                          ->where("payments.is_paid", true)
                          ->get();
  	$total = 0;
  	foreach ($payments as $installment) {
    	$total += $installment->getMonthlyPriciple();
  	}
  	return $total;
}

function ipAddress() {
	$host= gethostname();
	$ip = gethostbyname($host);
	return $ip;
}
function imgUrl($path) {
	$ip = Config::get("app.ip");
	return $ip .$path;
}
function f_format($number) {
	return floor($number * 100) / 100;
}

function add_loan_months($date_str, $months)
{
    $date = new DateTime($date_str);

    // We extract the day of the month as $start_day
    $start_day = $date->format('j');

    // We add 1 month to the given date
    $date->modify("+{$months} month");

    // We extract the day of the month again so we can compare
    $end_day = $date->format('j');

    if ($start_day != $end_day)
    {
        // The day of the month isn't the same anymore, so we correct the date
        $date->modify('last day of last month');
    }

    return $date->format("Y-m-d");
}

function cont_payment_today() {
	return Payment::installmentCustomer()->installmentNotComplete()->paymentToday()->count();
}

function get_paid_all_amount($id)
{
	$installment = Installment::find($id);
	if ($installment && $installment->status =="completed") return $installment->paid_off_amount;
	return 0; 
}

function installment_paid_off($id, $type = "total")
{
	$installment = Installment::find($id);
	$paids = Payment::where("installment_id", $id)->where("is_paid", true)->where("is_paid_all",false)->get();
	if (count($paids) <= 0) {
		if ($type == "total") return $installment->paid_off_amount;
		if ($type == "principal") return $installment->getPriciple();
		if ($type == "interest") return $installment->paid_off_amount - $installment->getPriciple();
	} else {
		$total_paid_i = 0;
		$total_paid_p = 0;
		$total_payment = 0;
		foreach ($paids as $pay) {
			$total_paid_i += $pay->amount - $installment->getMonthlyPriciple();
			$total_paid_p += $installment->getMonthlyPriciple();
			$total_payment += $pay->amount;
		}
		$remain_p = $installment->getPriciple() - $total_paid_p;
		if ($type == "total") return $installment->paid_off_amount;
		if ($type == "principal") return $remain_p;
		if ($type == "interest") return $installment->paid_off_amount - $remain_p;
	}
}

function round_up ( $value, $precision ) {
    $pow = pow ( 10, $precision );
    return ( ceil ( $pow * $value ) + ceil ( $pow * $value - ceil ( $pow * $value ) ) ) / $pow;
}

function get_payment($type = 'total', $date) {
	
	$payments = Payment::whereNotNull('fee_date');
	if (!empty($date)) {
    	$payments = $payments->whereBetween('fee_date', [$date['start'], $date['end']]);
	}
	
	$payments = $payments->get();
    $totalPrincipal = 0;
    $totalInterest = 0;
    $totalLate = 0;
    $totalAmount =0;
    foreach ($payments as $payment) {
        $installment = Installment::find($payment->installment_id);
        $totalPrincipal += $payment->is_paid_all ? installment_paid_off($payment->installment_id, 'principal') : $installment->getMonthlyPriciple();
        $totalInterest += $payment->is_paid_all ? installment_paid_off($payment->installment_id, 'interest') : $payment->amount - $installment->getMonthlyPriciple();
        $totalAmount += $payment->is_paid_all ? installment_paid_off($payment->installment_id) : $payment->amount ;
        $totalLate += $payment->fee_late;
    }
		// return dd($type);
    if ($type == "total") return $totalAmount;
    if ($type == "principal") return $totalPrincipal;
    if ($type == "late") return $totalLate;
    if ($type == 'interest') return $totalInterest;
		
    return 0;
}
function this_month() {
    $date = \Carbon\Carbon::now();
    return $date->format('F');
}

function mort_before_payments() {
    $payments = MortgagePayment::beforePayments()->selectFields();
    return $payments;
}
function mort_today_payments() {
    $payments = MortgagePayment::todayPayments()->selectFields();
    return $payments;
}
function mort_late_payments() {
    $payments = MortgagePayment::latePayments()->selectFields();
    return $payments;
}

function check_cloud_expired()
{
    $expiredDate = get_config('cloud_expired_date');
    if (empty($expiredDate) || $expiredDate == null) return false;
    $now = \Carbon\Carbon::now();
    $now->addMonth();
    $date = Carbon\Carbon::createFromFormat("d/m/Y", $expiredDate);
    if ($now > $date) return true;
    return false;
}
?>
