<?php

namespace App\Http\Controllers\Owner;

use App\Http\Controllers\Controller;
use App\Models\MariachiGroup;
use App\Models\OtherCostItem;
use App\Support\OwnerWorkspace;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class OtherCostItemController extends Controller
{
    private function redirectAfterOtherCostMutation(Request $request, int $groupId, string $message)
    {
        $returnToGroupId = (int) ($request->input('return_to_group_id', $request->query('return_to_group_id', 0)) ?? 0);
        if ($returnToGroupId > 0) {
            return redirect()
                ->to(route('owner.settings.mariachi-groups.show', $returnToGroupId) . '#group-other-costs')
                ->with('status', $message);
        }

        return redirect()->route('owner.settings.other-costs', [
            'mariachi_group_id' => $groupId,
        ])->with('status', $message);
    }

    private function resolveGroup(Request $request, int $organizationId): ?MariachiGroup
    {
        if ($organizationId <= 0) {
            return null;
        }

        $query = MariachiGroup::query()
            ->where('organization_id', $organizationId);

        $requestedGroupId = (int) ($request->query('mariachi_group_id', $request->input('mariachi_group_id', 0)) ?? 0);

        if ($requestedGroupId > 0) {
            return $query->whereKey($requestedGroupId)->first();
        }

        return $query
            ->orderByDesc('is_default')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->first();
    }

    public function index(Request $request)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        $canManage = $organizationId > 0;
        $groups = $canManage ? OwnerWorkspace::groupsForOrganization($organizationId) : collect();
        $currentGroup = $canManage ? $this->resolveGroup($request, $organizationId) : null;

        if ($currentGroup) {
            $currentGroup->ensureOwnCatalog();
        }

        $items = ($canManage && $currentGroup)
            ? OtherCostItem::query()
                ->where('organization_id', $organizationId)
                ->where('mariachi_group_id', (int) $currentGroup->id)
                ->orderBy('sort_order')
                ->orderBy('name')
                ->get()
            : collect();

        return view('content.owner.settings.other-costs.index', [
            'canManageOtherCosts' => $canManage,
            'currentGroup' => $currentGroup,
            'mariachiGroups' => $groups,
            'items' => $items,
            'stats' => [
                'total' => $items->count(),
                'active' => $items->where('is_active', true)->count(),
                'inactive' => $items->where('is_active', false)->count(),
                'avg_price' => (float) ($items->avg('base_price') ?? 0),
            ],
        ]);
    }

    public function store(Request $request)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        $currentGroup = $this->resolveGroup($request, $organizationId);
        if ($organizationId <= 0 || !$currentGroup) {
            return redirect()->route('owner.settings.other-costs', [
                'mariachi_group_id' => (int) $request->input('mariachi_group_id', 0),
            ])->withErrors([
                'name' => 'Primero debes tener una organización asignada.',
            ]);
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'internal_cost' => ['required', 'numeric', 'min:0'],
            'base_price' => ['required', 'numeric', 'min:0'],
            'is_active' => ['required', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

        $baseCode = Str::slug($validated['name'], '_');
        $code = $baseCode;
        $counter = 1;
        while (
            OtherCostItem::query()
                ->where('organization_id', $organizationId)
                ->where('mariachi_group_id', (int) $currentGroup->id)
                ->where('code', $code)
                ->exists()
        ) {
            $counter++;
            $code = $baseCode . '_' . $counter;
        }

        OtherCostItem::create([
            'organization_id' => $organizationId,
            'mariachi_group_id' => (int) $currentGroup->id,
            'code' => $code,
            'name' => $validated['name'],
            'internal_cost' => $validated['internal_cost'],
            'base_price' => $validated['base_price'],
            'is_active' => (bool) $validated['is_active'],
            'sort_order' => (int) ($validated['sort_order'] ?? 100),
        ]);

        return $this->redirectAfterOtherCostMutation($request, (int) $currentGroup->id, 'Costo creado correctamente.');
    }

    public function update(Request $request, OtherCostItem $otherCostItem)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        if (
            $organizationId <= 0
            || $otherCostItem->organization_id !== $organizationId
            || !OwnerWorkspace::canAccessGroup($request->user(), (int) $otherCostItem->mariachi_group_id)
        ) {
            abort(404);
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'internal_cost' => ['required', 'numeric', 'min:0'],
            'base_price' => ['required', 'numeric', 'min:0'],
            'is_active' => ['required', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

        $otherCostItem->update([
            'name' => $validated['name'],
            'internal_cost' => $validated['internal_cost'],
            'base_price' => $validated['base_price'],
            'is_active' => (bool) $validated['is_active'],
            'sort_order' => (int) ($validated['sort_order'] ?? $otherCostItem->sort_order),
        ]);

        return $this->redirectAfterOtherCostMutation($request, (int) $otherCostItem->mariachi_group_id, 'Costo actualizado correctamente.');
    }

    public function destroy(Request $request, OtherCostItem $otherCostItem)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        if (
            $organizationId <= 0
            || $otherCostItem->organization_id !== $organizationId
            || !OwnerWorkspace::canAccessGroup($request->user(), (int) $otherCostItem->mariachi_group_id)
        ) {
            abort(404);
        }

        $groupId = (int) $otherCostItem->mariachi_group_id;
        $otherCostItem->delete();

        return $this->redirectAfterOtherCostMutation($request, $groupId, 'Costo eliminado correctamente.');
    }
}
