<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Campus;
use App\Models\SiakadKampus;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator; // Tambahkan ini

class CampusController extends Controller
{
    // Pastikan kolom 'social_media' di model Campus memiliki $casts = ['social_media' => 'array'];

    /**
     * Menampilkan daftar semua kampus. (Read - Index)
     */
    public function index()
    {
        $campuses = Campus::with('siakadCampus:id,nama_kampus')
                            ->select('id', 'siakad_kampus_id', 'slug', 'city', 'province', 'whatsapp_number', 'status')
                            ->latest()
                            ->paginate(10);

        return Inertia::render('SuperAdmin/Kampus/Index', [
            'campuses' => $campuses,
        ]);
    }

    /**
     * Menampilkan formulir pembuatan kampus baru. (Create)
     */
    public function create()
    {
        $siakadCampuses = SiakadKampus::select('id', 'nama_kampus')->orderBy('nama_kampus')->get();

        // Konfigurasi Tema Default
        $defaultTheme = [
            'primaryColor' => 'indigo', 
            'primary' => 'bg-indigo-600', 
            'primaryHover' => 'hover:bg-indigo-700',
            'gradientFrom' => 'from-indigo-600',
            'gradientTo' => 'to-blue-600',
            'textColor' => 'text-indigo-600',
            'activeBg' => 'bg-indigo-700',
            'submenuHoverBg' => 'hover:bg-indigo-700',
            'submenuHoverBgDarker' => 'hover:bg-indigo-800',
            'badgeBg' => 'bg-indigo-100',
            'badgeText' => 'text-indigo-700',
            'copyrightBg' => 'bg-indigo-600',
            'shadowColor' => 'hover:shadow-indigo-200/50',
            'ringColor' => 'focus:ring-indigo-500',
            'borderColor' => 'border-indigo-500',
        ];
        
        return Inertia::render('SuperAdmin/Kampus/Create', [
            'defaultTheme' => $defaultTheme,
            'siakadCampuses' => $siakadCampuses,
        ]);
    }

    /**
     * Menambahkan method untuk mengubah status.
     */
    public function toggleStatus(Campus $campus)
    {
        $newStatus = $campus->status === 'aktif' ? 'non-aktif' : 'aktif';
        
        try {
            $campus->update(['status' => $newStatus]);

            return response()->json([
                'message' => 'Status kampus berhasil diperbarui',
                'status' => $newStatus,
            ]);
        } catch (\Exception $e) {
            Log::error("Failed to toggle campus status: " . $e->getMessage()); 
            
            return response()->json([
                'message' => 'Gagal memperbarui status kampus',
            ], 500);
        }
    }

