<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * Business Standard News Model
 * Matches tbl_news schema from myapiusa_spanish SQL dump.
 * Key columns: photo_url (not photo), news_title_english, news_content_english, etc.
 */
class News extends Model
{
    protected $table      = 'tbl_news';
    protected $primaryKey = 'news_id';
    public    $timestamps = false;

    protected $guarded = [];

    protected $casts = [
        'published_at' => 'datetime',
    ];

    // ─── Relationships ──────────────────────────────────────────────────────────

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'category_id');
    }

    public function author()
    {
        return $this->belongsTo(Author::class, 'author_id', 'author_id');
    }

    // ─── Accessors ───────────────────────────────────────────────────────────────

    /**
     * Full URL for the news article image.
     * DB column is `photo_url` — may be a full URL or bare filename.
     */
    public function getPhotoUrlAttribute(): string
    {
        $filename = $this->attributes['photo_url'] ?? null;

        if (!empty($filename)) {
            // If it's already a full URL (from CDN etc.), return as-is
            if (filter_var($filename, FILTER_VALIDATE_URL)) {
                return $filename;
            }
            // Primary location: assets/upload/news/
            if (file_exists(base_path('assets/upload/news/' . $filename))) {
                return asset('assets/upload/news/' . $filename);
            }
            // Fallback: public/images/
            if (file_exists(public_path('images/' . $filename))) {
                return asset('images/' . $filename);
            }
        }

        return asset('images/img.webp');
    }

    /**
     * Alias — banner and photo are the same for BS.
     */
    public function getBannerUrlAttribute(): string
    {
        return $this->photo_url;
    }

    /**
     * Reading-time estimate in minutes (uses English content if available).
     */
    public function getReadingTimeAttribute(): int
    {
        $content   = $this->attributes['news_content_english'] ?? $this->attributes['news_content'] ?? '';
        $wordCount = str_word_count(strip_tags($content));
        return max(1, (int) ceil($wordCount / 200));
    }

    /**
     * Human-friendly published date.
     */
    public function getPublishedHumanAttribute(): string
    {
        if (!$this->published_at) return '';
        $diff = now()->diffInMinutes($this->published_at);
        if ($diff < 60)  return $diff . ' min' . ($diff === 1 ? '' : 's') . ' ago';
        $hours = now()->diffInHours($this->published_at);
        if ($hours < 24) return $hours . ' hour' . ($hours === 1 ? '' : 's') . ' ago';
        $days = now()->diffInDays($this->published_at);
        if ($days < 7)   return $days . ' day' . ($days === 1 ? '' : 's') . ' ago';
        return $this->published_at->format('M j, Y');
    }

    /**
     * Canonical URL for this article.
     */
    public function getCanonicalUrlAttribute(): string
    {
        $catSlug = $this->category->slug ?? 'news';
        return url("/{$catSlug}/{$this->encode_title}");
    }

    // ─── Hooks ────────────────────────────────────────────────────────────────────

    protected static function boot(): void
    {
        parent::boot();

        static::created(function (News $news) {
            cache()->forget('all_nav_categories');

            $webhookUrl = env('MAKE_WEBHOOK_URL');
            if (!$webhookUrl) return;

            $news->load('category');
            try {
                Http::timeout(5)->post($webhookUrl, [
                    'title'   => $news->news_title_english ?? $news->news_title,
                    'summary' => strip_tags($news->news_content_short_english ?? $news->news_content_short),
                    'url'     => $news->canonical_url,
                ]);
                Log::info('Webhook fired: ' . ($news->news_title_english ?? $news->news_title));
            } catch (\Throwable $e) {
                Log::warning('Webhook failed: ' . $e->getMessage());
            }
        });
    }

    // ─── Scopes ───────────────────────────────────────────────────────────────────

    public function scopePublished($query)
    {
        return $query->whereNotNull('published_at')
                     ->where('published_at', '<=', now());
    }

    public function scopeLatest($query)
    {
        return $query->orderByDesc('published_at')->orderByDesc('news_id');
    }
}
