<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Lesson;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    public function index()
    {
        $users = User::query()
            ->where('role', 'guru')
            ->when(request()->q, function ($query) {
                $query->where(function ($subQuery) {
                    $subQuery->where('name', 'like', '%' . request()->q . '%')
                        ->orWhere('email', 'like', '%' . request()->q . '%');
                });
            })
            ->with('lessons')
            ->latest()
            ->paginate(10);

        $users->appends(['q' => request()->q]);

        return inertia('Admin/Users/Index', [
            'users' => $users,
        ]);
    }

    public function create()
    {
        return inertia('Admin/Users/Create', [
            'lessons' => Lesson::orderBy('title')->get(),
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:8|confirmed',
            'lesson_ids' => 'required|array|min:1',
            'lesson_ids.*' => 'integer|exists:lessons,id',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'role' => 'guru',
            'password' => $request->password,
        ]);

        $user->lessons()->sync($request->lesson_ids);

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

    public function edit(User $user)
    {
        abort_unless($user->isTeacher(), 404);

        $user->load('lessons');

        return inertia('Admin/Users/Edit', [
            'user' => $user,
            'lessons' => Lesson::orderBy('title')->get(),
        ]);
    }

    public function update(Request $request, User $user)
    {
        abort_unless($user->isTeacher(), 404);

        $request->validate([
            'name' => 'required|string|max:255',
            'email' => ['required', 'email', Rule::unique('users', 'email')->ignore($user->id)],
            'password' => 'nullable|string|min:8|confirmed',
            'lesson_ids' => 'required|array|min:1',
            'lesson_ids.*' => 'integer|exists:lessons,id',
        ]);

        $payload = [
            'name' => $request->name,
            'email' => $request->email,
        ];

        if ($request->filled('password')) {
            $payload['password'] = $request->password;
        }

        $user->update($payload);
        $user->lessons()->sync($request->lesson_ids);

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

    public function destroy(User $user)
    {
        abort_unless($user->isTeacher(), 404);

        $user->delete();

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