<?php

namespace App\Http\Controllers;

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

class AttendanceSettingController extends Controller
{
    public function index()
    {
        $setting = AttendanceSetting::first();

        return view('pages.attendance.settings', [
            'title' => 'Pengaturan Absensi',
            'setting' => $setting,
        ]);
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'location_name' => ['required', 'string', 'max:255'],
            'latitude' => ['required', 'numeric'],
            'longitude' => ['required', 'numeric'],
            'radius_meters' => ['required', 'integer', 'min:10'],
            'work_start_time' => ['nullable', 'date_format:H:i'],
            'work_end_time' => ['nullable', 'date_format:H:i'],
            'late_tolerance_minutes' => ['nullable', 'integer', 'min:0'],
            'early_leave_tolerance_minutes' => ['nullable', 'integer', 'min:0'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        $validated['is_active'] = $request->boolean('is_active');
        $validated['late_tolerance_minutes'] = $validated['late_tolerance_minutes'] ?? 0;
        $validated['early_leave_tolerance_minutes'] = $validated['early_leave_tolerance_minutes'] ?? 0;

        AttendanceSetting::updateOrCreate(
            ['id' => optional(AttendanceSetting::first())->id],
            $validated
        );

        return back()->with('success', 'Pengaturan absensi berhasil disimpan.');
    }
}