<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Support\Facades\Storage;
use App\Models\News; 
use App\Models\Campus; 
use App\Http\Controllers\LandingPageController; 

class NewsController extends Controller
{
    /**
     * Helper untuk mendapatkan URL lengkap dari path penyimpanan.
     * @param string|null $path
     * @return string|null
     */
    private static function getFullImageUrl($path)
    {
        if ($path) {
            if (filter_var($path, FILTER_VALIDATE_URL)) {
                return $path;
            }
            // Menggunakan asset('storage/') lebih aman dan sesuai standar Laravel
            return asset('storage/' . $path); 
        }
        return null;
    }

    /**
     * Mengambil daftar berita (ringkasan) dari database berdasarkan slug kampus.
     * @param string $slug Slug kampus (e.g., 'akbid', 'umiba')
     * @return \Illuminate\Support\Collection
     */
    public static function getNewsDataBySlug(string $slug)
    {
        $normalizedSlug = strtolower($slug);

        // 1. Cari Campus ID berdasarkan Slug
        $campus = Campus::where('slug', $normalizedSlug)->first();

        if (!$campus) {
            return collect([]);
        }

        // 2. Query Berita yang Sudah Dipublikasikan, TERMASUK kolom 'color'
        $newsList = News::where('campus_id', $campus->id)
                      ->whereNotNull('published_at') 
                      // Kolom 'color' harus disertakan di sini!
                      ->select('id', 'excerpt', 'category', 'color', 'published_at', 'image_url') 
                      ->orderBy('published_at', 'desc')
                      ->get();

        // 3. Memformat data
        return $newsList->map(function ($item) use ($slug) {
            
            $item->imageUrl = self::getFullImageUrl($item->image_url);
            $item->date = $item->published_at ? $item->published_at->format('d F Y') : null;
            $item->title = $item->excerpt;
            
            try {
                $item->url = route('campus.berita.detail', ['slug' => $slug, 'id' => $item->id]);
            } catch (\Exception $e) {
                $item->url = "/{$slug}/berita/{$item->id}";
            }
            
            // Properti 'color' sudah ada di item dan akan otomatis terkirim
            unset($item->published_at, $item->excerpt, $item->image_url);

            return $item;
        });
    }

    /**
     * Mengambil detail berita spesifik berdasarkan slug dan ID.
     * @param string $slug
     * @param int $id
     * @return array|null
     */
    public static function getNewsDetailBySlug(string $slug, int $id): ?array
    {
        $normalizedSlug = strtolower($slug);
        $campus = Campus::where('slug', $normalizedSlug)->first();

        if (!$campus) {
            return null;
        }

        // Cari berita spesifik
        $newsItem = News::where('campus_id', $campus->id)
                        ->where('id', $id)
                        ->whereNotNull('published_at')
                        ->first();

        if (!$newsItem) {
            return null;
        }

        // 3. Memformat item detail (pastikan 'color' ada di sini juga)
        $formattedItem = $newsItem->toArray();
        $formattedItem['imageUrl'] = self::getFullImageUrl($newsItem->image_url);
        $formattedItem['date'] = $newsItem->published_at ? $newsItem->published_at->format('d F Y') : null;
        $formattedItem['title'] = $newsItem->excerpt;
        
        try {
            $formattedItem['url'] = route('campus.berita.detail', ['slug' => $slug, 'id' => $id]);
        } catch (\Exception $e) {
            $formattedItem['url'] = "/{$slug}/berita/{$id}";
        }
        
        // Hapus properti DB asli yang tidak diperlukan di frontend
        unset($formattedItem['published_at'], $formattedItem['image_url'], $formattedItem['excerpt'], $formattedItem['campus_id'], $formattedItem['user_id']);


        return $formattedItem;
    }


    /**
     * Menampilkan halaman arsip berita (BeritaPage.jsx) untuk kampus tertentu.
     */
    public function show($slug)
    {
        $campusData = LandingPageController::getBaseCampusData($slug);
        
        if (!$campusData) {
            abort(404, "Data kampus tidak ditemukan untuk slug: " . $slug);
        }

        $newsData = self::getNewsDataBySlug($slug)->all(); 

        return Inertia::render('BeritaPage', [
            'campus' => $campusData,
            'news' => $newsData, // Data daftar berita (termasuk properti 'color')
        ]);
    }

    /**
     * Menampilkan halaman detail berita (BeritaDetailPage.jsx)
     */
    public function showDetail($slug, $id)
    {
        $campusData = LandingPageController::getBaseCampusData($slug); 
        
        if (!$campusData) {
            abort(404, "Data kampus tidak ditemukan untuk slug: " . $slug);
        }
        
        $newsItem = self::getNewsDetailBySlug($slug, (int)$id);
        
        if (!$newsItem) {
            abort(404, 'Berita tidak ditemukan atau belum dipublikasi.');
        }

        // Ambil 4 berita lainnya untuk sidebar
        $allNewsList = self::getNewsDataBySlug($slug);
        
        $newsList = $allNewsList
                         ->reject(fn ($item) => $item['id'] == (int)$id)
                         ->take(4) 
                         ->values()
                         ->all();

        return Inertia::render('BeritaDetailPage', [
            'campus' => $campusData,
            'newsItem' => $newsItem, // Item berita detail (termasuk properti 'color')
            'newsList' => $newsList, // Daftar berita lain untuk sidebar
        ]);
    }
}