<?php

class Payment extends \Eloquent
{
    protected $fillable = [
        'installment_id',
        'payment_date',
        'amount',
        'fee_date',
        'is_paid',
        'fee_late',
        'term_id',
        'interest',
        'principal',
        'balance',
        'debt'
    ];

    public static function beforePayment()
    {
        $day = get_config('day_before_payment');
        $now = Carbon\Carbon::today();
        $now->addDays($day);
        return self::installmentCustomer()
                  ->where('payments.payment_date', '<', $now)
                  ->where('payments.payment_date', '>', Carbon\Carbon::now())
                  ->where('installments.status', '<>', 'completed')
                  ->where('payments.is_paid', false)
                  ->orderBy('payments.payment_date', 'ASC')
                  ->selectFields()
                  ->get();
    }

    public static function latePayment()
    {
        $today = Carbon\Carbon::today();
        $payments = self::installmentCustomer()
                        ->where('payments.payment_date', '<', $today)
                        ->where('installments.status', '<>', 'completed')
                        ->where('payments.is_paid', false)
                        ->orderBy('payments.payment_date', 'ASC')
                        ->selectFields()
                        ->get();
        return $payments;
    }

    public function enableBtnPyament($id)
    {
        $now = Carbon\Carbon::today();
        $num = get_config('number_of_month') ? get_config('number_of_month') : 1;
        $now->addMonth($num);
        return $this->where(function ($query) use ($now) {
            $query->where('payment_date', '<', $now)
                            ->orWhere('payment_date', $now);
        })
                  ->where('is_paid', false)
                  ->where('id', $id)->first();
    }

    public function displayDate()
    {
        return format_date_installment($this->payment_date);
    }

    public function lateDay()
    {
        $date = new Carbon\Carbon($this->payment_date);
        $now = Carbon\Carbon::now();
        if ($now > $date) {
            $days = $date->diffInDays($now);
            return $days;
        }
        return 0;
    }

    /**
     * Count amount of time of customer payment
     * @param  int $id installment id
     * @return int     number of time customer payment
     */
    public static function paidTime($id)
    {
        return self::where('is_paid', true)->where('installment_id', $id)->count();
    }

    public function totalAndLate()
    {
        return $this->amount;
    }

    public function getPiadDetail($id)
    {
        $payment = $this->join('receipt_incomes', 'receipt_incomes.payment_id', '=', 'payments.id')
                      ->join('users', 'users.id', '=', 'receipt_incomes.user_id')
                      ->select('users.first_name', 'users.last_name', 'receipt_incomes.payment_name', 'receipt_incomes.created_at')
                      ->where('payments.id', $id)->first();
        return $payment;
    }

    public function paymentDate()
    {
        $date = new Carbon\Carbon($this->created_at);
        return $date->format('d/m/Y h:i:s');
    }

    public static function byMonth($month, $type = 'priciple')
    {
        $start = new \Carbon\Carbon($month);
        $start->startOfMonth();
        $end = new \Carbon\Carbon($month);
        $end->endOfMonth();
        $totalAmount = 0;
        $totalLate = 0;
        $totalPriciple = get_payment('principal', [
            'start' => $start,
            'end' => $end
        ]);
        $totalInterest = get_payment('interest', [
            'start' => $start,
            'end' => $end
        ]);
        $monthlyPayments = MortgagePayment::mortgagePayments([
            'start' => $start,
            'end' => $end
        ]);
        foreach ($monthlyPayments as $payment) {
            $totalPayment = ($payment->total_amount < $payment->amount) && $payment->is_paid_interest == false ? $payment->total_amount : $payment->amount;
            $paidPrincipal = $payment->is_paid_interest ? 0 : $payment->principal;
            $totalPriciple += $paidPrincipal;
            $interest = ($payment->total_amount < $payment->amount) && $payment->is_paid_interest == false ? $payment->amount - $payment->total_amount : $payment->interest;
            $totalInterest += $interest;
        }
        if ($type == 'priciple') {
            return $totalPriciple;// + $totalDeposit;
        }
        if ($type == 'rate') {
            return $totalInterest;
        }
    }

    public function scopePaymentToday($query)
    {
        $start = \Carbon\Carbon::today();
        $end = \Carbon\Carbon::today();
        $end->addHours(23)->addMinutes(59)->addSeconds(59);

        return $query->whereBetween('payment_date', [$start, $end])->where('is_paid', false);
    }

    public function scopeInstallmentCustomer($query)
    {
        return $query->join('installments', 'installments.id', '=', 'payments.installment_id')
                    ->join('loan_customers', 'loan_customers.id', '=', 'installments.customer_id');
    }

    public function scopeInstallmentNotComplete($query)
    {
        return $query->where('installments.status', '<>', 'completed');
    }

    public function scopeSelectFields($query)
    {
        return $query->select(
                        'installments.id as i_id',
                        'loan_customers.full_name_kh',
                        'loan_customers.full_name_en',
                        'loan_customers.tel',
                        'payments.*'
                    );
    }

    public function scopeReceipt($query)
    {
        return $query->join('receipt_incomes', 'receipt_incomes.id', '=', 'payments.receipt_id');
    }

    /**
     * Payment Receipt for
     * Update form
     * @param $query
     * @param $id
     * @return mixed
     */
    public function scopePaymentReceipt($query, $id)
    {
        return $query->receipt()
            ->select(
                'payments.*',
                'receipt_incomes.payment_name',
                'payments.fee_date as p_date',
                'receipt_incomes.receipt_id as receipt_no',
                'receipt_incomes.total_amount',
                'receipt_incomes.total_as_letter',
                'receipt_incomes.in_digit_of',
                'receipt_incomes.with_doc',
                'receipt_incomes.note'
            )
            ->find($id);
    }
}