    /**
     * Menyimpan kampus baru ke database, termasuk upload file gambar. (Create - Store)
     * Menggunakan relative path untuk image URL.
     */
    public function store(Request $request)
    {
        $disk = 'public';
        $imageFields = ['logo_url', 'logo_url_horizontal', 'footer_background_url', 'banner_url'];

        // 1. Definisikan Aturan Validasi
        $rules = [
            'siakad_kampus_id' => [
                'required',
                'integer',
                'unique:campuses,siakad_kampus_id',
                Rule::exists((new SiakadKampus)->getConnectionName() . '.' . (new SiakadKampus)->getTable(), 'id'),
            ],
            'slug' => 'required|string|max:50|unique:campuses,slug|regex:/^[a-z0-9\-]+$/',
            'description' => 'nullable|string',
            
            // ATURAN UNTUK FILE UPLOAD
            'logo_url' => 'nullable|image|mimes:jpeg,png,jpg,webp,svg|max:5120',
            'logo_url_horizontal' => 'nullable|image|mimes:jpeg,png,jpg,webp,svg|max:5120',
            'footer_background_url' => 'nullable|image|mimes:jpeg,png,jpg,webp,svg|max:5120',
            'banner_url' => 'nullable|image|mimes:jpeg,png,jpg,webp,svg|max:5120',
            
            'whatsapp_number' => 'nullable|string|max:20',
            'phone_number' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'address' => 'nullable|string',
            'city' => 'nullable|string|max:100',
            'province' => 'nullable|string|max:100',
            'map_embed_url' => 'nullable|string',
            
            // ATURAN VALIDASI UNTUK MEDIA SOSIAL (Hanya IG, FB, LI) - Data ini seharusnya tidak terkirim di sini
            'facebook_url' => 'nullable|url|max:255',
            'instagram_url' => 'nullable|url|max:255',
            'linkedin_url' => 'nullable|url|max:255',
            
            'theme_config' => 'nullable|string|max:50',
        ];

        // 2. Lakukan Validasi
        $validatedData = $request->validate($rules);
        $dataToStore = $validatedData;
        
        try {
            // 3. LOGIKA PENANGANAN FILE UPLOAD (MENGGUNAKAN RELATIVE PATH)
            foreach ($imageFields as $field) {
                if ($request->hasFile($field)) {
                    $imageFile = $request->file($field);
                    
                    // Tentukan folder penyimpanan: campuses/nama_field/slug-kampus
                    $pathPrefix = "campuses/{$field}/{$validatedData['slug']}";
                    
                    // Simpan file (Laravel akan mengembalikan relative path: e.g., campuses/logo_url/slug/hash.jpg)
                    $path = Storage::disk($disk)->put($pathPrefix, $imageFile);
                    
                    // Ganti objek File dengan relative path (BUKAN URL LENGKAP)
                    $dataToStore[$field] = $path; 
                } else {
                    // Hapus dari dataToStore jika tidak ada file diupload
                    unset($dataToStore[$field]);
                }
            }
            
            // 4. Proses Media Sosial (Kumpulkan dari field terpisah ke kolom social_media)
            $socialMedia = [
                'facebook' => $dataToStore['facebook_url'] ?? null,
                'instagram' => $dataToStore['instagram_url'] ?? null,
                'linkedin' => $dataToStore['linkedin_url'] ?? null,
            ];
            
            // Hapus field terpisah dari dataToStore
            unset($dataToStore['facebook_url'], $dataToStore['instagram_url'], $dataToStore['linkedin_url']);

            // Filter agar hanya URL yang terisi yang disimpan, jika semua kosong, simpan null
            $filteredSocialMedia = array_filter($socialMedia, function($value) {
                return !empty($value);
            });
            $dataToStore['social_media'] = empty($filteredSocialMedia) ? null : $filteredSocialMedia;

            // 5. Tambahkan kolom 'status'
            $dataToStore['status'] = 'aktif'; 

            // 6. Simpan data ke database
            Campus::create($dataToStore);

            // 7. Redirect dengan Flash message success
            return redirect()
                ->route('admin.super.kampus.index')
                ->with('success', '✅ Data Kampus berhasil ditambahkan dan berstatus AKTIF!');
                
        } catch (\Exception $e) {
            Log::error("Failed to store campus data: " . $e->getMessage()); 
            
            return redirect()
                ->back()
                ->withInput()
                ->with('error', '❌ Gagal menambahkan data Kampus. Cek log: ' . $e->getMessage());
        }
    }

    /**
     * Menampilkan data kampus spesifik. (Read - Show)
     */
    public function show(Campus $campus)
    {
        $campus->load('siakadCampus:id,nama_kampus'); 
        
        return Inertia::render('Admin/Campus/Show', [
            'campus' => $campus,
        ]);
    }

    /**
     * Menampilkan formulir pengeditan data kampus. (Read - Edit)
     */
    public function edit($id)
    {
        $campus = Campus::findOrFail($id); 

        $siakadCampuses = SiakadKampus::select('id', 'nama_kampus')->orderBy('nama_kampus')->get();

        $themeColor = $campus->theme_config ?? 'indigo';

        // Konfigurasi tema
        $defaultTheme = [
            'primaryColor' => $themeColor,
            'primary' => "bg-{$themeColor}-600", 
            'primaryHover' => "hover:bg-{$themeColor}-700",
            'gradientFrom' => "from-{$themeColor}-600",
            'gradientTo' => 'to-blue-600',
            'textColor' => "text-{$themeColor}-600",
            'activeBg' => "bg-{$themeColor}-700",
            'submenuHoverBg' => "hover:bg-{$themeColor}-700",
            'submenuHoverBgDarker' => "hover:bg-{$themeColor}-800",
            'badgeBg' => "bg-{$themeColor}-100",
            'badgeText' => "text-{$themeColor}-700",
            'copyrightBg' => "bg-{$themeColor}-600",
            'shadowColor' => "hover:shadow-{$themeColor}-200/50",
            'ringColor' => "focus:ring-{$themeColor}-500",
            'borderColor' => "border-{$themeColor}-500",
        ];
        
        // Memastikan social_media dikirim sebagai object ke frontend
        $campus->social_media = $campus->social_media ?? (object)[];

        return Inertia::render('SuperAdmin/Kampus/Edit', [
            'campus' => $campus,
            'siakadCampuses' => $siakadCampuses,
            'defaultTheme' => $defaultTheme,
        ]);
    }


