<?php

namespace App\Http\Controllers;

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

class JobTypeController extends Controller
{
    public function index()
    {
        return JobType::all();
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'job_name' => 'required|string',
            'hr_charge' => 'required|numeric',
            'count_charge' => 'required|numeric',
        ]);

        return JobType::create($validated);
    }

    public function show(JobType $jobType)
    {
        return $jobType;
    }

    public function update(Request $request, JobType $jobType)
    {
        $validated = $request->validate([
            'job_name' => 'string',
            'hr_charge' => 'numeric',
            'count_charge' => 'numeric',
        ]);

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

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

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