<?php

class MortgagePayment extends \Eloquent {
	protected $fillable = [
	    'mortgage_id',
        'payment_date',
        'payment_date',
        'fee_date',
        'amount',
        'principal',
        'interest',
        'receipt_id',
        'note'
    ];

	public function scopeMortgage($query)
    {
        return $query->join("mortgages", 'mortgages.id', "=", "mortgage_payments.mortgage_id");
    }

    public function scopeNotComplete($query)
    {
        return $query->where("mortgages.status", "<>", "completed");
    }

    public function scopeBeforePayments($query)
    {
        $day = get_config('mortgage_alert_day');
        $day = $day > 0 ? $day : 3;
        $now = Carbon\Carbon::today();
        $now->addDays($day);
        return $query->mortgage()->notComplete()
            ->where('mortgage_payments.payment_date', '<', $now)
            ->where('mortgage_payments.payment_date', '>', Carbon\Carbon::now())
            ->where('mortgage_payments.is_paid', false)
            ->orderBy('mortgage_payments.payment_date', 'ASC');
    }

    public function scopeTodayPayments($query)
    {
        $start = \Carbon\Carbon::today();
        $end = \Carbon\Carbon::today();
        $end->hour = 23;
        $end->minute = 59;
        $end->second = 59;
        return $query->mortgage()
            ->notComplete()
            ->whereBetween('mortgage_payments.payment_date', [$start, $end])
            ->where('mortgage_payments.is_paid', false);
    }

    public function scopeLatePayments($query)
    {
        $today = Carbon\Carbon::today();
        return $query->mortgage()->notComplete()
            ->where('mortgage_payments.payment_date', '<', $today)
            ->where('mortgage_payments.is_paid', false)
            ->orderBy('mortgage_payments.payment_date', 'ASC');
    }
    public function scopeSelectFields($query)
    {
        return $query->select(
            'mortgages.fullname',
            'mortgages.tel',
            'mortgages.id as m_id',
            'mortgage_payments.payment_date',
            'mortgage_payments.amount'
        );
    }

    public static function mortgagePayments($data){
        $payments = self::join("mortgages", "mortgages.id", "=", "mortgage_payments.mortgage_id")
            ->join("receipt_incomes", "mortgage_payments.receipt_id", "=", "receipt_incomes.id")
            ->where("mortgage_payments.is_paid", true)
            ->select("mortgages.fullname","mortgages.tel","mortgage_payments.*", "receipt_incomes.total_amount");
        if (!empty($data)) {
            $payments->whereBetween("mortgage_payments.fee_date", [$data['start'], $data['end']]);
        }
        $payments = $payments->get();
        return $payments;
	}
}