    /**
     * Mengupdate data kampus yang ada di database, termasuk upload file gambar. (Update)
     * Menggunakan relative path untuk image URL.
     */
    public function update(Request $request, $id)
    {
        $campus = Campus::findOrFail($id); 
        $disk = 'public';
        $imageFields = ['logo_url', 'logo_url_horizontal', 'footer_background_url', 'banner_url'];

        // 1. Aturan validasi yang DIPERBAIKI
        $rules = [
            'siakad_kampus_id' => [
                'required', 'integer',
                Rule::unique('campuses', 'siakad_kampus_id')->ignore($campus->id),
                Rule::exists((new SiakadKampus)->getConnectionName() . '.' . (new SiakadKampus)->getTable(), 'id'),
            ],
            'slug' => [
                'required', 'string', 'max:50', 'regex:/^[a-z0-9\-]+$/',
                Rule::unique('campuses', 'slug')->ignore($campus->id),
            ],
            'description' => 'nullable|string',

            // PERBAIKAN: Gunakan Validator::make() untuk validasi kondisional gambar
            // Hapus validasi gambar dari sini, akan dilakukan secara manual di bawah.
            
            'whatsapp_number' => 'nullable|string|max:20',
            'phone_number' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'address' => 'nullable|string',
            'city' => 'nullable|string|max:100',
            'province' => 'nullable|string|max:100',
            'map_embed_url' => 'nullable|string',
            
            // ATURAN VALIDASI UNTUK MEDIA SOSIAL (Hanya IG, FB, LI)
            'facebook_url' => 'nullable|url|max:255',
            'instagram_url' => 'nullable|url|max:255',
            'linkedin_url' => 'nullable|url|max:255',

            'theme_config' => 'nullable|string|max:50',
            'delete_images' => 'nullable|array',
            'delete_images.*' => Rule::in($imageFields),
            'status' => 'required|in:aktif,nonaktif', // Tambahkan status agar tidak hilang
        ];
        
        // 2. Validasi data non-file
        $validatedData = $request->validate($rules);
        $dataToUpdate = $validatedData;
        
        $oldSlug = $campus->slug;
        $newSlug = $validatedData['slug'];

        try {
            // 3. LOGIKA PENANGANAN FILE UPLOAD, PENGHAPUSAN, dan TIDAK ADA PERUBAHAN
            
            // Loop untuk menangani file/gambar
            foreach ($imageFields as $field) {
                $fileRules = 'nullable|image|mimes:jpeg,png,jpg,webp,svg|max:5120';

                // **VALIDASI KHUSUS GAMBAR**
                if ($request->has($field) && $request->file($field) !== null) {
                    // Hanya lakukan validasi 'image' jika ada file yang di-upload
                    $validator = Validator::make($request->only($field), [
                        $field => $fileRules,
                    ]);
                    
                    if ($validator->fails()) {
                        // Jika validasi file gagal, lempar error ke Inertia
                        return back()->withErrors($validator->errors()->toArray());
                    }
                }
                
                // KASUS A: PENGHAPUSAN EKSPLISIT (delete_images array)
                if (isset($validatedData['delete_images']) && in_array($field, $validatedData['delete_images'])) {
                    $oldPath = $campus->$field;
                    if ($oldPath && Storage::disk($disk)->exists($oldPath)) {
                        Storage::disk($disk)->delete($oldPath);
                    }
                    // Set nilai di database menjadi NULL
                    $dataToUpdate[$field] = null;
                } 
                // KASUS B: UPLOAD FILE BARU / GANTI FILE (hasFile)
                else if ($request->hasFile($field)) {
                    $imageFile = $request->file($field);
                    
                    // a. Hapus file lama jika ada
                    $oldPath = $campus->$field;
                    if ($oldPath && Storage::disk($disk)->exists($oldPath)) {
                        Storage::disk($disk)->delete($oldPath);
                    }

                    // b. Tentukan path penyimpanan: campuses/nama_field/slug-kampus (gunakan slug baru)
                    $pathPrefix = "campuses/{$field}/{$newSlug}";
                    
                    // c. Simpan file baru
                    $path = Storage::disk($disk)->put($pathPrefix, $imageFile);
                    
                    // d. Simpan RELATIVE PATH baru ke data
                    $dataToUpdate[$field] = $path;
                } 
                // KASUS C: TIDAK ADA PERUBAHAN FILE (Tidak diupload dan tidak dihapus)
                else {
                    // HAPUS field ini dari array $dataToUpdate agar nilai lama di DB TIDAK DITIMPA.
                    // Ini menyelesaikan masalah error validasi.
                    unset($dataToUpdate[$field]);
                }
            }
            
            // Hapus array delete_images karena bukan kolom di DB
            unset($dataToUpdate['delete_images']);
            
            // 4. Proses Media Sosial (Kumpulkan dari field terpisah ke kolom social_media)
            $socialMedia = [
                'facebook' => $dataToUpdate['facebook_url'] ?? null,
                'instagram' => $dataToUpdate['instagram_url'] ?? null,
                'linkedin' => $dataToUpdate['linkedin_url'] ?? null,
            ];
            
            // Hapus field terpisah dari dataToUpdate
            unset($dataToUpdate['facebook_url'], $dataToUpdate['instagram_url'], $dataToUpdate['linkedin_url']);

            // Filter agar hanya URL yang terisi yang disimpan, jika semua kosong, simpan null
            $filteredSocialMedia = array_filter($socialMedia, function($value) {
                return !empty($value);
            });
            $dataToUpdate['social_media'] = empty($filteredSocialMedia) ? null : $filteredSocialMedia;

            // 5. Jika slug berubah, pindahkan folder gambar
            if ($oldSlug !== $newSlug) {
                
                // Pindahkan folder utama slug yang lama ke slug yang baru
                foreach ($imageFields as $field) {
                    $oldFieldPath = "campuses/{$field}/{$oldSlug}";
                    $newFieldPath = "campuses/{$field}/{$newSlug}";
                    
                    // Hanya lakukan move jika folder lama ada
                    if (Storage::disk($disk)->exists($oldFieldPath)) {
                        
                        $files = Storage::disk($disk)->files($oldFieldPath);
                        foreach ($files as $file) {
                            $fileName = basename($file);
                            $newFilePath = $newFieldPath . '/' . $fileName;
                            
                            // Pindahkan file
                            Storage::disk($disk)->move($file, $newFilePath);
                            
                            // Update path di $dataToUpdate (untuk file yang tidak diganti dan path-nya masih menggunakan slug lama)
                            if (($campus->$field == $file) && !isset($dataToUpdate[$field])) {
                                $dataToUpdate[$field] = $newFilePath;
                            }
                        }
                        // Hapus folder lama (jika kosong)
                        Storage::disk($disk)->deleteDirectory($oldFieldPath);
                    }
                }
            }
            
            // 6. Update data kampus
            $campus->update($dataToUpdate);

            return redirect()
                ->route('admin.super.kampus.index')
                ->with('success', '✅ Data Kampus berhasil diperbarui!');
        } catch (\Exception $e) {
            Log::error("Gagal memperbarui data kampus: " . $e->getMessage());

            return redirect()
                ->back()
                ->with('error', '❌ Gagal memperbarui data kampus. Terjadi kesalahan. Cek log untuk detail: ' . $e->getMessage());
        }
    }


