<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class AiKeyword extends Model
{
	protected $fillable = [
		'keyword',
		'slug',
		'volume',
		'intent',
		'persona',
		'priority',
		'status',
	];
	
	protected $casts = [
		'volume'     => 'integer',
		'created_at' => 'datetime',
		'updated_at' => 'datetime',
	];
	
	/**
	 * Boot the model and automatically generate slug from keyword
	 */
	protected static function boot()
	{
		parent::boot();
		
		static::creating(function ($model) {
			if (empty($model->slug)) {
				// Remove all whitespace from keyword before creating slug
				$cleanKeyword = preg_replace('/\s+/', '', $model->keyword);
				$model->slug = urlencode($cleanKeyword);
			}
		});
		
		static::updating(function ($model) {
			if ($model->isDirty('keyword') && empty($model->slug)) {
				// Remove all whitespace from keyword before creating slug
				$cleanKeyword = preg_replace('/\s+/', '', $model->keyword);
				$model->slug = urlencode($cleanKeyword);
			}
		});
	}
	
	/**
	 * Get the route key for the model.
	 */
	public function getRouteKeyName(): string
	{
		return 'slug';
	}
	
	/**
	 * Scope for filtering by intent
	 */
	public function scopeByIntent($query, $intent)
	{
		return $query->where('intent', $intent);
	}
	
	/**
	 * Scope for filtering by priority
	 */
	public function scopeByPriority($query, $priority)
	{
		return $query->where('priority', $priority);
	}
	
	/**
	 * Scope for filtering by status
	 */
	public function scopeByStatus($query, $status)
	{
		return $query->where('status', $status);
	}
	
	/**
	 * Get high priority keywords
	 */
	public function scopeHighPriority($query)
	{
		return $query->where('priority', 'High');
	}
	
	/**
	 * Get keywords that haven't been generated yet
	 */
	public function scopeNotGenerated($query)
	{
		return $query->where('status', 'processing');
	}
	
	/**
	 * Search keywords by keyword text
	 */
	public function scopeSearch($query, $search)
	{
		return $query->where('keyword', 'LIKE', "%{$search}%")
			->orWhere('persona', 'LIKE', "%{$search}%");
	}
}
