<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Support\Str;

class StudentCourse extends Model
{
    use HasUuids;

    protected $fillable = [
        'student_id',
        'course_id',
        'payment_status',
        'amount_paid',
        'is_certified',
        'enrollment_date',
        'certification_date',
        'certificate_number',
        'issued_by_type',
        'issued_by_id',
        'issued_by_name',
    ];

    protected $casts = [
        'enrollment_date' => 'date',
        'certification_date' => 'date',
        'is_certified' => 'boolean',
        'amount_paid' => 'decimal:2',
    ];

    public function paymentRecords()
    {
        return $this->hasMany(PaymentRecord::class);
    }

    public function getRemainingAmountAttribute()
    {
        $remaining = (float) $this->course->price - (float) $this->amount_paid;
        return max(0, $remaining);
    }

    public function getPaymentStatusTextAttribute()
    {
        $amountPaid = (float) $this->amount_paid;
        $coursePrice = (float) $this->course->price;
        
        if ($amountPaid >= $coursePrice) {
            return 'paid';
        } elseif ($amountPaid > 0) {
            return 'partial';
        } else {
            return $this->payment_status;
        }
    }
    
    public function isFullyPaid()
    {
        return (float) $this->amount_paid >= (float) $this->course->price;
    }

    public function student()
    {
        return $this->belongsTo(Student::class);
    }

    public function course()
    {
        return $this->belongsTo(Course::class);
    }
}
