<?php

namespace App\Http\Controllers\AdminKampus;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\News; 
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule; 
use Illuminate\Support\Arr; 

class NewsController extends Controller
{
    // Folder penyimpanan di disk 'public'
    private $storageFolder = 'news_images'; 

    // --- Helper Functions ---

    /**
     * Mendefinisikan opsi kategori beserta warna defaultnya.
     */
    private function getCategoryDefinitions(): array
    {
        return [
            'Prestasi' => ['name' => 'Prestasi', 'color' => '#10B981'], // Emerald
            'Pengabdian' => ['name' => 'Pengabdian Masyarakat', 'color' => '#3B82F6'], // Blue
            'Akademik' => ['name' => 'Akademik', 'color' => '#F59E0B'], // Amber
            'Kerjasama' => ['name' => 'Kerjasama', 'color' => '#8B5CF6'], // Violet
            'Lainnya' => ['name' => 'Lainnya', 'color' => '#6B7280'], // Gray
        ];
    }

    /**
     * Helper untuk opsi kategori yang siap dikirim ke Inertia (hanya key => value).
     * Hasilnya: ['Prestasi' => 'Prestasi', ...]
     */
    private function getCategoryOptions(): array
    {
        $definitions = $this->getCategoryDefinitions();
        $options = [];
        
        foreach ($definitions as $key => $details) {
            $options[$key] = $details['name'];
        }

        return $options; 
    }

    /**
     * Mengambil ID Kampus dari user yang sedang login.
     */
    private function getCampusId()
    {
        return Auth::user()->campus_id ?? null; 
    }

    /**
     * Aturan validasi yang disesuaikan untuk CREATE dan UPDATE.
     * @param News|null $news
     */
    private function validationRules(?News $news = null): array
    {
        $categoryOptions = $this->getCategoryOptions();

        $rules = [
            'excerpt' => ['required', 'string', 'max:500'], 
            'content' => ['required', 'string'],
            'category' => ['required', 'string', Rule::in(array_keys($categoryOptions))], 
            'published_at' => 'nullable|date',
            'image_file' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048', 
            // 'remove_image' hanya relevan untuk proses UPDATE
            '_delete_image' => 'nullable|boolean', 
            '_method' => 'in:put', // Tambahkan validasi untuk method spoofing
        ];

        if ($news) {
            // Aturan untuk UPDATE/EDIT: 
            // image_file tidak perlu required jika sudah ada gambar lama atau flag hapus tidak di set.
            $rules['image_file'] = 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048';
            // PENTING: Gunakan nama field yang sama seperti di form Inertia Anda
            $rules['_delete_image'] = 'nullable|boolean'; 
            
            // Hapus requirement image_file jika ada image_url lama dan tidak ada file baru yang diunggah
            if ($news->image_url && !request()->hasFile('image_file')) {
                // Di sini kita tidak menambahkan 'required' untuk image_file karena
                // kondisinya ditangani oleh logika di method update.
            }
        } else {
            // Aturan untuk CREATE
            // Asumsi di Form Create, gambar wajib diisi.
            $rules['image_file'] = 'required|image|mimes:jpeg,png,jpg,webp|max:2048';
        }
        
        return Arr::only($rules, array_keys(request()->all())); // Hanya validasi field yang ada di request
    }

    // --------------------------------------------------------------------------
    // 1. INDEX (READ ALL)
    // --------------------------------------------------------------------------
 public function index()
{
    $campusId = $this->getCampusId();
    if (!$campusId) {
        abort(403, 'Akses ditolak. Pengguna tidak terasosiasi dengan kampus manapun.');
    }

    // Ambil berita berdasarkan kampus dan urutkan berdasarkan tanggal publikasi
    $news = News::where('campus_id', $campusId)
        ->with('user:id,name') 
        ->orderBy('published_at', 'desc')
        ->get();

    // Transformasi data berita
    $news->transform(function ($item) {
        $item->title = $item->excerpt;

        $item->image_url = $item->image_url
            ? (Storage::disk('public')->exists($item->image_url) ? Storage::url($item->image_url) : null)
            : null;

        $item->published_date = $item->published_at ? $item->published_at->format('d M Y') : 'Draft';
        $item->is_published = (bool) $item->published_at;

        return $item;
    });

    // Kategori yang ada di berita
    $categoryOptions = $this->getCategoryOptions();

    return Inertia::render('AdminCampus/Berita/Index', [
        'items' => $news,
        'categoryOptions' => $categoryOptions, // Pastikan kategori dikirim ke view
    ]);
}

