<?php

namespace App\Http\Controllers;

use App\Models\Guru;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests\StoreGuruRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

class GuruController extends Controller
{
    public function index(Request $request)
    {
        $query = Guru::with('user');

        // filter search berdasarkan nama guru
        if ($request->has('search') && $request->search != '') {
            $query->where('nama', 'like', '%' . $request->search . '%');
            // ganti 'nama' dengan nama kolom di tabel gurus
        }

        $gurus = $query->paginate(10)->withQueryString();

        return view('gurus.index', compact('gurus'));
    }


    public function create()
    {
        $codeGuruBaru = Guru::generateCodeGuru();
        return view('gurus.create', compact('codeGuruBaru'));
    }


    public function store(Request $request)
    {
        $codeGuruBaru = Guru::generateCodeGuru();

        $request->validate([
            'nama' => 'required|string|max:255',
            'alamat' => 'required|string',
            'tanggal_lahir' => 'required|date',
            'jenis_kelamin' => 'required|in:L,P',
            'username' => 'required|string|max:255|unique:users',
            'password' => 'required|string|confirmed|min:6',
        ]);

        // buat user dulu
        $user = User::create([
            'name' => $request->nama,
            'username' => $request->username,
            'password' => bcrypt($request->password),
            'role' => 'guru',
        ]);

        // ambil kode guru otomatis
        $kodeBaru = Guru::generateCodeGuru();

        // simpan guru
        Guru::create([
            'user_id' => $user->id,
            'nama' => $request->nama,
            'code_guru' => $codeGuruBaru,
            'alamat' => $request->alamat,
            'tanggal_lahir' => $request->tanggal_lahir,
            'jenis_kelamin' => $request->jenis_kelamin,
        ]);

        return redirect()->route('gurus.index')->with('success', 'Data guru berhasil ditambahkan.');
    }

    /**
     * Display the specified resource.
     */
    public function show(Guru $guru)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Guru $guru)
    {
        return view('gurus.edit', compact('guru'));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Guru $guru)
    {
        $guru->delete();
        return redirect()->route('gurus.index')->with('success', 'Guru berhasil dihapus');
    }

    public function profile()
    {
        $user = Auth::user();
        $guru = \App\Models\Guru::where('user_id', $user->id)->firstOrFail();
        return view('guru.profile', compact('guru'));
    }

    public function editProfile()
    {
        $user = Auth::user();
        $guru = \App\Models\Guru::where('user_id', $user->id)->firstOrFail();
        return view('guru.edit_profile', compact('guru'));
    }

    public function updateProfile(Request $request)
    {
        $user = Auth::user();
        $guru = \App\Models\Guru::where('user_id', $user->id)->firstOrFail();
        $validated = $request->validate([
            'nama' => 'required|string|max:255',
            'code_guru' => 'required|string|max:50',
            'alamat' => 'nullable|string',
            'tanggal_lahir' => 'nullable|date',
            'jenis_kelamin' => 'required|in:L,P',
            'foto' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);
        if ($request->hasFile('foto')) {
            if ($guru->foto && \Storage::disk('public')->exists('foto_guru/' . $guru->foto)) {
                \Storage::disk('public')->delete('foto_guru/' . $guru->foto);
            }
            $file = $request->file('foto');
            $filename = uniqid() . '.' . $file->getClientOriginalExtension();
            $file->storeAs('foto_guru', $filename, 'public');
            $validated['foto'] = $filename;
        }
        $guru->update($validated);
        return redirect()->route('guru.profile')->with('success', 'Profil berhasil diperbarui');
    }
}
