<?php

namespace App\Http\Controllers;

use App\Models\Staff;
use App\Models\Device;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class StaffController extends Controller
{
    /**
     * Display staff list
     */
    public function index()
    {
        $user = Auth::user();
        
        // Get device_id from session or user's first device
        $device_id = session('device_id') ?? $user->devices()->first()?->id;
        
        // Get all staff for this device
        $staff = Staff::with(['device', 'user'])
            ->where('user_id', $user->id);
        
        if ($device_id) {
            $staff = $staff->where('device_id', $device_id);
        }
        
        $staff = $staff->orderBy('created_at', 'desc')->paginate(20);
        
        // Get user's devices for dropdown
        $devices = Device::where('user_id', $user->id)->get();
        
        // Calculate statistics
        $totalStaff = Staff::where('user_id', $user->id)->count();
        $activeStaff = Staff::where('user_id', $user->id)->where('status', 'active')->count();
        $inactiveStaff = Staff::where('user_id', $user->id)->where('status', 'inactive')->count();
        $managers = Staff::where('user_id', $user->id)->where('role', 'manager')->count();
        
        return view('staff-list', compact('staff', 'devices', 'device_id', 'totalStaff', 'activeStaff', 'inactiveStaff', 'managers'));
    }

    /**
     * Store a new staff member
     */
    public function store(Request $request)
    {
        $user = Auth::user();
        
        $validated = $request->validate([
            'device_id' => 'required|exists:devices,id',
            'staff_name' => 'required|string|max:255',
            'staff_email' => 'required|email|max:255',
            'staff_phone' => 'nullable|string|max:20',
            'role' => 'required|in:viewer,operator,manager',
            'permissions' => 'nullable|array',
            'status' => 'nullable|in:active,inactive,suspended',
        ]);

        // Verify device belongs to user
        $device = Device::where('id', $validated['device_id'])
            ->where('user_id', $user->id)
            ->firstOrFail();

        // Check if staff email already exists for this device
        $existing = Staff::where('device_id', $validated['device_id'])
            ->where('staff_email', $validated['staff_email'])
            ->first();

        if ($existing) {
            return back()->with('error', 'A staff member with this email already exists for this device.');
        }

        Staff::create([
            'user_id' => $user->id,
            'device_id' => $validated['device_id'],
            'staff_name' => $validated['staff_name'],
            'staff_email' => $validated['staff_email'],
            'staff_phone' => $validated['staff_phone'] ?? null,
            'role' => $validated['role'],
            'permissions' => $validated['permissions'] ?? [],
            'status' => $validated['status'] ?? 'active',
        ]);

        return back()->with('success_alert', 'Staff member added successfully!');
    }

    /**
     * Update staff member
     */
    public function update(Request $request)
    {
        $user = Auth::user();
        
        $validated = $request->validate([
            'id' => 'required|exists:staff,id',
            'staff_name' => 'required|string|max:255',
            'staff_email' => 'required|email|max:255',
            'staff_phone' => 'nullable|string|max:20',
            'role' => 'required|in:viewer,operator,manager',
            'permissions' => 'nullable|array',
            'status' => 'required|in:active,inactive,suspended',
        ]);

        $staff = Staff::where('id', $validated['id'])
            ->where('user_id', $user->id)
            ->firstOrFail();

        // Check if email is being changed and already exists
        if ($staff->staff_email !== $validated['staff_email']) {
            $existing = Staff::where('device_id', $staff->device_id)
                ->where('staff_email', $validated['staff_email'])
                ->where('id', '!=', $staff->id)
                ->first();

            if ($existing) {
                return back()->with('error', 'A staff member with this email already exists for this device.');
            }
        }

        $staff->update([
            'staff_name' => $validated['staff_name'],
            'staff_email' => $validated['staff_email'],
            'staff_phone' => $validated['staff_phone'] ?? null,
            'role' => $validated['role'],
            'permissions' => $validated['permissions'] ?? [],
            'status' => $validated['status'],
        ]);

        return back()->with('success_alert', 'Staff member updated successfully!');
    }

    /**
     * Delete staff member
     */
    public function destroy(Request $request)
    {
        $user = Auth::user();
        
        $staff = Staff::where('id', $request->id)
            ->where('user_id', $user->id)
            ->firstOrFail();

        $staff->delete();

        return back()->with('success_alert', 'Staff member removed successfully!');
    }

    /**
     * Toggle staff status
     */
    public function toggleStatus($id)
    {
        $user = Auth::user();
        
        $staff = Staff::where('id', $id)
            ->where('user_id', $user->id)
            ->firstOrFail();

        $newStatus = $staff->status === 'active' ? 'inactive' : 'active';
        $staff->update(['status' => $newStatus]);

        return back()->with('success_alert', 'Staff status updated successfully!');
    }
}
