<?php

namespace App\Http\Controllers;

use App\Models\Operator;
use Illuminate\Http\Request;

class OperatorController extends Controller
{
    public function index()
    {
        return Operator::all();
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string',
            'contact' => 'nullable|string',
            'category' => 'required|string',
            'salary' => 'nullable|numeric',
            'bata' => 'nullable|numeric',
            'status' => 'string'
        ]);

        return Operator::create($validated);
    }

    public function show(Operator $operator)
    {
        return $operator;
    }

    public function update(Request $request, Operator $operator)
    {
        $validated = $request->validate([
            'name' => 'string',
            'contact' => 'nullable|string',
            'category' => 'string',
            'salary' => 'nullable|numeric',
            'bata' => 'nullable|numeric',
            'status' => 'string'
        ]);

        $operator->fill($validated);
        
        $dirty = $operator->getDirty();
        
        if (!empty($dirty)) {
            $changes = [];
            foreach($dirty as $field => $newValue) {
                $oldValue = $operator->getOriginal($field);
                $changes[] = [
                    'field' => $field,
                    'old_value' => $oldValue,
                    'new_value' => $newValue,
                ];
            }
            
            $history = $operator->history ?? [];
            $history[] = [
                'timestamp' => now()->toDateTimeString(),
                'changes' => $changes
            ];
            $operator->history = $history;
        }

        $operator->save();
        return $operator;
    }

    public function destroy(Operator $operator)
    {
        $operator->delete();
        return response()->json(['success' => true]);
    }
}
