<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

/**
 * Model: RCampaign (Health Campaign)
 * 
 * Represents a health advocacy campaign for community engagement.
 * Supports banners, targeting, and associated stories.
 * 
 * @property int $id
 * @property int $user_id
 * @property string $title
 * @property string $slug
 * @property string $description
 * @property string|null $objectives
 * @property string|null $banner_image
 * @property string|null $thumbnail
 * @property string|null $target_audience
 * @property array|null $regions
 * @property \Carbon\Carbon $start_date
 * @property \Carbon\Carbon|null $end_date
 * @property string $status
 * @property bool $is_featured
 * @property string|null $meta_title
 * @property string|null $meta_description
 * @property array|null $meta_keywords
 * @property int $views_count
 * @property int $stories_count
 */
class RCampaign extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'r_campaigns';

    protected $fillable = [
        'user_id',
        'title',
        'slug',
        'description',
        'objectives',
        'banner_image',
        'thumbnail',
        'target_audience',
        'regions',
        'start_date',
        'end_date',
        'status',
        'is_featured',
        'meta_title',
        'meta_description',
        'meta_keywords',
        'views_count',
        'stories_count',
    ];

    protected $casts = [
        'start_date' => 'date',
        'end_date' => 'date',
        'is_featured' => 'boolean',
        'regions' => 'array',
        'meta_keywords' => 'array',
        'views_count' => 'integer',
        'stories_count' => 'integer',
    ];

    /**
     * Status constants.
     */
    const STATUS_DRAFT = 'draft';
    const STATUS_ACTIVE = 'active';
    const STATUS_PAUSED = 'paused';
    const STATUS_COMPLETED = 'completed';
    const STATUS_ARCHIVED = 'archived';

    /**
     * Get the campaign creator/manager.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * Get stories associated with this campaign.
     */
    public function stories(): HasMany
    {
        return $this->hasMany(RHealthStory::class, 'campaign_id');
    }

    /**
     * Get polls associated with this campaign.
     */
    public function polls(): HasMany
    {
        return $this->hasMany(RPoll::class, 'campaign_id');
    }

    /**
     * Scope: Active campaigns.
     */
    public function scopeActive($query)
    {
        return $query->where('status', self::STATUS_ACTIVE);
    }

    /**
     * Scope: Featured campaigns.
     */
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    /**
     * Scope: Currently running campaigns.
     */
    public function scopeRunning($query)
    {
        return $query->where('status', self::STATUS_ACTIVE)
                     ->where('start_date', '<=', now())
                     ->where(function ($q) {
                         $q->whereNull('end_date')
                           ->orWhere('end_date', '>=', now());
                     });
    }

    /**
     * Check if campaign is currently active.
     */
    public function isCurrentlyActive(): bool
    {
        if ($this->status !== self::STATUS_ACTIVE) {
            return false;
        }

        if ($this->start_date->isFuture()) {
            return false;
        }

        if ($this->end_date && $this->end_date->isPast()) {
            return false;
        }

        return true;
    }

    /**
     * Get status color for UI.
     */
    public function getStatusColorAttribute(): string
    {
        return match($this->status) {
            self::STATUS_DRAFT => 'gray',
            self::STATUS_ACTIVE => 'green',
            self::STATUS_PAUSED => 'yellow',
            self::STATUS_COMPLETED => 'blue',
            self::STATUS_ARCHIVED => 'red',
            default => 'gray',
        };
    }

    /**
     * Get status label.
     */
    public function getStatusLabelAttribute(): string
    {
        return ucfirst($this->status);
    }

    /**
     * Increment view count.
     */
    public function incrementViews(): void
    {
        $this->increment('views_count');
    }

    /**
     * Update stories count.
     */
    public function updateStoriesCount(): void
    {
        $this->stories_count = $this->stories()->approved()->count();
        $this->save();
    }

    /**
     * Generate slug from title.
     */
    public static function generateSlug(string $title): string
    {
        $slug = Str::slug($title);
        $count = static::where('slug', 'LIKE', "{$slug}%")->count();
        
        return $count > 0 ? "{$slug}-{$count}" : $slug;
    }
}
