<?php

namespace App\Http\Controllers;

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

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

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

        try {
            $ageing = new SupAgeing();
            $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('supplier_ageing.index')->with('success', 'Supplier 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 = SupAgeing::findOrFail($id);
            return response()->json(['success' => true, 'data' => $ageing]);
        } catch (Exception $e) {
            return response()->json(['success' => false, 'error' => 'Supplier ageing record not found']);
        }
    }

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

        try {
            $ageing = SupAgeing::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('supplier_ageing.index')->with('success', 'Supplier 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 = SupAgeing::findOrFail($id);
            $ageing->delete();

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