<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class OperatorController extends Controller
{
    public function index()
    {
        $operators = User::where('role', 'operator')
            ->orderBy('created_at', 'desc')
            ->paginate(10);

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

    public function create()
    {
        return view('admin.operators.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'phone' => ['nullable', 'string', 'max:20'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'] ?? null,
            'role' => 'operator',
            'password' => Hash::make($validated['password']),
        ]);

        return redirect()->route('admin.operators.index')
            ->with('success', 'Operator created successfully.');
    }

    public function edit(User $operator)
    {
        if ($operator->role !== 'operator') {
            abort(404);
        }

        return view('admin.operators.edit', compact('operator'));
    }

    public function update(Request $request, User $operator)
    {
        if ($operator->role !== 'operator') {
            abort(404);
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users')->ignore($operator->id)],
            'phone' => ['nullable', 'string', 'max:20'],
            'password' => ['nullable', 'string', 'min:8', 'confirmed'],
        ]);

        $operator->name = $validated['name'];
        $operator->email = $validated['email'];
        $operator->phone = $validated['phone'] ?? null;

        if (!empty($validated['password'])) {
            $operator->password = Hash::make($validated['password']);
        }

        $operator->save();

        return redirect()->route('admin.operators.index')
            ->with('success', 'Operator updated successfully.');
    }

    public function destroy(User $operator)
    {
        if ($operator->role !== 'operator') {
            abort(404);
        }

        $operator->delete();

        return redirect()->route('admin.operators.index')
            ->with('success', 'Operator deleted successfully.');
    }
}