    // --------------------------------------------------------------------------
    // 2. CREATE & 3. STORE
    // --------------------------------------------------------------------------
    public function create()
    {
        return Inertia::render('AdminCampus/Berita/Create', [
            'categoryOptions' => $this->getCategoryOptions(),
        ]); 
    }

    public function store(Request $request)
    {
        $campusId = $this->getCampusId();
        if (!$campusId) {
            return redirect()->back()->with('error', 'Gagal menyimpan. Admin tidak terasosiasi dengan kampus.');
        }

        $validatedData = $request->validate($this->validationRules());
        
        $category = $validatedData['category'];
        $colorDefinitions = $this->getCategoryDefinitions();
        $defaultColor = $colorDefinitions[$category]['color'] ?? '#6B7280'; 
        
        try {
            $data = [
                'campus_id' => $campusId,
                'user_id' => Auth::id(),
                'excerpt' => $validatedData['excerpt'],
                'content' => $validatedData['content'],
                'category' => $category,
                'color' => $defaultColor, 
                'published_at' => $validatedData['published_at'] ?? null,
                'image_url' => null, 
            ];
            
            if (empty($data['published_at'])) {
                $data['published_at'] = null;
            }

            // Penanganan File Gambar
            if ($request->hasFile('image_file')) { 
                $imagePath = $request->file('image_file')->store("{$this->storageFolder}/{$campusId}", 'public');
                $data['image_url'] = $imagePath; 
            }
            
            News::create($data);
            
            return redirect()
                ->route('admin.kampus.berita.index')
                ->with('success', "✅ Berita berhasil ditambahkan dengan kategori {$category}."); 

        } catch (\Exception $e) {
            Log::error("Gagal menyimpan Berita Kampus ID: {$campusId}. Error: " . $e->getMessage()); 
            return redirect()
                ->back()
                ->withInput()
                ->with('error', '❌ Gagal menyimpan data. Terjadi kesalahan saat memproses data.');
        }
    }


    // --------------------------------------------------------------------------
    // 4. EDIT (MENAMPILKAN FORM)
    // --------------------------------------------------------------------------
    public function edit(string $id)
    {
        $campusId = $this->getCampusId(); 
        if (!$campusId) {
            abort(403, 'Akses ditolak. Pengguna tidak terasosiasi dengan kampus manapun.');
        }

        // Cek data berita
        $news = News::find($id);

        if (!$news || $news->campus_id !== $campusId) {
            // PENTING: Alihkan (redirect) jika tidak ditemukan. 
            // Ini mencegah error "Cannot read properties of undefined" di React.
            return redirect()->route('admin.kampus.berita.index')
                             ->with('error', 'Berita tidak ditemukan atau Anda tidak memiliki akses.');
        }
        
        // Format URL Gambar
        $news->image_url = $news->image_url && Storage::disk('public')->exists($news->image_url) 
                         ? Storage::url($news->image_url)
                         : null;
        
        $news->title = $news->excerpt; 
        
        // Mengirim data kategori dan data berita yang sudah di-format
        return Inertia::render('AdminCampus/Berita/Edit', [
            // PERBAIKAN: Gunakan nama prop newsData sesuai permintaan di komponen React
            'newsData' => $news, 
            'categoryOptions' => $this->getCategoryOptions(),
        ]);
    }

