<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class NewCertificateTemplate extends Model
{
    protected $table = 'new_certificates_template';

    protected $fillable = [
        'name',
        'description',
        'background_image_path',
        'background_image_name',
        'canvas_width',
        'canvas_height',
        'fields_config',
        'is_active',
        'created_by'
    ];

    protected $casts = [
        'fields_config' => 'array',
        'is_active' => 'boolean',
        'canvas_width' => 'integer',
        'canvas_height' => 'integer'
    ];

    /**
     * Get the certificates generated from this template
     */
    public function certificates(): HasMany
    {
        return $this->hasMany(NewCertificate::class, 'template_id');
    }

    /**
     * Get the user who created this template
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    /**
     * Scope for active templates
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Get the background image URL
     */
    public function getBackgroundImageUrlAttribute()
    {
        if ($this->background_image_path) {
            return asset('storage/' . $this->background_image_path);
        }
        return null;
    }

    /**
     * Get field configuration as array
     */
    public function getFieldsConfigArrayAttribute()
    {
        return $this->fields_config ?? [];
    }

    /**
     * Set field configuration
     */
    public function setFieldsConfig($fields)
    {
        $this->fields_config = $fields;
        $this->save();
    }

    /**
     * Add a field to the configuration
     */
    public function addField($fieldData)
    {
        $fields = $this->fields_config ?? [];
        $fields[] = $fieldData;
        $this->fields_config = $fields;
        $this->save();
    }

    /**
     * Remove a field from the configuration
     */
    public function removeField($fieldIndex)
    {
        $fields = $this->fields_config ?? [];
        if (isset($fields[$fieldIndex])) {
            unset($fields[$fieldIndex]);
            $this->fields_config = array_values($fields); // Re-index array
            $this->save();
        }
    }
}


