<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AllocationRule;
use App\Models\Company;
use App\Services\LocationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AllocationRuleController extends Controller
{
    public function __construct(protected LocationService $locationService)
    {
        $this->middleware('auth');
    }

    public function index(): View
    {
        $company = Company::primary() ?? $this->locationService->ensureCompanyAndDefaults();

        // Do NOT force-enable Split Orders on page load — toggling is admin-only via update/toggle.

        $rules = AllocationRule::query()
            ->where('company_id', $company->id)
            ->orderBy('priority')
            ->get();

        return view('admin.allocation-rules.index', compact('rules', 'company'));
    }

    public function update(Request $request, AllocationRule $allocation_rule): RedirectResponse
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'priority' => 'required|integer|min:1|max:999',
            'is_active' => 'nullable|boolean',
        ]);

        $allocation_rule->update([
            'name' => $data['name'],
            'priority' => $data['priority'],
            'is_active' => $request->boolean('is_active'),
        ]);

        return back()->with('success', 'Allocation rule updated.');
    }

    public function toggle(AllocationRule $allocation_rule): RedirectResponse
    {
        $allocation_rule->update(['is_active' => !$allocation_rule->is_active]);

        return back()->with('success', 'Rule ' . ($allocation_rule->is_active ? 'enabled' : 'disabled') . '.');
    }
}
