<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BusinessStaff;
use App\Models\Business;
use App\Models\User;
use Illuminate\Http\Request;

class StaffController extends Controller
{
    /**
     * Display a listing of staff
     */
    public function index()
    {
        $staff = BusinessStaff::with('user', 'business')->paginate(50);

        $stats = [
            'total' => BusinessStaff::count(),
            'active' => BusinessStaff::where('status', 'active')->count(),
            'pending' => BusinessStaff::where('status', 'pending_invitation')->count(),
        ];

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

    /**
     * Display the specified staff member
     */
    public function show(BusinessStaff $staff)
    {
        $staff->load('user', 'business');

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

    /**
     * Store a newly created staff member
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'business_id' => 'required|exists:businesses,id',
            'user_id' => 'required|exists:users,id',
            'role' => 'required|string|max:255',
            'status' => 'required|in:active,inactive,pending_invitation',
        ]);

        $staff = BusinessStaff::create($validated);

        return redirect()->route('admin.staff.show', $staff->id)
            ->with('success', 'Staff member added successfully.');
    }

    /**
     * Show the form for editing the specified staff member
     */
    public function edit(BusinessStaff $staff)
    {
        $staff->load('user', 'business');
        $businesses = Business::all();
        $users = User::all();

        return view('admin.staff.edit', compact('staff', 'businesses', 'users'));
    }

    /**
     * Update the specified staff member
     */
    public function update(Request $request, BusinessStaff $staff)
    {
        $validated = $request->validate([
            'role' => 'required|string|max:255',
            'status' => 'required|in:active,inactive,pending_invitation',
        ]);

        $staff->update($validated);

        return redirect()->route('admin.staff.show', $staff->id)
            ->with('success', 'Staff member updated successfully.');
    }

    /**
     * Delete the specified staff member
     */
    public function destroy(BusinessStaff $staff)
    {
        $staff->delete();

        return redirect()->route('admin.staff.index')
            ->with('success', 'Staff member removed successfully.');
    }
}

