<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use App\Models\Deal;
use App\Models\Item;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;

class DealController extends Controller
{
    public function index(): View
    {
        $branchId = auth()->user()->active_branch_id;
        $deals = Deal::where('branch_id', $branchId)->with('slots.items.item', 'slots.items.variant')->get();

        return view('portal.deals.index', compact('deals'));
    }

    public function create(): View
    {
        $branchId = auth()->user()->active_branch_id;
        $items = Item::forBranch($branchId)->with('variants')->where('is_active', true)->get();

        return view('portal.deals.create', compact('items'));
    }

    public function store(Request $request): RedirectResponse
    {
        $branchId = auth()->user()->active_branch_id;

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'available_days' => 'nullable|array',
            'slots' => 'required|array|min:1',
            'slots.*.name' => 'required|string|max:255',
            'slots.*.selections' => 'required|array|min:1',
        ]);

        DB::transaction(function () use ($validated, $branchId) {
            $deal = Deal::create([
                'branch_id' => $branchId,
                'name' => $validated['name'],
                'description' => $validated['description'],
                'price' => $validated['price'],
                'available_days' => $validated['available_days'] ?? null,
                'is_active' => true,
            ]);

            foreach ($validated['slots'] as $slotData) {
                $slot = $deal->slots()->create([
                    'name' => $slotData['name'],
                    'quantity' => 1,
                ]);

                foreach ($slotData['selections'] as $selection) {
                    // Selection is "item_id:variant_id" or "item_id"
                    $parts = explode(':', $selection);
                    $itemId = $parts[0];
                    $variantId = isset($parts[1]) ? $parts[1] : null;

                    $slot->items()->create([
                        'item_id' => $itemId,
                        'variant_id' => $variantId,
                    ]);
                }
            }
        });

        return redirect()->route('portal.deals.index')->with('success', 'Deal created successfully.');
    }

    public function edit(Deal $deal): View
    {
        $this->authorizeAccess($deal);
        $branchId = auth()->user()->active_branch_id;
        $items = Item::forBranch($branchId)->with('variants')->where('is_active', true)->get();
        $deal->load('slots.items');

        return view('portal.deals.edit', compact('deal', 'items'));
    }

    public function update(Request $request, Deal $deal): RedirectResponse
    {
        $this->authorizeAccess($deal);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'available_days' => 'nullable|array',
            'slots' => 'required|array|min:1',
            'slots.*.name' => 'required|string|max:255',
            'slots.*.selections' => 'required|array|min:1',
        ]);

        DB::transaction(function () use ($validated, $deal) {
            $deal->update([
                'name' => $validated['name'],
                'description' => $validated['description'],
                'price' => $validated['price'],
                'available_days' => $validated['available_days'] ?? null,
            ]);

            $deal->slots()->delete();

            foreach ($validated['slots'] as $slotData) {
                $slot = $deal->slots()->create([
                    'name' => $slotData['name'],
                    'quantity' => 1,
                ]);

                foreach ($slotData['selections'] as $selection) {
                    $parts = explode(':', $selection);
                    $itemId = $parts[0];
                    $variantId = isset($parts[1]) ? $parts[1] : null;

                    $slot->items()->create([
                        'item_id' => $itemId,
                        'variant_id' => $variantId,
                    ]);
                }
            }
        });

        return redirect()->route('portal.deals.index')->with('success', 'Deal updated successfully.');
    }

    public function destroy(Deal $deal): RedirectResponse
    {
        $this->authorizeAccess($deal);
        $deal->delete();

        return redirect()->route('portal.deals.index')->with('success', 'Deal deleted successfully.');
    }

    protected function authorizeAccess(Deal $deal): void
    {
        if ($deal->branch_id !== auth()->user()->active_branch_id) {
            abort(403);
        }
    }
}
