<?php

namespace App\Http\Controllers\Owner;

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

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

        return redirect()->route('owner.settings.artists', [
            '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)
            ? ArtistItem::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.artists.index', [
            'canManageArtists' => $canManage,
            'currentGroup' => $currentGroup,
            'mariachiGroups' => $groups,
            'items' => $items,
            'stats' => [
                'total' => $items->count(),
                'included' => $items->where('type', ArtistItem::TYPE_INCLUDED)->count(),
                'additional' => $items->where('type', ArtistItem::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.artists', [
                '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'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

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

        ArtistItem::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'],
            'sort_order' => (int) ($validated['sort_order'] ?? 100),
        ]);

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

    public function update(Request $request, ArtistItem $artistItem)
    {
        $organizationId = (int) ($request->user()->organization_id ?? 0);
        if (
            $organizationId <= 0
            || $artistItem->organization_id !== $organizationId
            || !OwnerWorkspace::canAccessGroup($request->user(), (int) $artistItem->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'],
            'sort_order' => ['nullable', 'integer', 'min:0', 'max:9999'],
        ]);

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

        return $this->redirectAfterArtistMutation($request, (int) $artistItem->mariachi_group_id, 'Artista actualizado correctamente.');
    }

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

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

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