<?php

namespace App\Http\Controllers;

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

class EquipmentController extends Controller
{
    public function index()
    {
        return Equipment::all();
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string',
            'category' => 'required|string',
            'hourly_rate' => 'required|numeric',
            'min_rate' => 'required|numeric',
            'daily_rate' => 'nullable|numeric',
            'shifting_charge' => 'nullable|numeric',
        ]);

        return Equipment::create($validated);
    }

    public function show(Equipment $equipment)
    {
        return $equipment;
    }

    public function update(Request $request, Equipment $equipment)
    {
        $validated = $request->validate([
            'name' => 'string',
            'category' => 'string',
            'hourly_rate' => 'numeric',
            'min_rate' => 'numeric',
            'daily_rate' => 'nullable|numeric',
            'shifting_charge' => 'nullable|numeric',
        ]);

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

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

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