<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CertificateField extends Model
{
    protected $table = 'certificate_fields';

    protected $fillable = [
        'template_id',
        'field_key',
        'label',
        'x',
        'y',
        'font_size',
        'font_family',
        'color',
        'align',
        'valign',
        'bold',
        'italic',
        'underline',
        'opacity',
        'required',
        'data_source',
        'default_value',
        'validation_rules',
        'order',
    ];

    protected $casts = [
        'x' => 'integer',
        'y' => 'integer',
        'font_size' => 'integer',
        'bold' => 'boolean',
        'italic' => 'boolean',
        'underline' => 'boolean',
        'opacity' => 'integer',
        'required' => 'boolean',
        'order' => 'integer',
        'validation_rules' => 'array',
    ];

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

    public function getFontWeightAttribute()
    {
        return $this->bold ? 'bold' : 'normal';
    }

    public function getFontStyleAttribute()
    {
        return $this->italic ? 'italic' : 'normal';
    }

    public function getTextDecorationAttribute()
    {
        return $this->underline ? 'underline' : 'none';
    }

    public function getOpacityAttribute($value)
    {
        return $value / 100;
    }

    public function setOpacityAttribute($value)
    {
        $this->attributes['opacity'] = $value * 100;
    }

    public function getDataSourcesAttribute()
    {
        return [
            'student_name' => 'Student Full Name',
            'student_email' => 'Student Email',
            'course_name' => 'Course Name',
            'course_duration' => 'Course Duration',
            'graduation_date' => 'Graduation Date',
            'completion_date' => 'Completion Date',
            'instructor_name' => 'Instructor Name',
            'organization_name' => 'Organization Name',
            'serial_number' => 'Serial Number',
            'certificate_id' => 'Certificate ID',
            'custom_text' => 'Custom Text',
            'current_date' => 'Current Date',
            'current_time' => 'Current Time',
        ];
    }

    public function getValidationRulesArrayAttribute()
    {
        if (is_string($this->validation_rules)) {
            return explode('|', $this->validation_rules);
        }

        return $this->validation_rules ?? [];
    }
}
