<?php

namespace App\Http\Controllers;

use App\Models\Guru;
use App\Models\User;
use App\Models\Kelas;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;

class GuruController extends Controller
{
    public function index()
    {
        $guru = Guru::all();
        $kelas = Kelas::all(); // Mengambil data kelas dari model Kelas
        
        return view('guru.index', compact('guru', 'kelas')); // Mengirimkan variabel $guru dan $kelas ke view
    }

    public function show($classId)
    {
        $guru = Guru::where('id_kelas', $classId)->get();
        $kelas = Kelas::find($classId);
        return view('guru.show', compact('guru', 'kelas'));
    }





    
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'nip' => 'required|unique:guru',
            'nama_guru' => 'required',
            'nomor_hp' => 'required|max:13',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        try {
            DB::beginTransaction();

            $users = new User();
            $users->name = $request->nama_guru;
            $users->username = $request->nip;
            $users->password = $request->password;
            $users->save();

            $guru = new Guru();
            $guru->nip = $request->nip;
            $guru->nama_guru = $request->nama_guru;
            $guru->nomor_hp = $request->nomor_hp;
            $guru->password = $request->password;
            $guru->save();

            DB::commit();

            return redirect()->back()->with('success', 'Data guru berhasil ditambahkan.');
        } catch (\Exception $e) {
            DB::rollback();
            return back()->withErrors(['error' => $e->getMessage()]);
        }
    }

    public function update(Request $request, $nip)
    {
        // Find and update the Guru record
        $guru = Guru::findOrFail($nip);
        $guru->update($request->only(['nama_guru', 'nomor_hp']));

        // Update the related User record's password if provided
        if ($request->filled('password')) {
            $user = User::where('username', $nip)->first();
            if ($user) {
                $user->password = $request->password;
                $user->save();
            }
        }

        return redirect()->back()->with('success', 'Data guru berhasil diperbarui.');
    }

    public function destroy($nip)
    {
        // Find and delete the Guru record
        $guru = Guru::findOrFail($nip);
        $guru->delete();

        // Delete the associated User record
        User::where('username', $nip)->delete();

        return redirect()->back()->with('success', 'Data guru berhasil dihapus.');
    }
}