<?php

namespace App\Http\Controllers;

use App\Models\SiblingDiscountRule;
use App\Support\BranchContext;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Illuminate\View\View;

class SiblingDiscountController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:fees.view', only: ['index']),
            new Middleware('can:fees.update', only: ['store', 'destroy']),
        ];
    }

    public function index(): View
    {
        $rules = SiblingDiscountRule::orderBy('child_order')->get();

        return view('fees.sibling.index', compact('rules'));
    }

    public function store(Request $request, BranchContext $context): RedirectResponse
    {
        $data = $request->validate([
            'child_order' => ['required', 'integer', 'min:1', 'max:20'],
            'type' => ['required', 'in:percentage,fixed'],
            'value' => ['required', 'numeric', 'min:0'],
        ]);
        $branchId = $context->currentId() ?? auth()->user()->branch_id;

        SiblingDiscountRule::updateOrCreate(
            ['branch_id' => $branchId, 'child_order' => $data['child_order']],
            ['type' => $data['type'], 'value' => $data['value'], 'is_active' => true]
        );

        return back()->with('success', 'Sibling discount rule saved.');
    }

    public function destroy(SiblingDiscountRule $siblingDiscount): RedirectResponse
    {
        $siblingDiscount->delete();

        return back()->with('success', 'Rule removed.');
    }
}
