<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AllowanceType;
use Illuminate\Http\Request;

class MasterAllowanceController extends Controller
{
    public function index() {
        return response()->json(['success' => true, 'data' => AllowanceType::all()]);
    }

    public function store(Request $request) {
        $request->validate([
            'name' => 'required',
            'calculation_method' => 'required|in:flat,prorata_working_days,attendance_based',
            'default_amount' => 'required|numeric'
        ]);

        $allowance = AllowanceType::create($request->all());
        return response()->json(['success' => true, 'data' => $allowance]);
    }

    public function destroy($id) {
        AllowanceType::findOrFail($id)->delete();
        return response()->json(['success' => true]);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name'               => 'required|string|max:255',
            'calculation_method' => 'required|string',
            'default_amount'     => 'required|numeric'
        ]);

        try {
            $allowanceType = \App\Models\AllowanceType::findOrFail($id);
            
            $allowanceType->update([
                'name'               => $request->name,
                'calculation_method' => $request->calculation_method,
                'default_amount'     => $request->default_amount,
                'is_taxable'         => $request->is_taxable ?? 1
            ]);

            return response()->json([
                'success' => true, 
                'message' => 'Master Tunjangan berhasil diperbarui.',
                'data'    => $allowanceType
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false, 
                'message' => 'Gagal memperbarui data: ' . $e->getMessage()
            ], 500);
        }
    }
}