<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Siswa;
use App\Models\Alumni;
use App\Models\ActivityLog;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;

class PetugasDashboardController extends Controller
{
    /**
     * Display the Petugas dashboard.
     */
    public function index()
    {
        $siswa = Siswa::orderBy('nis', 'desc')->get();
        $alumni = Alumni::orderBy('id_alumni', 'desc')->get();
        $pengumuman = \App\Models\Pengumuman::orderBy('id_pengumuman', 'desc')->get();
        $galeri = \App\Models\Galeri::orderBy('id_galeri', 'desc')->get();
        $guru = \App\Models\Guru::orderBy('nip', 'desc')->get();
        $profilJurusan = \App\Models\ProfilJurusan::first();
        $petugasName = Auth::guard('petugas')->user()->nama_petugas;

        return view('dashboard.petugas', compact('siswa', 'alumni', 'pengumuman', 'galeri', 'guru', 'profilJurusan', 'petugasName'));
    }



    /**
     * Update the specified student in storage.
     */
    public function updateSiswa(Request $request, $nis)
    {
        $siswa = Siswa::findOrFail($nis);

        $request->validate([
            'nama_siswa' => 'required|string|max:100',
            'kelas' => 'required|string|max:50',
            'jk' => 'required|in:laki-laki,perempuan',
            'alamat' => 'required|string|max:255',
            'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $fotoPath = $siswa->foto;
        if ($request->hasFile('foto')) {
            // Delete old file if exists
            if ($siswa->foto && $siswa->foto !== 'default_avatar.png' && file_exists(public_path($siswa->foto))) {
                @unlink(public_path($siswa->foto));
            }

            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/siswa'), $filename);
            $fotoPath = 'uploads/siswa/' . $filename;
        }

        $siswa->update([
            'nama_siswa' => $request->nama_siswa,
            'kelas' => $request->kelas,
            'jk' => $request->jk,
            'alamat' => $request->alamat,
            'foto' => $fotoPath,
        ]);

        // Catat aktifitas
        $user = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $user->nama_petugas,
            'user_id' => $user->id_petugas,
            'activity' => 'Memperbarui data Siswa: ' . $siswa->nama_siswa . ' (NIS: ' . $siswa->nis . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Data siswa berhasil diperbarui!');
    }

    /**
     * Remove the specified student from storage.
     */
    public function destroySiswa(Request $request, $nis)
    {
        $siswa = Siswa::findOrFail($nis);
        $namaSiswa = $siswa->nama_siswa;

        // Delete photo
        if ($siswa->foto && $siswa->foto !== 'default_avatar.png' && file_exists(public_path($siswa->foto))) {
            @unlink(public_path($siswa->foto));
        }

        $siswa->delete();

        // Catat aktifitas
        $user = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $user->nama_petugas,
            'user_id' => $user->id_petugas,
            'activity' => 'Menghapus data Siswa: ' . $namaSiswa . ' (NIS: ' . $nis . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Siswa berhasil dihapus!');
    }

    /**
     * Update the specified alumni in storage.
     */
    public function updateAlumni(Request $request, $id)
    {
        $alumni = Alumni::findOrFail($id);

        $request->validate([
            'nama' => 'required|string|max:200',
            'tahun_lulus' => 'required|integer|min:1900|max:' . (date('Y') + 1),
            'kelanjutan' => 'required|in:kerja,kuliah',
            'tempat' => 'required|string|max:150',
            'jabatan' => 'required|string|max:100',
            'testimoni' => 'required|string',
            'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $fotoPath = $alumni->foto;
        if ($request->hasFile('foto')) {
            if ($alumni->foto && $alumni->foto !== 'default_alumni.jpg' && file_exists(public_path($alumni->foto))) {
                @unlink(public_path($alumni->foto));
            }

            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/alumni'), $filename);
            $fotoPath = 'uploads/alumni/' . $filename;
        }

        $alumni->update([
            'nama' => $request->nama,
            'tahun_lulus' => $request->tahun_lulus,
            'kelanjutan' => $request->kelanjutan,
            'tempat' => $request->tempat,
            'jabatan' => $request->jabatan,
            'testimoni' => $request->testimoni,
            'foto' => $fotoPath,
        ]);

        // Catat aktifitas
        $user = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $user->nama_petugas,
            'user_id' => $user->id_petugas,
            'activity' => 'Memperbarui data Alumni: ' . $alumni->nama . ' (ID: ' . $alumni->id_alumni . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Data alumni berhasil diperbarui!');
    }

    /**
     * Remove the specified alumni from storage.
     */
    public function destroyAlumni(Request $request, $id)
    {
        $alumni = Alumni::findOrFail($id);
        $namaAlumni = $alumni->nama;

        if ($alumni->foto && $alumni->foto !== 'default_alumni.jpg' && file_exists(public_path($alumni->foto))) {
            @unlink(public_path($alumni->foto));
        }

        $alumni->delete();

        // Catat aktifitas
        $user = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $user->nama_petugas,
            'user_id' => $user->id_petugas,
            'activity' => 'Menghapus data Alumni: ' . $namaAlumni . ' (ID: ' . $id . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Alumni berhasil dihapus!');
    }

    /**
     * Update current Petugas's own profile.
     */
    public function updateProfile(Request $request)
    {
        $petugas = Auth::guard('petugas')->user();

        $request->validate([
            'nama_petugas' => 'required|string|max:100',
            'username' => 'required|string|max:100|unique:petugas,username,' . $petugas->id_petugas . ',id_petugas',
            'password' => 'nullable|string|min:6',
            'jabatan' => 'required|string|max:100',
            'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $fotoPath = $petugas->foto;
        if ($request->hasFile('foto')) {
            if ($petugas->foto && $petugas->foto !== 'default_petugas.jpg' && file_exists(public_path($petugas->foto))) {
                @unlink(public_path($petugas->foto));
            }

            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/petugas'), $filename);
            $fotoPath = 'uploads/petugas/' . $filename;
        }

        $updateData = [
            'nama_petugas' => $request->nama_petugas,
            'username' => $request->username,
            'jabatan' => $request->jabatan,
            'foto' => $fotoPath,
        ];

        if ($request->filled('password')) {
            $updateData['password'] = \Illuminate\Support\Facades\Hash::make($request->password);
        }

        // Eloquent update
        \App\Models\Petugas::where('id_petugas', $petugas->id_petugas)->update($updateData);

        // Log activity
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $request->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Memperbarui profil pribadinya',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Profil Anda berhasil diperbarui!');
    }

    /**
     * Store a newly created announcement.
     */
    public function storePengumuman(Request $request)
    {
        $request->validate([
            'judul' => 'required|string|max:200',
            'isi' => 'required|string',
        ]);

        $petugas = Auth::guard('petugas')->user();

        $pengumuman = \App\Models\Pengumuman::create([
            'judul' => $request->judul,
            'isi' => $request->isi,
            'tanggal' => date('Y-m-d'),
            'id_petugas' => $petugas->id_petugas
        ]);

        // Log activity
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Membuat pengumuman baru: "' . $pengumuman->judul . '"',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Pengumuman baru berhasil dipublikasikan!');
    }

    /**
     * Update an announcement.
     */
    public function updatePengumuman(Request $request, $id)
    {
        $pengumuman = \App\Models\Pengumuman::findOrFail($id);

        $request->validate([
            'judul' => 'required|string|max:200',
            'isi' => 'required|string',
        ]);

        $pengumuman->update([
            'judul' => $request->judul,
            'isi' => $request->isi,
            'tanggal' => date('Y-m-d')
        ]);

        // Log activity
        $petugas = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Memperbarui pengumuman: "' . $pengumuman->judul . '"',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Pengumuman berhasil diperbarui!');
    }

    /**
     * Delete an announcement.
     */
    public function destroyPengumuman(Request $request, $id)
    {
        $pengumuman = \App\Models\Pengumuman::findOrFail($id);
        $judul = $pengumuman->judul;

        $pengumuman->delete();

        // Log activity
        $petugas = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Menghapus pengumuman: "' . $judul . '"',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Pengumuman berhasil dihapus!');
    }

    /**
     * Store a newly created gallery item.
     */
    public function storeGaleri(Request $request)
    {
        $request->validate([
            'judul' => 'required|string|max:100',
            'deskripsi' => 'required|string',
            'foto' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $fotoPath = '';
        if ($request->hasFile('foto')) {
            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/galeri'), $filename);
            $fotoPath = 'uploads/galeri/' . $filename;
        }

        $petugas = Auth::guard('petugas')->user();

        $galeri = \App\Models\Galeri::create([
            'id_petugas' => $petugas->id_petugas,
            'judul' => $request->judul,
            'foto' => $fotoPath,
            'deskripsi' => $request->deskripsi,
            'tanggal_kegiatan' => date('Y-m-d')
        ]);

        // Log activity
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Menambahkan foto galeri baru: "' . $galeri->judul . '"',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Foto galeri baru berhasil ditambahkan!');
    }

    /**
     * Update a gallery item.
     */
    public function updateGaleri(Request $request, $id)
    {
        $galeri = \App\Models\Galeri::findOrFail($id);

        $request->validate([
            'judul' => 'required|string|max:100',
            'deskripsi' => 'required|string',
            'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $fotoPath = $galeri->foto;
        if ($request->hasFile('foto')) {
            // Delete old file
            if ($galeri->foto && file_exists(public_path($galeri->foto))) {
                @unlink(public_path($galeri->foto));
            }

            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/galeri'), $filename);
            $fotoPath = 'uploads/galeri/' . $filename;
        }

        $galeri->update([
            'judul' => $request->judul,
            'deskripsi' => $request->deskripsi,
            'foto' => $fotoPath,
            'tanggal_kegiatan' => date('Y-m-d')
        ]);

        // Log activity
        $petugas = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Memperbarui foto galeri: "' . $galeri->judul . '"',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Foto galeri berhasil diperbarui!');
    }

    /**
     * Delete a gallery item.
     */
    public function destroyGaleri(Request $request, $id)
    {
        $galeri = \App\Models\Galeri::findOrFail($id);
        $judul = $galeri->judul;

        if ($galeri->foto && file_exists(public_path($galeri->foto))) {
            @unlink(public_path($galeri->foto));
        }

        $galeri->delete();

        // Log activity
        $petugas = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Menghapus foto galeri: "' . $judul . '"',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Foto galeri berhasil dihapus!');
    }

    /**
     * Store a newly created teacher.
     */
    public function storeGuru(Request $request)
    {
        $request->validate([
            'nip' => 'required|integer|unique:guru,nip',
            'nama_guru' => 'required|string|max:100',
            'mapel' => 'required|string|max:200',
            'jabatan' => 'required|string|max:200',
            'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $fotoPath = 'default_guru.jpg';
        if ($request->hasFile('foto')) {
            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/guru'), $filename);
            $fotoPath = 'uploads/guru/' . $filename;
        }

        $profil = \App\Models\ProfilJurusan::first();
        $profilId = $profil ? $profil->id_profil : 1;

        $guru = \App\Models\Guru::create([
            'nip' => $request->nip,
            'id_profil' => $profilId,
            'nama_guru' => $request->nama_guru,
            'mapel' => $request->mapel,
            'jabatan' => $request->jabatan,
            'foto' => $fotoPath,
        ]);

        // Log activity
        $petugas = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Menambahkan Guru baru: ' . $guru->nama_guru . ' (NIP: ' . $guru->nip . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Data Guru baru berhasil ditambahkan!');
    }

    /**
     * Update an existing teacher.
     */
    public function updateGuru(Request $request, $nip)
    {
        $guru = \App\Models\Guru::findOrFail($nip);

        $request->validate([
            'nama_guru' => 'required|string|max:100',
            'mapel' => 'required|string|max:200',
            'jabatan' => 'required|string|max:200',
            'foto' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $fotoPath = $guru->foto;
        if ($request->hasFile('foto')) {
            if ($guru->foto && $guru->foto !== 'default_guru.jpg' && file_exists(public_path($guru->foto))) {
                @unlink(public_path($guru->foto));
            }

            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/guru'), $filename);
            $fotoPath = 'uploads/guru/' . $filename;
        }

        $guru->update([
            'nama_guru' => $request->nama_guru,
            'mapel' => $request->mapel,
            'jabatan' => $request->jabatan,
            'foto' => $fotoPath,
        ]);

        // Log activity
        $petugas = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Memperbarui data Guru: ' . $guru->nama_guru . ' (NIP: ' . $nip . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Data Guru berhasil diperbarui!');
    }

    /**
     * Delete an existing teacher.
     */
    public function destroyGuru(Request $request, $nip)
    {
        $guru = \App\Models\Guru::findOrFail($nip);
        $namaGuru = $guru->nama_guru;

        if ($guru->foto && $guru->foto !== 'default_guru.jpg' && file_exists(public_path($guru->foto))) {
            @unlink(public_path($guru->foto));
        }

        $guru->delete();

        // Log activity
        $petugas = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Menghapus data Guru: ' . $namaGuru . ' (NIP: ' . $nip . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Data Guru berhasil dihapus!');
    }

    /**
     * Bulk delete selected teachers.
     */
    public function bulkDestroyGuru(Request $request)
    {
        $request->validate([
            'selected_nip' => 'required|array|min:1',
            'selected_nip.*' => 'required|numeric',
        ]);

        $nips = $request->input('selected_nip', []);
        $gurus = \App\Models\Guru::whereIn('nip', $nips)->get();
        $deletedCount = 0;

        foreach ($gurus as $guru) {
            if ($guru->foto && $guru->foto !== 'default_guru.jpg' && file_exists(public_path($guru->foto))) {
                @unlink(public_path($guru->foto));
            }
            $guru->delete();
            $deletedCount++;
        }

        $petugas = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Menghapus ' . $deletedCount . ' data Guru secara massal',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Berhasil menghapus ' . $deletedCount . ' data Guru.');
    }

    /**
     * Export guru data as JSON file.
     */
    public function exportGuru(Request $request)
    {
        $guru = \App\Models\Guru::orderBy('nip')->get(['nip', 'id_profil', 'nama_guru', 'mapel', 'jabatan', 'foto'])->toArray();
        $filename = 'guru_export_' . date('Ymd_His') . '.json';
        $json = json_encode($guru, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

        return response()->streamDownload(function () use ($json) {
            echo $json;
        }, $filename, [
            'Content-Type' => 'application/json',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"'
        ]);
    }

    /**
     * Import guru data from uploaded JSON file.
     */
    public function importGuru(Request $request)
    {
        $request->validate([
            'guru_file' => 'required|file',
        ]);

        $file = $request->file('guru_file');
        $content = file_get_contents($file->getRealPath());
        $data = json_decode($content, true, 512, JSON_BIGINT_AS_STRING);

        if (!is_array($data)) {
            return redirect()->route('petugas.dashboard')->with('error', 'File JSON tidak valid atau format tidak sesuai.');
        }

        DB::beginTransaction();
        try {
            $count = 0;
            $profilDefault = \App\Models\ProfilJurusan::first();
            $defaultProfilId = $profilDefault ? $profilDefault->id_profil : 1;

            foreach ($data as $item) {
                if (!isset($item['nip']) || !isset($item['nama_guru']) || !isset($item['mapel']) || !isset($item['jabatan'])) {
                    throw new \Exception('Setiap record harus memiliki field: nip, nama_guru, mapel, jabatan');
                }

                $nip = (string) $item['nip'];
                if (!ctype_digit($nip) || (int) $nip <= 0) {
                    continue; // skip invalid NIP entries
                }

                $profilId = $defaultProfilId;
                if (isset($item['id_profil']) && is_numeric($item['id_profil'])) {
                    $foundProfil = \App\Models\ProfilJurusan::find((int) $item['id_profil']);
                    if ($foundProfil) {
                        $profilId = $foundProfil->id_profil;
                    }
                }

                $payload = [
                    'id_profil' => $profilId,
                    'nama_guru' => $item['nama_guru'],
                    'mapel' => $item['mapel'],
                    'jabatan' => $item['jabatan'],
                    'foto' => $item['foto'] ?? 'default_guru.jpg',
                ];

                \App\Models\Guru::updateOrCreate(['nip' => $nip], array_merge(['nip' => $nip], $payload));
                $count++;
            }

            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            return redirect()->route('petugas.dashboard')->with('error', 'Import gagal: ' . $e->getMessage());
        }

        // Log activity
        $petugas = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Mengimpor data Guru dari JSON (' . $count . ' record)',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Import berhasil: ' . $count . ' record diproses.');
    }

    /**
     * Update Profil Jurusan content.
     */
    public function updateKonten(Request $request)
    {
        $request->validate([
            'nama_jurusan' => 'required|string|max:100',
            'deskripsi' => 'required|string',
            'visi' => 'required|string',
            'misi' => 'required|string',
        ]);

        $profil = \App\Models\ProfilJurusan::first();

        if (!$profil) {
            $profil = \App\Models\ProfilJurusan::create([
                'nama_jurusan' => $request->nama_jurusan,
                'deskripsi' => $request->deskripsi,
                'visi' => $request->visi,
                'misi' => $request->misi,
            ]);
        } else {
            $profil->update([
                'nama_jurusan' => $request->nama_jurusan,
                'deskripsi' => $request->deskripsi,
                'visi' => $request->visi,
                'misi' => $request->misi,
            ]);
        }

        // Log activity
        $petugas = Auth::guard('petugas')->user();
        ActivityLog::create([
            'user_type' => 'Petugas',
            'user_name' => $petugas->nama_petugas,
            'user_id' => $petugas->id_petugas,
            'activity' => 'Memperbarui konten Profil Jurusan: ' . $profil->nama_jurusan,
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('petugas.dashboard')->with('success', 'Konten Profil Jurusan berhasil diperbarui!');
    }
}
