<?php

namespace App\Models;

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

class Form extends Model
{
    protected $fillable = [
        'project_id', 'user_id', 'title', 'description', 'slug',
        'is_public', 'is_active', 'settings', 'template_category',
        'task_mapping', 'sla_hours',
    ];

    protected $casts = [
        'settings' => 'array',
        'task_mapping' => 'array',
        'is_public' => 'boolean',
        'is_active' => 'boolean',
    ];

    protected static function booted(): void
    {
        static::creating(function (Form $form) {
            if (empty($form->slug)) {
                $form->slug = Str::slug($form->title) . '-' . Str::random(8);
            }
        });
    }

    // --- Relationships ---

    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function fields()
    {
        return $this->hasMany(FormField::class)->orderBy('sort_order');
    }

    public function submissions()
    {
        return $this->hasMany(FormSubmission::class);
    }

    public function escalationRules()
    {
        return $this->hasMany(FormEscalationRule::class);
    }

    // --- Accessors ---

    public function getPublicUrlAttribute(): string
    {
        return url('/forms/' . $this->slug);
    }

    public function getSubmissionCountAttribute(): int
    {
        return $this->submissions()->count();
    }

    public function getSlaComplianceAttribute(): ?float
    {
        if (!$this->sla_hours) return null;
        $total = $this->submissions()->count();
        if ($total === 0) return 100;
        $compliant = $this->submissions()
            ->whereNotNull('sla_deadline_at')
            ->whereHas('task', fn($q) => $q->where('is_completed', true))
            ->whereRaw('tasks.completed_at <= form_submissions.sla_deadline_at')
            ->count();
        // Simplified: just check submissions with resolved tasks
        $resolved = $this->submissions()->where('status', 'resolved')->count();
        return $total > 0 ? round(($resolved / $total) * 100, 1) : 100;
    }

    // --- Methods ---

    public function duplicate(): self
    {
        $clone = $this->replicate();
        $clone->title = $this->title . ' (Copy)';
        $clone->slug = Str::slug($clone->title) . '-' . Str::random(8);
        $clone->save();

        foreach ($this->fields as $field) {
            $fieldClone = $field->replicate();
            $fieldClone->form_id = $clone->id;
            $fieldClone->save();
        }

        foreach ($this->escalationRules as $rule) {
            $ruleClone = $rule->replicate();
            $ruleClone->form_id = $clone->id;
            $ruleClone->save();
        }

        return $clone;
    }

    public function generateTicketId(): string
    {
        $prefix = strtoupper(substr(Str::slug($this->title, ''), 0, 3)) ?: 'FRM';
        $date = now()->format('Ymd');
        $seq = $this->submissions()->whereDate('created_at', today())->count() + 1;
        return sprintf('TKT-%s-%s-%04d', $prefix, $date, $seq);
    }

    public function getFieldTypes(): array
    {
        return [
            'text' => ['label' => 'Text Input', 'icon' => 'text'],
            'textarea' => ['label' => 'Long Text', 'icon' => 'align-left'],
            'number' => ['label' => 'Number', 'icon' => 'hash'],
            'date' => ['label' => 'Date', 'icon' => 'calendar'],
            'select' => ['label' => 'Dropdown', 'icon' => 'chevron-down'],
            'multi_select' => ['label' => 'Multi Select', 'icon' => 'check-square'],
            'file' => ['label' => 'File Upload', 'icon' => 'paperclip'],
            'section' => ['label' => 'Section Header', 'icon' => 'minus'],
            'heading' => ['label' => 'Heading Text', 'icon' => 'type'],
        ];
    }
}
