<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Models\DeductionSection;
use Illuminate\Http\Request;

class DeductionSectionController extends Controller
{
    public function index()
    {
        $sections = DeductionSection::orderBy('section_code')->get();
        return view('superadmin.deduction-sections.index', compact('sections'));
    }

    public function create()
    {
        return view('superadmin.deduction-sections.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'section_code' => 'required|string|max:20|unique:deduction_sections,section_code',
            'section_name' => 'required|string|max:100',
            'limit_amount' => 'nullable|numeric|min:0',
            'description' => 'nullable|string',
            'is_active' => 'required|boolean',
        ]);
        $data['is_active'] = (bool) $data['is_active'];
        DeductionSection::create($data);
        return redirect()->route('superadmin.deduction-sections.index')->with('success', 'Deduction section created.');
    }

    public function edit(DeductionSection $deductionSection)
    {
        return view('superadmin.deduction-sections.edit', compact('deductionSection'));
    }

    public function update(Request $request, DeductionSection $deductionSection)
    {
        $data = $request->validate([
            'section_code' => 'required|string|max:20|unique:deduction_sections,section_code,' . $deductionSection->id,
            'section_name' => 'required|string|max:100',
            'limit_amount' => 'nullable|numeric|min:0',
            'description' => 'nullable|string',
            'is_active' => 'required|boolean',
        ]);
        $deductionSection->update([
            'section_code' => $data['section_code'],
            'section_name' => $data['section_name'],
            'limit_amount' => $data['limit_amount'] ?? null,
            'description' => $data['description'] ?? null,
            'is_active' => (bool) $data['is_active'],
        ]);
        return redirect()->route('superadmin.deduction-sections.index')->with('success', 'Deduction section updated.');
    }

    public function destroy(DeductionSection $deductionSection)
    {
        $deductionSection->delete();
        return redirect()->route('superadmin.deduction-sections.index')->with('success', 'Deduction section deleted.');
    }
}
