<?php

namespace Modules\Installment\Entities;

use App\User;
use Illuminate\Database\Eloquent\Model;
use Modules\CourseSetting\Entities\Course;

class InstallmentPurchaseRequest extends Model
{
    protected $fillable = ['payment_status'];

    public function installmentPayments()
    {
        return $this->hasMany(InstallmentPurchasePayment::class, 'installment_purchase_id', 'id');
    }

    public function plan()
    {
        return $this->belongsTo(InstallmentPlan::class, 'plan_id', 'id');
    }

    public function topic()
    {
        return $this->belongsTo(Course::class, 'topic_id', 'id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    protected $casts = [
        'checkout_data' => 'array',
    ];

    public function overdueInstallment()
    {
        return $this->installmentPayments()->where('status', '!=', 'paid')->where('due_date', '<', date('Y-m-d'))->get();
    }

    public function installmentRemainingDays()
    {
        $installmentPayments = $this->installmentPayments()->where('status', '!=', 'paid')->where('due_date', '>=', date('Y-m-d'))
            ->orderBy('id', 'desc')->first();
        $remainingDays = 0;
        if ($installmentPayments) {
            $remainingDays = dateDifference(date('Y-m-d'), $installmentPayments->due_date);
        }
        return $remainingDays;
    }

    public function installment_cart()
    {
        return $this->belongsTo(InstallmentCart::class, 'id', 'purchase_id');
    }

    public function installmentAttachment()
    {
        return $this->hasMany(InstallmentVerificationAttachment::class, 'installment_purchase_id', 'id');
    }

    public function approvedPurchase($user_id)
    {
        return $this->where('payment_status', '!=', 'incomplete')->with('installmentPayments')
            ->where('user_id', $user_id)
            ->get();
    }

}
