<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Role;
use App\Models\Student;
use App\Models\User;
use Exception;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class StudentController extends Controller
{
    private function useValidator(Request $request, array $rules)
    {
        return Validator::make($request->all(), $rules);
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $users = User::query()->where("role_id", "=", '9e3efb34-c5ef-416e-b31e-58ba13807301')->get();
        $students = Student::query()->latest()->paginate(5);

        $title = "Hapus Siswa!";
        $text = "Are you sure you want to delete?";
        confirmDelete($title, $text);

        return view("admin.student.index", [
            "users" => $users,
            "students" => $students,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        try {
            $existingStudent = Student::where("user_id", $request->user_id)->first();
            if ($existingStudent) {
                return redirect()->back()->withInput()->with('errorCreateStudent', "Data siswa dengan user ID {$request->user_id} sudah ada.");
            }
    
            $validator = Validator::make($request->all(), [
                "name" => "required|string|max:255",
                "email" => "required|email",
                "nis" => "required|max:50",
                "user_id" => "required",
                "status" => "required",
                "gaya_belajar" => "nullable|string|max:255",
            ]);
    
            if ($validator->fails()) {
                return redirect()->back()
                    ->withErrors($validator)
                    ->withInput()
                    ->with('errorCreateStudent', 'Gagal menambahkan siswa, periksa kembali input.');
            }
    
            $validated = $validator->validated();
    
            Student::create($validated);
    
            return redirect()->route("student.index")->with("successCreateStudent", "Berhasil Menambahkan Siswa Baru");
        } catch (QueryException $e) {
            Log::error("Gagal menambahkan siswa: " . $e->getMessage());
            return redirect()->back()->withInput()->with('errorCreateStudent', 'Gagal Menambahkan Siswa: ' . $e->getMessage());
        } catch (Exception $e) {
            Log::error("Error lain: " . $e->getMessage());
            return redirect()->back()->withInput()->with('errorCreateStudent', 'Terjadi kesalahan: ' . $e->getMessage());
        }
    }    

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request)
    {
        try {
            if (!$request->has('student_id')) {
                return back()->with('errorUpdateStudent', 'Student ID tidak ditemukan.');
            }
    
            $student = Student::find($request->student_id);
    
            if (!$student) {
                return back()->with('errorUpdateStudent', 'Data siswa tidak ditemukan.');
            }
    
            $validator = Validator::make($request->all(), [
                "name" => "required|string|max:255",
                "email" => "required|email",
                "nis" => "required|max:50",
                "user_id" => "required|exists:users,id",
                "status" => "required",
                "gaya_belajar" => "nullable|string|max:255",
            ]);
    
            if ($validator->fails()) {
                return redirect()->back()
                    ->withErrors($validator)
                    ->withInput()
                    ->with('errorCreateStudent', 'Gagal menambahkan siswa, periksa kembali input.');
            }
    
            $student->update($validator->validated());
    
            return redirect()->route("student.index")->with("successUpdateStudent", "Data Siswa Berhasil Di Update.");
        } catch (QueryException $e) {
            Log::error("Database Error: " . $e->getMessage());
            return back()->with("errorUpdateStudent", "Gagal memperbarui data siswa. Database Error: " . $e->getMessage());
        } catch (Exception $e) {
            Log::error("General Error: " . $e->getMessage());
            return back()->with("errorUpdateStudent", "Terjadi kesalahan: " . $e->getMessage());
        }
    }
    

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try {
            Student::query()->where('id', '=', $id)->delete();

            return redirect()->route("student.index")->with("successDeleteStudent", "Data Siswa Berhasil Di Delete.");
        } catch (QueryException $e) {
            Log::info($e->getMessage());
            return back()->with("errorDeleteStudent", "Gagal menghapus data siswa");
        }
    }
}