<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\MasterInduk;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Models\MasterInduk;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UserController extends Controller
{
    public function index()
    {
        $query = User::orderBy('created_at', 'desc');

        if (request()->has('role') && request('role') != '') {
            $query->where('role', request('role'));
        }

        $users = $query->paginate(10)->appends(request()->query());

        $whitelists = MasterInduk::orderBy('created_at', 'desc')->get();

        return view('admin.pengguna.index', [
            'pageTitle' => 'Daftar Pengguna',
            'users' => $users,
            'whitelists' => $whitelists
        ]);
    }

    public function create()
    {
        return view('admin.pengguna.create', ['pageTitle' => 'Tambah Pengguna Baru']);
    }

    public function store(Request $request)
    {
        $request->validate([
            'nama_lengkap' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'role' => 'required|in:siswa,guru,penjaga perpus',
            'no_hp' => 'nullable|string|max:20',
            'password' => 'required|min:6|confirmed',
            'nomor_induk' => [
                'required',
                function ($attribute, $value, $fail) use ($request) {
                    $label = $request->role == 'siswa' ? 'NISN' : 'NIP/NIK';

                    // Cek Nisn/Nip sudah dipakai di tabel users
                    $sudahDipakai = User::where('nisn', $value)->orWhere('nip', $value)->exists();
                    if ($sudahDipakai) {
                        $fail("{$label} ini sudah digunakan oleh akun lain.");
                        return;
                    }

                    if (in_array($request->role, ['siswa', 'guru'])) {
                        $terdaftar = MasterInduk::where('nomor_induk', $value)
                            ->where('role', $request->role)
                            ->exists();
                        if (!$terdaftar) {
                            $fail("{$label} tidak terdaftar di data sekolah. Hubungi admin.");
                        }
                    }
                },
            ],
        ], [
            'role.in' => 'Pilih role yang valid.',
            'email.unique' => 'Email sudah terdaftar.',
            'password.confirmed' => 'Konfirmasi password tidak cocok.'
        ]);

        $user = new User();
        $user->name = $request->nama_lengkap;
        $user->email = $request->email;
        $user->role = $request->role;
        $user->password = Hash::make($request->password);
        $user->no_hp = $request->no_hp;

        // Validasi NISN dan NIP berdasarkan Role
        if ($request->role == 'siswa') {
            $user->nisn = $request->nomor_induk;
            $user->kelas = $request->kelas;
            $user->golongan = $request->golongan;
        } else {
            $user->nip = $request->nomor_induk;
        }

        $user->save();

        return redirect()->route('admin.pengguna.index')->with('success', 'Pengguna berhasil ditambahkan.');
    }

    public function edit($id)
    {
        $pengguna = User::findOrFail($id);
        return view('admin.pengguna.edit', [
            'pageTitle' => 'Edit Pengguna: ' . $pengguna->nama_lengkap,
            'pengguna' => $pengguna,
        ]);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'nama_lengkap' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $id,
            'role' => 'required|in:siswa,guru,penjaga perpus',
            'no_hp' => 'nullable|string|max:20',
            'password' => 'nullable|min:6|confirmed',
            'nomor_induk' => [
                'required',
                function ($attribute, $value, $fail) use ($request, $id) {
                    $label = $request->role == 'siswa' ? 'NISN' : 'NIP/NIK';

                    // cek nisn/nip sudah dipakai di tabel users (kecuali oleh dirinya sendiri)
                    $sudahDipakai = User::where(function ($query) use ($value) {
                        $query->where('nisn', $value)->orWhere('nip', $value);
                    })->where('id', '!=', $id)->exists();

                    if ($sudahDipakai) {
                        $fail("{$label} ini sudah digunakan oleh akun lain.");
                        return;
                    }

                    if (in_array($request->role, ['siswa', 'guru'])) {
                        $terdaftar = MasterInduk::where('nomor_induk', $value)
                            ->where('role', $request->role)
                            ->exists();
                        if (!$terdaftar) {
                            $fail("{$label} tidak terdaftar di data sekolah. Hubungi admin.");
                        }
                    }
                },
            ],
        ]);

        $user = User::findOrFail($id);
        $user->name = $request->nama_lengkap;
        $user->email = $request->email;
        $user->role = $request->role;
        $user->no_hp = $request->no_hp;

        // Jika password diisi, maka update. Jika kosong, biarkan password lama.
        if ($request->filled('password')) {
            $user->password = \Illuminate\Support\Facades\Hash::make($request->password);
        }

        $user->nisn = null;
        $user->nip = null;
        $user->kelas = null;
        $user->golongan = null;

        // Masukkan kembali sesuai role
        if ($request->role == 'siswa') {
            $user->nisn = $request->nomor_induk;
            $user->kelas = $request->kelas;
            $user->golongan = $request->golongan;
        } else {
            $user->nip = $request->nomor_induk;
        }

        $user->save();

        return redirect()->route('admin.pengguna.index')->with('success', 'Data pengguna berhasil diperbarui.');
    }

    public function destroy($id)
    {
        User::findOrFail($id)->delete();
        return back()->with('success', 'Pengguna berhasil dihapus.');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'nama_lengkap' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'nomor_induk' => 'nullable|string|max:50',
            'phone' => 'nullable|string|max:20',
            'role' => 'required|in:siswa,guru,penjaga perpus',
            'kelas' => 'nullable|string|max:50',
            'password' => 'required|string|min:8|confirmed',
        ]);

        $validated['password'] = Hash::make($validated['password']);
        $validated['name'] = $validated['nama_lengkap']; // Set name field for compatibility

        User::create($validated);

        return redirect()->route('admin.pengguna.index')->with('success', 'Pengguna berhasil ditambahkan.');
    }

    public function update(Request $request, $id)
    {
        $pengguna = User::findOrFail($id);

        $validated = $request->validate([
            'nama_lengkap' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email,' . $id,
            'nomor_induk' => 'nullable|string|max:50',
            'phone' => 'nullable|string|max:20',
            'role' => 'required|in:siswa,guru,penjaga perpus',
            'kelas' => 'nullable|string|max:50',
            'password' => 'nullable|string|min:8|confirmed',
        ]);

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

        $validated['name'] = $validated['nama_lengkap']; // Set name field for compatibility

        $pengguna->update($validated);

        return redirect()->route('admin.pengguna.index')->with('success', 'Pengguna berhasil diperbarui.');
    }

    public function destroy($id)
    {
        $pengguna = User::findOrFail($id);
        $pengguna->delete();

        return redirect()->route('admin.pengguna.index')->with('success', 'Pengguna berhasil dihapus.');
    }
}
