<?php

namespace App\Http\Controllers\Membership\Admin;

use App\Http\Controllers\Controller;
use App\Models\MembershipCategory;
use App\Models\MembershipRenewalConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class MembershipRenewalConfigController extends Controller
{
    /**
     * List all renewal period configurations.
     */
    public function index()
    {
        abort_unless(auth()->user()->can('manage renewal configs'), 403);

        $configs = MembershipRenewalConfig::with(['membershipCategory', 'creator', 'updater'])
            ->orderByDesc('is_default')
            ->orderBy('created_at')
            ->get();

        $categories = MembershipCategory::active()->ordered()->get();

        return view('membership.admin.renewal-configs.index', compact('configs', 'categories'));
    }

    /**
     * Store a new renewal period configuration.
     */
    public function store(Request $request)
    {
        abort_unless(auth()->user()->can('manage renewal configs'), 403);

        $validator = Validator::make($request->all(), [
            'membership_category_id' => 'nullable|exists:membership_categories,id',
            'renewal_period_months'  => 'required|integer|min:1|max:120',
            'is_default'             => 'boolean',
            'effective_from'         => 'required|date',
            'effective_until'        => 'nullable|date|after_or_equal:effective_from',
        ], [
            'renewal_period_months.required' => 'Renewal period is required.',
            'renewal_period_months.integer'  => 'Renewal period must be a whole number.',
            'renewal_period_months.min'      => 'Renewal period must be at least 1 month.',
            'renewal_period_months.max'      => 'Renewal period cannot exceed 120 months.',
            'effective_from.required'        => 'Effective from date is required.',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $data = $validator->validated();
        $data['created_by'] = auth()->id();
        $data['updated_by'] = auth()->id();

        // If marking as default, unset any existing default
        if (!empty($data['is_default'])) {
            MembershipRenewalConfig::where('is_default', true)->update(['is_default' => false]);
        }

        MembershipRenewalConfig::create($data);

        return redirect()->route('admin.renewal-configs.index')
            ->with('success', 'Renewal period configuration created successfully.');
    }

    /**
     * Update an existing renewal period configuration.
     */
    public function update(Request $request, MembershipRenewalConfig $config)
    {
        abort_unless(auth()->user()->can('manage renewal configs'), 403);

        $validator = Validator::make($request->all(), [
            'membership_category_id' => 'nullable|exists:membership_categories,id',
            'renewal_period_months'  => 'required|integer|min:1|max:120',
            'is_default'             => 'boolean',
            'effective_from'         => 'required|date',
            'effective_until'        => 'nullable|date|after_or_equal:effective_from',
        ], [
            'renewal_period_months.required' => 'Renewal period is required.',
            'renewal_period_months.integer'  => 'Renewal period must be a whole number.',
            'renewal_period_months.min'      => 'Renewal period must be at least 1 month.',
            'renewal_period_months.max'      => 'Renewal period cannot exceed 120 months.',
            'effective_from.required'        => 'Effective from date is required.',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $data = $validator->validated();
        $data['updated_by'] = auth()->id();

        // If marking as default, unset any other default (excluding this record)
        if (!empty($data['is_default'])) {
            MembershipRenewalConfig::where('is_default', true)
                ->where('id', '!=', $config->id)
                ->update(['is_default' => false]);
        }

        $config->update($data);

        return redirect()->route('admin.renewal-configs.index')
            ->with('success', 'Renewal period configuration updated successfully.');
    }

    /**
     * Delete a renewal period configuration.
     */
    public function destroy(MembershipRenewalConfig $config)
    {
        abort_unless(auth()->user()->can('manage renewal configs'), 403);

        $config->delete();

        return redirect()->route('admin.renewal-configs.index')
            ->with('success', 'Renewal period configuration deleted.');
    }
}
