<?php

namespace App\Http\Controllers\Owner;

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

class GiftItemController extends Controller
{
    private function redirectAfterGiftMutation(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-gifts')
                ->with('status', $message);
        }

        return redirect()->route('owner.settings.gifts', [
            '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)
            ? GiftItem::query()
                ->where('organization_id', $organizationId)
                ->where('mariachi_group_id', (int) $currentGroup->id)
                ->orderBy('type')
                ->orderBy('sort_order')
                ->orderBy('name')
                ->get()
            : collect();

        return view('content.owner.settings.gifts.index', [
            'canManageGifts' => $canManage,
            'currentGroup' => $currentGroup,
            'mariachiGroups' => $groups,
            'items' => $items,
            'stats' => [
                'total' => $items->count(),
                'included' => $items->where('type', GiftItem::TYPE_INCLUDED)->count(),
                'additional' => $items->where('type', GiftItem::TYPE_ADDITIONAL)->count(),
                'active' => $items->where('is_active', true)->count(),
            ],
        ]);
    }

    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.gifts', [
                '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'],
            'type' => ['required', 'in:included,additional'],
            'internal_cost' => ['required', 'numeric', 'min:0'],
            'base_price' => ['required', 'numeric', 'min:0'],
            'is_active' => ['required', 'boolean'],
            'is_default' => ['required', 'boolean'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

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

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

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

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

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

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

        return $this->redirectAfterGiftMutation($request, (int) $giftItem->mariachi_group_id, 'Obsequio actualizado correctamente.');
    }

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

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

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