<?php

namespace App\Models;

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

/**
 * SmsTemplate Model
 * 
 * Represents a reusable SMS template.
 * Managed by Super Manager and Manager roles.
 * 
 * Requirements: 2.3, 3.8
 * 
 * @property int $id
 * @property string $name
 * @property string $slug
 * @property string $content
 * @property string|null $description
 * @property bool $is_active
 * @property int|null $created_by
 * @property int $usage_count
 */
class SmsTemplate extends Model
{
    use SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'slug',
        'content',
        'description',
        'is_active',
        'created_by',
        'usage_count',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'is_active' => 'boolean',
        'usage_count' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime',
    ];

    /**
     * Common placeholders available in templates.
     */
    public static function availablePlaceholders(): array
    {
        return [
            '{name}' => 'Recipient name',
            '{phone}' => 'Recipient phone number',
            '{email}' => 'Recipient email',
            '{date}' => 'Current date',
            '{time}' => 'Current time',
            '{company}' => 'Company name',
            '{sender_name}' => 'Sender name',
        ];
    }

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

    /**
     * Get messages that used this template.
     */
    public function messages(): HasMany
    {
        return $this->hasMany(SmsMessage::class, 'template_id');
    }

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

    /**
     * Scope for inactive templates.
     */
    public function scopeInactive(Builder $query): Builder
    {
        return $query->where('is_active', false);
    }

    /**
     * Scope for searching templates.
     */
    public function scopeSearch(Builder $query, string $search): Builder
    {
        return $query->where(function ($q) use ($search) {
            $q->where('name', 'like', "%{$search}%")
              ->orWhere('content', 'like', "%{$search}%");
        });
    }

    /**
     * Parse template with given variables.
     */
    public function parse(array $variables): string
    {
        $content = $this->content;
        
        foreach ($variables as $key => $value) {
            $placeholder = '{' . $key . '}';
            $content = str_replace($placeholder, $value, $content);
        }

        // Replace any remaining placeholders with empty string
        $content = preg_replace('/\{[a-zA-Z_]+\}/', '', $content);

        return $content;
    }

    /**
     * Increment usage count.
     */
    public function incrementUsage(): void
    {
        $this->increment('usage_count');
    }

    /**
     * Activate the template.
     */
    public function activate(): void
    {
        $this->update(['is_active' => true]);
    }

    /**
     * Deactivate the template.
     */
    public function deactivate(): void
    {
        $this->update(['is_active' => false]);
    }

    /**
     * Get character count of content.
     */
    public function getCharacterCountAttribute(): int
    {
        return strlen($this->content);
    }

    /**
     * Estimate number of SMS messages needed (160 chars per SMS for GSM-7).
     */
    public function getEstimatedSegmentsAttribute(): int
    {
        $length = $this->character_count;
        
        if ($length <= 160) {
            return 1;
        }
        
        // For longer messages, each segment has 153 characters
        return (int) ceil($length / 153);
    }

    /**
     * Check if template contains placeholders.
     */
    public function hasPlaceholders(): bool
    {
        return preg_match('/\{[a-zA-Z_]+\}/', $this->content) === 1;
    }

    /**
     * Extract placeholders from content.
     */
    public function extractPlaceholders(): array
    {
        preg_match_all('/\{([a-zA-Z_]+)\}/', $this->content, $matches);
        return array_unique($matches[1] ?? []);
    }
}
