<?php

namespace App\Http\Controllers\AdminKampus;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Models\Gallery; // Menggunakan model Gallery
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule; 
use Illuminate\Support\Arr; 

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

    // --- Helper Functions ---

    /**
     * Mendefinisikan opsi kategori untuk Galeri.
     * Warna hanya untuk referensi/tampilan di frontend, tidak disimpan di DB.
     */
    private function getCategoryDefinitions(): array
    {
        return [
            'Fasilitas' => ['name' => 'Fasilitas', 'color' => '#10B981'], 
            'Kegiatan' => ['name' => 'Kegiatan', 'color' => '#3B82F6'], 
            'Prestasi' => ['name' => 'Prestasi', 'color' => '#F59E0B'], 
            'Lainnya' => ['name' => 'Lainnya', 'color' => '#6B7280'],
        ];
    }

    /**
     * Helper untuk opsi kategori yang siap dikirim ke Inertia (hanya key => value).
     */
    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 Gallery|null $gallery
     */
    private function validationRules(?Gallery $gallery = null): array
    {
        $categoryOptions = $this->getCategoryOptions();

        $rules = [
            'title' => ['required', 'string', 'max:255'], 
            'category' => ['required', 'string', Rule::in(array_keys($categoryOptions))], 
            'image_file' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:2048', 
            '_delete_image' => 'nullable|boolean', 
            '_method' => 'in:put', // Validasi untuk method spoofing
        ];

        if (!$gallery) {
            // Aturan untuk CREATE: Gambar wajib diisi
            $rules['image_file'] = 'required|image|mimes:jpeg,png,jpg,webp|max:2048';
        }
        
        // Hanya validasi field yang ada di request
        return Arr::only($rules, array_keys(request()->all())); 
    }

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

        $galleries = Gallery::where('campus_id', $campusId)
            ->orderBy('created_at', 'desc') 
            ->get(); 
            
        $galleries->transform(function ($item) {
            // Menggunakan Storage::url() untuk URL gambar
            $item->image_url = $item->image_path && Storage::disk('public')->exists($item->image_path)
                                ? Storage::url($item->image_path)
                                : null;
            $item->created_date = $item->created_at ? $item->created_at->format('d M Y') : '-';

            return $item;
        });

        return Inertia::render('AdminCampus/Galeri/Index', [
            'items' => $galleries, 
        ]);
    }

    // --------------------------------------------------------------------------
    // 2. CREATE & 3. STORE
    // --------------------------------------------------------------------------
    public function create()
    {
        return Inertia::render('AdminCampus/Galeri/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'];
        
        try {
            $data = [
                'campus_id' => $campusId,
                'title' => $validatedData['title'],
                'category' => $category,
                'image_path' => null, 
            ];
            
            // Penanganan File Gambar
            if ($request->hasFile('image_file')) { 
                $imagePath = $request->file('image_file')->store("{$this->storageFolder}/{$campusId}", 'public');
                $data['image_path'] = $imagePath; 
            }
            
            Gallery::create($data);
            
            return redirect()
                ->route('admin.kampus.galeri.index') 
                ->with('success', "✅ Gambar galeri '{$validatedData['title']}' berhasil ditambahkan."); 

        } catch (\Exception $e) {
            Log::error("Gagal menyimpan Galeri 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.');
        }

        $gallery = Gallery::find($id);

        if (!$gallery || $gallery->campus_id !== $campusId) {
            return redirect()->route('admin.kampus.galeri.index')
                             ->with('error', 'Gambar galeri tidak ditemukan atau Anda tidak memiliki akses.');
        }
        
        // Menggunakan Storage::url() untuk URL gambar saat ini
        $gallery->current_image_url = $gallery->image_path && Storage::disk('public')->exists($gallery->image_path)
                                     ? Storage::url($gallery->image_path)
                                     : null;
        
        // Mengirim data kategori dan data galeri yang sudah di-format
        return Inertia::render('AdminCampus/Galeri/Edit', [
            'itemData' => $gallery, 
            '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.');
        }

        $gallery = Gallery::find($id);

        if (!$gallery || $gallery->campus_id !== $campusId) {
            return redirect()->route('admin.kampus.galeri.index')
                             ->with('error', 'Gambar galeri tidak ditemukan atau Anda tidak memiliki akses.');
        }
        
        $validatedData = $request->validate($this->validationRules($gallery));
        
        try {
            // Ambil semua data kecuali file, method spoofing, dan flag hapus gambar
            $dataToUpdate = collect($validatedData)->except(['image_file', '_delete_image', '_method'])->all();
            
            $oldImagePath = $gallery->image_path;

            // KARENA MODEL GALLERY TIDAK ADA KOLOM COLOR, LOGIKA WARNA DIHILANGKAN DI SINI.

            // Penanganan File Gambar
            if ($request->hasFile('image_file')) { 
                $newImagePath = $request->file('image_file')->store("{$this->storageFolder}/{$campusId}", 'public');
                $dataToUpdate['image_path'] = $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 path ke null (hanya jika flag _delete_image true)
                $dataToUpdate['image_path'] = null;
                if ($oldImagePath && Storage::disk('public')->exists($oldImagePath)) {
                    Storage::disk('public')->delete($oldImagePath);
                }
            } else {
                 // Jika tidak ada file baru dan tidak ada penghapusan, biarkan Laravel mengabaikan kolom 'image_path'
                 // jika tidak ada perubahan pada path, kecuali jika kita secara eksplisit ingin mempertahankannya:
                 if (!isset($dataToUpdate['image_path'])) {
                     unset($dataToUpdate['image_path']); // Biarkan Laravel hanya mengupdate title dan category
                 }
            }
            
            // Update data
            $gallery->update($dataToUpdate);
            
            return redirect()
                ->route('admin.kampus.galeri.index')
                ->with('success', "✨ Gambar galeri berhasil diperbarui.");

        } catch (\Exception $e) {
            Log::error("Gagal memperbarui Galeri ID: {$gallery->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);
        }

        $gallery = Gallery::find($id);
        if (!$gallery || $gallery->campus_id !== $campusId) {
            return response()->json(['message' => 'Akses ditolak. Gambar ini bukan milik kampus Anda atau tidak ditemukan.'], 403);
        }
        
        try {
            $galleryTitle = substr($gallery->title, 0, 50) . '...';
            
            // Hapus gambar dari storage
            if ($gallery->image_path && Storage::disk('public')->exists($gallery->image_path)) {
                Storage::disk('public')->delete($gallery->image_path);
            }
            
            $gallery->delete();

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

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