<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\StaffUser;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class UserStaffController extends Controller
{
    public function store(Request $request, User $user): RedirectResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:80',
            'role' => 'required|in:cashier,manager,admin',
        ]);

        $user->staffUsers()->create([
            'name'      => $data['name'],
            'role'      => $data['role'],
            'is_active' => true,
        ]);

        return back()->with('success', "Staff member \"{$data['name']}\" added.");
    }

    public function update(Request $request, User $user, StaffUser $staff): RedirectResponse
    {
        abort_if($staff->user_id !== $user->id, 403);

        $data = $request->validate([
            'role'      => 'required|in:cashier,manager,admin',
            'is_active' => 'required|boolean',
        ]);

        $staff->update([
            'role'      => $data['role'],
            'is_active' => (bool) $data['is_active'],
        ]);

        return back()->with('success', "Staff member \"{$staff->name}\" updated.");
    }

    public function destroy(User $user, StaffUser $staff): RedirectResponse
    {
        abort_if($staff->user_id !== $user->id, 403);
        $name = $staff->name;
        $staff->delete();

        return back()->with('success', "Staff member \"{$name}\" removed.");
    }
}
