<?php

namespace App\Http\Controllers\Owner;

use App\Http\Controllers\Controller;
use App\Models\QuoteTransportRule;
use Illuminate\Http\Request;

class QuoteTransportRuleController extends Controller
{
    public function index(Request $request)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        $canManage = $organizationId > 0;

        $items = $canManage
            ? QuoteTransportRule::query()
                ->where('organization_id', $organizationId)
                ->orderBy('sort_order')
                ->orderBy('name')
                ->get()
            : collect();

        return view('content.owner.settings.quote-rules.index', [
            'canManageRules' => $canManage,
            'items' => $items,
        ]);
    }

    public function store(Request $request)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        if ($organizationId <= 0) {
            return back()->withErrors(['name' => 'Primero debes tener una organización asignada.']);
        }

        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'city' => ['required', 'string', 'max:120'],
            'zone_keywords' => ['nullable', 'string', 'max:255'],
            'pricing_mode' => ['required', 'in:fixed,km'],
            'fixed_amount' => ['nullable', 'numeric', 'min:0'],
            'base_km' => ['nullable', 'numeric', 'min:0'],
            'per_km_amount' => ['nullable', 'numeric', 'min:0'],
            'min_amount' => ['nullable', 'numeric', 'min:0'],
            'is_active' => ['required', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

        QuoteTransportRule::create([
            'organization_id' => $organizationId,
            'name' => trim((string) $data['name']),
            'city' => trim((string) ($data['city'] ?: '*')),
            'zone_keywords' => trim((string) ($data['zone_keywords'] ?? '')) ?: null,
            'pricing_mode' => $data['pricing_mode'],
            'fixed_amount' => (float) ($data['fixed_amount'] ?? 0),
            'base_km' => (float) ($data['base_km'] ?? 0),
            'per_km_amount' => (float) ($data['per_km_amount'] ?? 0),
            'min_amount' => (float) ($data['min_amount'] ?? 0),
            'is_active' => (bool) $data['is_active'],
            'sort_order' => (int) ($data['sort_order'] ?? 100),
        ]);

        return redirect()->route('owner.settings.quote-rules')->with('status', 'Regla de cotización creada.');
    }

    public function update(Request $request, QuoteTransportRule $quoteTransportRule)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        if ($organizationId <= 0 || $quoteTransportRule->organization_id !== $organizationId) {
            abort(404);
        }

        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'city' => ['required', 'string', 'max:120'],
            'zone_keywords' => ['nullable', 'string', 'max:255'],
            'pricing_mode' => ['required', 'in:fixed,km'],
            'fixed_amount' => ['nullable', 'numeric', 'min:0'],
            'base_km' => ['nullable', 'numeric', 'min:0'],
            'per_km_amount' => ['nullable', 'numeric', 'min:0'],
            'min_amount' => ['nullable', 'numeric', 'min:0'],
            'is_active' => ['required', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

        $quoteTransportRule->update([
            'name' => trim((string) $data['name']),
            'city' => trim((string) ($data['city'] ?: '*')),
            'zone_keywords' => trim((string) ($data['zone_keywords'] ?? '')) ?: null,
            'pricing_mode' => $data['pricing_mode'],
            'fixed_amount' => (float) ($data['fixed_amount'] ?? 0),
            'base_km' => (float) ($data['base_km'] ?? 0),
            'per_km_amount' => (float) ($data['per_km_amount'] ?? 0),
            'min_amount' => (float) ($data['min_amount'] ?? 0),
            'is_active' => (bool) $data['is_active'],
            'sort_order' => (int) ($data['sort_order'] ?? 100),
        ]);

        return redirect()->route('owner.settings.quote-rules')->with('status', 'Regla de cotización actualizada.');
    }

    public function destroy(Request $request, QuoteTransportRule $quoteTransportRule)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        if ($organizationId <= 0 || $quoteTransportRule->organization_id !== $organizationId) {
            abort(404);
        }

        $quoteTransportRule->delete();

        return redirect()->route('owner.settings.quote-rules')->with('status', 'Regla de cotización eliminada.');
    }
}

