<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use App\User;

class NewCertificate extends Model
{
    protected $table = 'new_certificates';

    protected $fillable = [
        'template_id',
        'student_name',
        'student_email',
        'student_id',
        'course_name',
        'completion_date',
        'instructor_name',
        'organization_name',
        'serial_number',
        'custom_fields',
        'generated_image_path',
        'status',
        'generated_by'
    ];

    protected $casts = [
        'completion_date' => 'date',
        'custom_fields' => 'array',
        'generated_at' => 'datetime'
    ];

    /**
     * Get the template this certificate was generated from
     */
    public function template(): BelongsTo
    {
        return $this->belongsTo(NewCertificateTemplate::class, 'template_id');
    }

    /**
     * Get the user who generated this certificate
     */
    public function generator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'generated_by');
    }

    /**
     * Get the generated image URL
     */
    public function getGeneratedImageUrlAttribute()
    {
        if ($this->generated_image_path) {
            return asset($this->generated_image_path);
        }
        return null;
    }

    /**
     * Scope for pending certificates
     */
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    /**
     * Scope for generated certificates
     */
    public function scopeGenerated($query)
    {
        return $query->where('status', 'generated');
    }

    /**
     * Scope for failed certificates
     */
    public function scopeFailed($query)
    {
        return $query->where('status', 'failed');
    }

    /**
     * Mark certificate as generated
     */
    public function markAsGenerated($imagePath = null)
    {
        $this->status = 'generated';
        $this->generated_at = now();
        if ($imagePath) {
            $this->generated_image_path = $imagePath;
        }
        $this->save();
    }

    /**
     * Mark certificate as failed
     */
    public function markAsFailed()
    {
        $this->status = 'failed';
        $this->save();
    }

    /**
     * Get custom field value
     */
    public function getCustomField($key, $default = null)
    {
        return $this->custom_fields[$key] ?? $default;
    }

    /**
     * Set custom field value
     */
    public function setCustomField($key, $value)
    {
        $customFields = $this->custom_fields ?? [];
        $customFields[$key] = $value;
        $this->custom_fields = $customFields;
        $this->save();
    }
}
