<?php

namespace App\Http\Controllers;

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

class AttendanceController extends Controller
{
    public function index(Request $request)
    {
        $query = Attendance::with('operator');
        if ($request->has('date')) {
            $query->where('date', $request->date);
        }
        return $query->get();
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'operator_id' => 'required|exists:operators,id',
            'date' => 'required|date',
            'status' => 'required|string',
            'shift' => 'string',
            'overtime_hours' => 'numeric',
            'remarks' => 'nullable|string'
        ]);

        return Attendance::updateOrCreate(
            ['operator_id' => $validated['operator_id'], 'date' => $validated['date'], 'shift' => $validated['shift'] ?? 'Day'],
            $validated
        );
    }

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