<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;

class Certificate extends Model
{
    use HasFactory;

    protected $fillable = [
        'certificate_uuid',
        'student_id',
        'template_id',
        'course_id',
        'internship_mode',
        'internship_nature',
        'start_date',
        'end_date',
        'duration',
        'hours_completed',
        'performance_grade',
        'role_designation',
        'issue_date',
        'status',
        'revocation_reason',
        'pdf_path',
        'issued_by',
        'signatory_title',
        'email_sent',
        'email_sent_at',
        'print_count',
    ];

    protected function casts(): array
    {
        return [
            'start_date' => 'date',
            'end_date' => 'date',
            'issue_date' => 'date',
            'email_sent' => 'boolean',
            'email_sent_at' => 'datetime',
            'print_count' => 'integer',
        ];
    }

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

    public function template(): BelongsTo
    {
        return $this->belongsTo(CertificateTemplate::class, 'template_id');
    }

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

    public function issuer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'issued_by');
    }

    public function getPdfUrlAttribute(): ?string
    {
        return $this->pdf_path ? Storage::url($this->pdf_path) : null;
    }

    public function getVerificationUrlAttribute(): string
    {
        return route('public.verify', $this->certificate_uuid);
    }
}
