<?php

namespace App\Http\Controllers;

use App\Models\Department;
use App\Models\User;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class UserController extends Controller
{
    /**
     * Fetch all user names.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAllUserNames()
    {
        $users = User::select('id', 'name')->get();
        return response()->json($users);
    }
    public function index()
    {
        $departments = Department::all();
        return view('pages.users.index', compact('departments'));
    }

    public function getUsersData(Request $request)
    {
        $responses = User::with(['role', 'department'])
            ->select('users.*');

        // Apply filters
        if ($request->has('department') && !empty($request->department)) {
            $responses->where('department_id', $request->department);
        }
        if ($request->has('role') && !empty($request->role)) {
            $responses->where('role_id', $request->role);
        }

        return DataTables::of($responses)
            ->addColumn('department_name', function ($response) {
                return $response->department ? $response->department->name : 'Unknown';
            })
            ->addColumn('role_name', function ($response) {
                $roles = [
                    1 => 'Admin',
                    2 => 'HOD',
                    3 => 'Faculty',
                ];
                $options = '';
                foreach ($roles as $id => $name) {
                    $selected = $response->role_id == $id ? 'selected' : '';
                    $options .= "<option value='$id' $selected>$name</option>";
                }
                return "<select class='form-select form-select-sm user-role-dropdown' data-user-id='{$response->id}'>$options</select>";
            })
            ->addColumn('action', function ($response) {
                $actions = [];

                // Edit button with role-appropriate route
                $userRole = auth()->user()->role->name;
                // Determine the appropriate route based on user role
                // if ($userRole === 'Admin') {
                //     $editRoute = route('admin.users.edit', $response->id);
                // } elseif ($userRole === 'Coordinator') {
                //     $editRoute = route('coordinator.users.edit', $response->id);
                // } else {
                //     $editRoute = route('faculty.users.edit', $response->id);
                // }

                // $actions[] = '<a href="' . $editRoute . '" class="btn btn-sm btn-info mx-1"><i class="fas fa-edit"></i></a>';

                $deleteRoute = route('users.destroy', $response->id);
                $actions[] = '<button type="button" class="btn btn-sm btn-danger delete-btn" data-id="' . $response->id . '" data-url="' . $deleteRoute . '"><i class="fas fa-trash"></i></button>';

                return implode(' ', $actions);
            })
            ->rawColumns(['action', 'role_name'])
            ->make(true);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'email' => 'required|email|unique:users',
            'password' => 'required|string|min:8',
            'role_id' => 'required|exists:roles,id',
            'department_id' => 'nullable|exists:departments,id',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
            'role_id' => $request->role_id,
            'department_id' => $request->department_id,
        ]);

        return $user;
    }

    public function show(User $user)
    {
        return $user->load(['role', 'department']);
    }

    public function update(Request $request, User $user)
    {
        $request->validate([
            'name' => 'sometimes|required|string',
            'email' => 'sometimes|required|email|unique:users,email,' . $user->id,
            'password' => 'nullable|string|min:8',
            'role_id' => 'sometimes|required|exists:roles,id',
            'department_id' => 'nullable|exists:departments,id',
        ]);

        $user->update(array_filter($request->all()));
        return $user->load(['role', 'department']);
    }

    public function destroy(User $user)
    {
        $user->delete();
        return response()->noContent();
    }
}
