<?php

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Admin;
use App\Models\Petugas;
use App\Models\Alumni;
use App\Models\Siswa;
use App\Models\ActivityLog;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class AdminDashboardController extends Controller
{
    /**
     * Display the Admin Dashboard with Stats, Logs, and Petugas/Admin/Alumni/Siswa lists.
     */
    public function index()
    {
        // 1. Get statistics counters
        $stats = [
            'total_admin' => Admin::count(),
            'total_petugas' => Petugas::count(),
            'total_alumni' => Alumni::count(),
            'total_siswa' => Siswa::count(),
            'total_guru' => \App\Models\Guru::count(),
            'total_logs' => ActivityLog::count(),
        ];

        // 2. Fetch logs ordered by latest
        $logs = ActivityLog::orderBy('id', 'desc')->get();

        // 3. Fetch all officers (Petugas)
        $petugas = Petugas::orderBy('id_petugas', 'desc')->get();

        // 4. Fetch all Admins
        $admins = Admin::orderBy('id_admin', 'desc')->get();

        // 5. Fetch all Alumni
        $alumni = Alumni::orderBy('id_alumni', 'desc')->get();

        // 6. Fetch all Siswa
        $siswa = Siswa::orderBy('nis', 'desc')->get();

        // 7. Fetch all Guru
        $guru = \App\Models\Guru::orderBy('nip', 'desc')->get();

        $currentAdmin = Auth::guard('admin')->user();
        $adminName = $currentAdmin->nama_admin;

        return view('dashboard.admin', compact('stats', 'logs', 'petugas', 'admins', 'alumni', 'siswa', 'guru', 'currentAdmin', 'adminName'));
    }

    /**
     * Clear all system activity logs.
     */
    public function clearLogs(Request $request)
    {
        ActivityLog::truncate();

        // Log the clear action itself
        $user = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $user->nama_admin,
            'user_id' => $user->id_admin,
            'activity' => 'Membersihkan seluruh LOG AKTIFITAS sistem',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('admin.dashboard')->with('success', 'Terminal log berhasil dibersihkan!');
    }

    /**
     * Create a new Petugas officer account.
     */
    public function storePetugas(Request $request)
    {
        $request->validate([
            'nama_petugas' => 'required|string|max:100',
            'username' => 'required|string|max:100|unique:petugas,username',
            'password' => 'required|string|min:6',
            'jabatan' => 'required|string|max:100',
        ]);

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

        $petugas = Petugas::create([
            'nama_petugas' => $request->nama_petugas,
            'username' => $request->username,
            'password' => Hash::make($request->password),
            'jabatan' => $request->jabatan,
            'foto' => 'default_petugas.jpg',
            'id_admin' => $admin->id_admin,
        ]);

        // Log activity
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Mendaftarkan Petugas baru: ' . $petugas->nama_petugas . ' (Username: ' . $petugas->username . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('admin.dashboard')->with('success', 'Akun Petugas baru berhasil didaftarkan!');
    }

    /**
     * Update an existing Petugas account.
     */
    public function updatePetugas(Request $request, $id)
    {
        $petugas = Petugas::findOrFail($id);

        $request->validate([
            'nama_petugas' => 'required|string|max:100',
            'username' => 'required|string|max:100|unique:petugas,username,' . $id . ',id_petugas',
            'password' => 'nullable|string|min:6',
            'jabatan' => 'required|string|max:100',
        ]);

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

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

        $petugas->update($updateData);

        // Log activity
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Memperbarui akun Petugas: ' . $petugas->nama_petugas . ' (ID: ' . $id . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('admin.dashboard')->with('success', 'Data akun Petugas berhasil diperbarui!');
    }

    /**
     * Remove a Petugas account.
     */
    public function destroyPetugas(Request $request, $id)
    {
        $petugas = Petugas::findOrFail($id);
        $namaPetugas = $petugas->nama_petugas;

        $petugas->delete();

        // Log activity
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Menghapus akun Petugas: ' . $namaPetugas . ' (ID: ' . $id . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('admin.dashboard')->with('success', 'Akun Petugas berhasil dihapus!');
    }

    /**
     * Update an existing Admin account.
     */
    public function updateAdmin(Request $request, $id)
    {
        $targetAdmin = Admin::findOrFail($id);

        $request->validate([
            'nama_admin' => 'required|string|max:100',
            'username' => 'required|string|max:100|unique:admin,username,' . $id . ',id_admin',
            'password' => 'nullable|string|min:6',
        ]);

        $updateData = [
            'nama_admin' => $request->nama_admin,
            'username' => $request->username,
        ];

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

        $targetAdmin->update($updateData);

        // Log activity
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Memperbarui akun Admin: ' . $targetAdmin->nama_admin . ' (ID: ' . $id . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('admin.dashboard')->with('success', 'Data akun Admin berhasil diperbarui!');
    }

    /**
     * Remove an Admin account.
     */
    public function destroyAdmin(Request $request, $id)
    {
        $admin = Auth::guard('admin')->user();
        if ($admin->id_admin == $id) {
            return redirect()->route('admin.dashboard')->withErrors(['error' => 'Anda tidak dapat menghapus akun Anda sendiri!']);
        }

        $targetAdmin = Admin::findOrFail($id);
        $namaAdmin = $targetAdmin->nama_admin;
        $targetAdmin->delete();

        // Log activity
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Menghapus akun Admin: ' . $namaAdmin . ' (ID: ' . $id . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('admin.dashboard')->with('success', 'Akun Admin berhasil dihapus!');
    }

    /**
     * Store a newly created Alumni.
     */
    public function storeAlumni(Request $request)
    {
        $request->validate([
            'nama' => 'required|string|max:200',
            'username' => 'required|string|max:100|unique:alumni,username',
            'password' => 'required|string|min:6',
            '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 = 'default_alumni.jpg';
        if ($request->hasFile('foto')) {
            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/alumni'), $filename);
            $fotoPath = 'uploads/alumni/' . $filename;
        }

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

        $alumni = Alumni::create([
            'id_profil' => $profilId,
            'nama' => $request->nama,
            'username' => $request->username,
            'password' => Hash::make($request->password),
            'tahun_lulus' => $request->tahun_lulus,
            'kelanjutan' => $request->kelanjutan,
            'tempat' => $request->tempat,
            'jabatan' => $request->jabatan,
            'testimoni' => $request->testimoni,
            'foto' => $fotoPath,
        ]);

        // Log activity
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Mendaftarkan Alumni baru: ' . $alumni->nama . ' (Username: ' . $alumni->username . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('admin.dashboard')->with('success', 'Akun Alumni baru berhasil terdaftar!');
    }

    /**
     * Update an existing Alumni.
     */
    public function updateAlumni(Request $request, $id)
    {
        $alumni = Alumni::findOrFail($id);

        $request->validate([
            'nama' => 'required|string|max:200',
            'username' => 'required|string|max:100|unique:alumni,username,' . $id . ',id_alumni',
            'password' => 'nullable|string|min:6',
            '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;
        }

        $updateData = [
            'nama' => $request->nama,
            'username' => $request->username,
            'tahun_lulus' => $request->tahun_lulus,
            'kelanjutan' => $request->kelanjutan,
            'tempat' => $request->tempat,
            'jabatan' => $request->jabatan,
            'testimoni' => $request->testimoni,
            'foto' => $fotoPath,
        ];

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

        $alumni->update($updateData);

        // Log activity
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Memperbarui data Alumni: ' . $alumni->nama . ' (ID: ' . $id . ')',
            'ip_address' => $request->ip()
        ]);

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

    /**
     * Remove an Alumni.
     */
    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();

        // Log activity
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Menghapus data Alumni: ' . $namaAlumni . ' (ID: ' . $id . ')',
            'ip_address' => $request->ip()
        ]);

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

    /**
     * Store a newly created Siswa.
     */
    public function storeSiswa(Request $request)
    {
        $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 = 'default_avatar.png';
        if ($request->hasFile('foto')) {
            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('uploads/siswa'), $filename);
            $fotoPath = 'uploads/siswa/' . $filename;
        }

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

        $siswa = Siswa::create([
            'nama_siswa' => $request->nama_siswa,
            'kelas' => $request->kelas,
            'jk' => $request->jk,
            'alamat' => $request->alamat,
            'foto' => $fotoPath,
            'id_profil' => $profilId,
        ]);

        // Log activity
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Menambahkan Siswa baru: ' . $siswa->nama_siswa . ' (Kelas: ' . $siswa->kelas . ')',
            'ip_address' => $request->ip()
        ]);

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

    /**
     * Update an existing Siswa.
     */
    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')) {
            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,
        ]);

        // Log activity
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Memperbarui data Siswa: ' . $siswa->nama_siswa . ' (NIS: ' . $nis . ')',
            'ip_address' => $request->ip()
        ]);

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

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

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

        $siswa->delete();

        // Log activity
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Menghapus data Siswa: ' . $namaSiswa . ' (NIS: ' . $nis . ')',
            'ip_address' => $request->ip()
        ]);

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

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

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

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

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

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

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

        // Eloquent update
        Admin::where('id_admin', $admin->id_admin)->update($updateData);

        // Log activity
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $request->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Memperbarui profil pribadinya',
            'ip_address' => $request->ip()
        ]);

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

    /**
     * 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
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Menambahkan Guru baru: ' . $guru->nama_guru . ' (NIP: ' . $guru->nip . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('admin.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
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Memperbarui data Guru: ' . $guru->nama_guru . ' (NIP: ' . $nip . ')',
            'ip_address' => $request->ip()
        ]);

        return redirect()->route('admin.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
        $admin = Auth::guard('admin')->user();
        ActivityLog::create([
            'user_type' => 'Admin',
            'user_name' => $admin->nama_admin,
            'user_id' => $admin->id_admin,
            'activity' => 'Menghapus data Guru: ' . $namaGuru . ' (NIP: ' . $nip . ')',
            'ip_address' => $request->ip()
        ]);

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