<?php

namespace App\Models;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Str;

class Form extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'name', 'uuid', 'type', 'status', 'fields', 'settings', 'style',
        'total_views', 'total_submissions', 'user_id',
    ];

    protected $casts = [
        'fields'             => 'array',
        'settings'           => 'array',
        'style'              => 'array',
        'total_views'        => 'integer',
        'total_submissions'  => 'integer',
    ];

    protected static function booted(): void
    {
        static::creating(function (Form $form) {
            $form->uuid ??= (string) Str::uuid();
            $form->fields ??= [];
            $form->settings ??= [];
            $form->style ??= [];
        });
    }

    public function lists(): BelongsToMany
    {
        return $this->belongsToMany(ContactList::class, 'form_list', 'form_id', 'list_id');
    }

    public function tags(): BelongsToMany
    {
        return $this->belongsToMany(Tag::class, 'form_tag', 'form_id', 'tag_id');
    }

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

    public function submitUrl(): string
    {
        return url("/api/forms/submit/{$this->uuid}");
    }

    public function popupScriptUrl(): string
    {
        return url("/api/forms/{$this->uuid}/popup.js");
    }

    public function inlineScriptUrl(): string
    {
        return url("/api/forms/{$this->uuid}/embed.js");
    }

    public function embedTargetId(): string
    {
        return 'crmfic-form-' . $this->uuid;
    }

    public function viewPingUrl(): string
    {
        return url("/api/forms/{$this->uuid}/view");
    }

    public function submissionRate(): float
    {
        if ($this->total_views <= 0) {
            return 0.0;
        }

        return round(($this->total_submissions / $this->total_views) * 100, 1);
    }
}