    // --------------------------------------------------------------------------
    // 5. UPDATE (Mengubah Data)
    // --------------------------------------------------------------------------
    public function update(Request $request, string $id) 
    {
        $campusId = $this->getCampusId();

        if (!$campusId) {
            abort(403, 'Akses ditolak. Pengguna tidak terasosiasi dengan kampus manapun.');
        }

        $news = News::find($id);

        if (!$news || $news->campus_id !== $campusId) {
            return redirect()->route('admin.kampus.berita.index')
                             ->with('error', 'Berita tidak ditemukan atau Anda tidak memiliki akses.');
        }
        
        // Gunakan aturan validasi UPDATE
        $validatedData = $request->validate($this->validationRules($news));
        
        try {
            // Ambil semua data kecuali file, method spoofing, dan flag hapus gambar
            $dataToUpdate = collect($validatedData)->except(['image_file', '_delete_image', '_method'])->all();
            
            // LOGIKA PENGISIAN WARNA OTOMATIS BERDASARKAN KATEGORI (Jika kategori berubah)
            if (isset($dataToUpdate['category']) && $dataToUpdate['category'] !== $news->category) {
                $category = $dataToUpdate['category'];
                $colorDefinitions = $this->getCategoryDefinitions();
                $dataToUpdate['color'] = $colorDefinitions[$category]['color'] ?? '#6B7280';
            }
            
            // Pastikan published_at di set ke null jika dikosongkan
            if (isset($dataToUpdate['published_at']) && empty($dataToUpdate['published_at'])) {
                $dataToUpdate['published_at'] = null;
            }
            
            $oldImagePath = $news->image_url;

            // 2. Penanganan File Gambar
            if ($request->hasFile('image_file')) { 
                $newImagePath = $request->file('image_file')->store("{$this->storageFolder}/{$campusId}", 'public');
                $dataToUpdate['image_url'] = $newImagePath;
                
                // Hapus gambar lama
                if ($oldImagePath && Storage::disk('public')->exists($oldImagePath)) {
                    Storage::disk('public')->delete($oldImagePath);
                }
            } else if (isset($validatedData['_delete_image']) && $validatedData['_delete_image']) {
                // Hapus gambar lama dan set URL ke null (hanya jika flag _delete_image true)
                $dataToUpdate['image_url'] = null;
                if ($oldImagePath && Storage::disk('public')->exists($oldImagePath)) {
                    Storage::disk('public')->delete($oldImagePath);
                }
            } 
            
            // 3. Update data
            $news->update($dataToUpdate);
            
            return redirect()
                ->route('admin.kampus.berita.index')
                ->with('success', "✨ Berita berhasil diperbarui.");

        } catch (\Exception $e) {
            Log::error("Gagal memperbarui Berita ID: {$news->id}. Error: " . $e->getMessage()); 
            
            return redirect()
                ->back()
                ->withInput() 
                ->with('error', '❌ Gagal memperbarui data. Terjadi kesalahan saat memproses data.');
        }
    }

    // --------------------------------------------------------------------------
    // 6. DESTROY (Menghapus Data)
    // --------------------------------------------------------------------------
    public function destroy(string $id) 
    {
        $campusId = $this->getCampusId();
        if (!$campusId) {
            return response()->json(['message' => 'Akses ditolak.'], 403);
        }

        $news = News::find($id);
        if (!$news || $news->campus_id !== $campusId) {
            return response()->json(['message' => 'Akses ditolak. Berita ini bukan milik kampus Anda atau tidak ditemukan.'], 403);
        }
        
        try {
            if ($news->image_url && Storage::disk('public')->exists($news->image_url)) {
                Storage::disk('public')->delete($news->image_url);
            }
            
            $newsExcerpt = substr($news->excerpt, 0, 50) . '...';
            $news->delete();

            return redirect()
                ->route('admin.kampus.berita.index')
                ->with('success', "🗑️ Berita '{$newsExcerpt}' berhasil dihapus.");

        } catch (\Exception $e) {
            Log::error("Gagal menghapus Berita ID: {$news->id}. Error: " . $e->getMessage());
            return redirect()
                ->back()
                ->with('error', '❌ Gagal menghapus berita. Terjadi kesalahan.');
        }
    }

    // --------------------------------------------------------------------------
    // 7. UPDATE STATUS (Publish/Draft)
    // --------------------------------------------------------------------------
    public function updateStatus(Request $request, string $id)
    {
        $campusId = $this->getCampusId();

        if (!$campusId) {
            return response()->json(['message' => 'Akses ditolak.'], 403);
        }

        $news = News::find($id);

        if (!$news || $news->campus_id !== $campusId) {
            return response()->json(['message' => 'Akses ditolak. Berita ini bukan milik kampus Anda atau tidak ditemukan.'], 403);
        }

        $validated = $request->validate([
            'is_published' => 'required|boolean',
        ]);
        
        $isPublished = $validated['is_published'];
        
        try {
            $news->published_at = $isPublished ? now() : null;
            $news->save();

            $statusText = $isPublished ? 'Dipublikasikan' : 'Ditarik ke Draft';
            
            return redirect()
                ->back()
                ->with('success', "Status berita '{$news->excerpt}' berhasil diubah menjadi **{$statusText}**.");
                
        } catch (\Exception $e) {
            Log::error("Gagal mengubah status Berita ID: {$news->id}. Error: " . $e->getMessage());
            return redirect()
                ->back()
                ->with('error', '❌ Gagal mengubah status publikasi.');
        }
    }

}