<?php
namespace App\Http\Controllers;

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


class AgeingAnalysisController extends Controller
{
    public function index()
    {
        $ageingAnalyses = AgeingAnalysis::all(); // Ensure this line fetches all records
        return view('ageing.add', compact('ageingAnalyses')); // Pass the variable correctly
    }


    public function store(Request $request)
    {
        $data = $request->validate([
            'ageCode' => 'required|string',
            'description' => 'required|string',
            'ageingGroup' => 'required|string',
            'intervalType' => 'required|string',
            'interval' => 'required|string',
            'customIntervals' => 'nullable|string',
            'customAgeGroups' => 'nullable|string',
        ]);

        $ageingAnalysis = AgeingAnalysis::create([
            'age_code' => $data['ageCode'],
            'description' => $data['description'],
            'ageing_group' => $data['ageingGroup'],
            'interval_type' => $data['intervalType'],
            'interval' => $data['interval'],
            'custom_intervals' => json_decode($data['customIntervals'], true) ?? null,
            'custom_age_groups' => json_decode($data['customAgeGroups'], true) ?? null,
        ]);

        return redirect()->route('ageing.add')->with('success', 'Ageing Analysis saved successfully!');
    }
    public function edit($id)
{
    $ageingAnalysis = AgeingAnalysis::findOrFail($id);
    return view('ageing.edit', compact('ageingAnalysis')); // Return only the form content
}

public function update(Request $request, $id)
{
    $data = $request->validate([
        'ageCode' => 'required|string',
        'description' => 'required|string',
        'ageingGroup' => 'required|string',
        'intervalType' => 'required|string',
        'interval' => 'required|string',
        'customIntervals' => 'nullable|string',
        'customAgeGroups' => 'nullable|string',
    ]);

    $ageingAnalysis = AgeingAnalysis::findOrFail($id);
    $ageingAnalysis->update([
        'age_code' => $data['ageCode'],
        'description' => $data['description'],
        'ageing_group' => $data['ageingGroup'],
        'interval_type' => $data['intervalType'],
        'interval' => $data['interval'],
        'custom_intervals' => json_decode($data['customIntervals'], true) ?? null,
        'custom_age_groups' => json_decode($data['customAgeGroups'], true) ?? null,
    ]);

    return redirect()->route('ageing.add')->with('success', 'Ageing Analysis updated successfully!');
}

public function destroy($id)
{
    $ageingAnalysis = AgeingAnalysis::findOrFail($id);
    $ageingAnalysis->delete();

    return redirect()->route('ageing.add')->with('success', 'Ageing Analysis deleted successfully!');
}


}