    /**
     * Menghapus kampus dari database PMB saja, dan semua file gambar terkait.
     */
    public function destroy($id) 
    {
        $campus = Campus::findOrFail($id); 

        $name = $campus->slug;

        try {
            // Hapus semua file gambar terkait kampus
            $imageFields = ['logo_url', 'logo_url_horizontal', 'footer_background_url', 'banner_url'];
            $disk = 'public';

            foreach ($imageFields as $field) {
                $oldPath = $campus->$field;
                if ($oldPath) {
                    if (Storage::disk($disk)->exists($oldPath)) {
                        Storage::disk($disk)->delete($oldPath);
                    }
                }
            }
            
            // Hapus folder utama slug (untuk membersihkan)
            foreach($imageFields as $field) {
                Storage::disk($disk)->deleteDirectory("campuses/{$field}/{$campus->slug}");
            }
            
            // Hapus data kampus dari tabel `campuses`
            $campus->delete();

            Log::info("Campus ID {$id} (SLUG: {$campus->slug}) berhasil dihapus dari PMB. Data Siakad tetap ada.");

            return redirect()
                ->route('admin.super.kampus.index')
                ->with('success', "🗑️ Data Kampus **{$name}** berhasil dihapus dari PMB. File gambar juga dihapus.");
        } catch (\Exception $e) {
            Log::error("Gagal menghapus data kampus dari PMB (ID: {$id}, Slug: {$campus->slug}): " . $e->getMessage());

            return redirect()
                ->back()
                ->with('error', "❌ Gagal menghapus Kampus **{$name}** dari PMB. Terjadi kesalahan. Cek log untuk detail.");
        }
    }
}