<?php

namespace App\Models;

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

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.
     */
    public function getPhotoUrlAttribute(): string
    {
        // DB column is `photo_url` — contains the bare filename (e.g. "news-1772608585.webp")
        $filename = $this->attributes['photo_url'] ?? $this->attributes['photo'] ?? null;

        if (!empty($filename)) {
            // Primary location: assets/upload/news/
            if (file_exists(base_path('assets/upload/news/' . $filename))) {
                return asset('assets/upload/news/' . $filename);
            }
            // Fallback location: img/ folder (legacy files)
            if (file_exists(public_path('img/' . $filename))) {
                return asset('img/' . $filename);
            }
        }

        return asset('img/news1.jpg');
    }

    /**
     * Full URL for article banner (detail page hero).
     * We use only one image (photo) — no separate banner needed.
     */
    public function getBannerUrlAttribute(): string
    {
        return $this->photo_url;
    }

    /**
     * Reading-time estimate in minutes.
     */
    public function getReadingTimeAttribute(): int
    {
        $wordCount = str_word_count(strip_tags($this->news_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) {
            // Bust nav category cache on new article
            cache()->forget('all_nav_categories');

            // Optional Make.com webhook for social auto-posting
            $webhookUrl = env('MAKE_WEBHOOK_URL');
            if (!$webhookUrl) return;

            $news->load('category');
            try {
                Http::timeout(5)->post($webhookUrl, [
                    'title'   => $news->news_title,
                    'summary' => strip_tags($news->news_content_short),
                    'url'     => $news->canonical_url,
                ]);
                Log::channel('hindu')->info('Webhook fired: ' . $news->news_title);
            } catch (\Throwable $e) {
                Log::channel('hindu')->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');
    }
}
