<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use App\Models\Ageing;

class AgeingController extends Controller
{
    // Show the list and form for creating new ageing records
    public function index()
    {
        $ageings = Ageing::all();
        return view('maintanance.customers.create_ageing', compact('ageings'));
    }

    // Store new ageing record
    public function store(Request $request)
    {
        $request->validate([
            'age_code' => 'required|string|max:255|unique:ageings,age_code',
            'description' => 'required|string|max:255',
        ], [
            'age_code.unique' => 'The code you entered already exists. Please use a different code.',
        ]);

        try {
            $ageing = new Ageing();
            $ageing->age_code = $request->age_code;
            $ageing->description = $request->description;
            $ageing->group_type = $request->group_type;
            $ageing->interval_type = $request->interval_type;
            
            // Set interval fields based on selection
            $ageing->interval_30_days = ($request->interval == '30') ? 1 : 0;
            $ageing->interval_7_days = ($request->interval == '7') ? 1 : 0;
            $ageing->interval_custom = ($request->interval == 'custom') ? 1 : 0;

            // Save custom age fields
            for ($i = 1; $i <= 7; $i++) {
                $field = 'custom_age_' . $i;
                $ageing->$field = $request->$field;
            }
            
            // Save custom interval fields
            for ($i = 1; $i <= 6; $i++) {
                $field = 'custom_interval_' . $i;
                $ageing->$field = $request->$field;
            }

            $ageing->save();

            return redirect()->route('customer_ageing.index')->with('success', 'Ageing record created successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()])->withInput();
        }
    }

    // Get ageing data for editing
    public function edit($id)
    {
        try {
            $ageing = Ageing::find($id);
            
            if (!$ageing) {
                return response()->json([
                    'success' => false, 
                    'error' => 'Ageing record not found'
                ]);
            }
            
            return response()->json(['success' => true, 'data' => $ageing]);
        } catch (Exception $e) {
            return response()->json([
                'success' => false, 
                'error' => 'Error retrieving ageing data: ' . $e->getMessage()
            ]);
        }
    }

    // Update ageing record
    public function update(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:ageings,id',
            'age_code' => 'required|string|max:255|unique:ageings,age_code,' . $request->id,
            'description' => 'required|string|max:255',
        ]);

        try {
            $ageing = Ageing::findOrFail($request->id);

            $ageing->age_code = $request->age_code;
            $ageing->description = $request->description;
            $ageing->group_type = $request->group_type;
            $ageing->interval_type = $request->interval_type;
            
            // Set interval fields based on selection
            $ageing->interval_30_days = ($request->interval == '30') ? 1 : 0;
            $ageing->interval_7_days = ($request->interval == '7') ? 1 : 0;
            $ageing->interval_custom = ($request->interval == 'custom') ? 1 : 0;

            // Save custom age fields
            for ($i = 1; $i <= 7; $i++) {
                $field = 'custom_age_' . $i;
                $ageing->$field = $request->$field;
            }
            
            // Save custom interval fields
            for ($i = 1; $i <= 6; $i++) {
                $field = 'custom_interval_' . $i;
                $ageing->$field = $request->$field;
            }

            $ageing->save();

            return redirect()->route('customer_ageing.index')->with('success', 'Ageing record updated successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()])->withInput();
        }
    }

    // Delete ageing record
    public function destroy($id)
    {
        try {
            $ageing = Ageing::findOrFail($id);
            $ageing->delete();

            return redirect()->route('customer_ageing.index')->with('success', 'Ageing record deleted successfully.');
        } catch (Exception $e) {
            return redirect()->route('customer_ageing.index')->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }
}