<?php

namespace App\Http\Controllers\Admin;

use App\DataTables\StaffDataTable;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreStaffRequest;
use App\Http\Requests\UpdateStaffRequest;
use App\Models\User;
use App\Services\StaffService;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Role;

class StaffController extends Controller
{
    public function __construct(protected StaffService $service)
    {
        $this->authorizeResource(User::class, 'staff');
    }

    public function index()
    {
        $roles = $this->availableRoles();

        return view('admin.staff.index', compact('roles'));
    }

    public function create()
    {
        $roles = $this->availableRoles();

        return view('admin.staff.create', compact('roles'));
    }

    public function data(Request $request, StaffDataTable $dataTable)
    {
        $this->authorize('viewAny', User::class);

        return $dataTable->render($request);
    }

    public function store(StoreStaffRequest $request)
    {
        $staff = $this->service->create($request->validated());

        return response()->json(['success' => true, 'data' => $staff], 201);
    }

    public function edit(User $staff)
    {
        // If AJAX (DataTable edit flow) return JSON; otherwise return edit page.
        if (request()->wantsJson() || request()->ajax()) {
            return response()->json([
                'data' => $staff->load('roles'),
                'roles' => $staff->roles->pluck('id'),
                'update_url' => route('admin.staff.update', $staff),
            ]);
        }

        $roles = $this->availableRoles();

        return view('admin.staff.edit', ['staff' => $staff, 'roles' => $roles]);
    }

    public function update(UpdateStaffRequest $request, User $staff)
    {
        $this->service->update($staff, $request->validated());

        return response()->json(['success' => true, 'data' => $staff->fresh()->load('roles')]);
    }

    public function destroy(User $staff)
    {
        $this->service->delete($staff);

        return response()->json(['success' => true]);
    }

    private function availableRoles()
    {
        return Role::query()
            ->when(! auth()->user()->hasRole('Super Admin'), fn ($query) => $query->where('name', '!=', 'Super Admin'))
            ->where('name', '!=', 'Customer')
            ->orderBy('name')
            ->get();
    }
}
