<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AgeType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AgeTypeController extends Controller
{
    public function index()
    {
        $ageTypes = AgeType::where('shop_id', $this->shopId())
            ->orderBy('display_order')
            ->get();

        return view('admin.age-types.index', compact('ageTypes'));
    }

    public function store(Request $request)
    {
        $this->authorizeManage();

        $data = $request->validate([
            'name' => 'required|string|max:255',
            'name_ta' => 'nullable|string|max:255',
        ]);

        $maxOrder = AgeType::where('shop_id', $this->shopId())->max('display_order') ?? 0;

        AgeType::create([
            'shop_id' => $this->shopId(),
            'name' => $data['name'],
            'name_ta' => $data['name_ta'] ?? null,
            'display_order' => $maxOrder + 1,
        ]);

        return back()->with('status', "Age type \"{$data['name']}\" added.");
    }

    public function update(Request $request, AgeType $ageType)
    {
        abort_unless($ageType->shop_id === $this->shopId(), 403);
        $this->authorizeManage();

        $data = $request->validate([
            'name' => 'required|string|max:255',
            'name_ta' => 'nullable|string|max:255',
        ]);

        $ageType->update($data);

        return back()->with('status', "Age type updated.");
    }

    public function destroy(AgeType $ageType)
    {
        abort_unless($ageType->shop_id === $this->shopId(), 403);
        $this->authorizeManage();

        // Prevent deleting an age type that's actually been used in past orders,
        // to avoid orphaning historical order_items.
        if ($ageType->prices()->whereHas('shopGarment')->exists() &&
            \App\Models\OrderItem::where('age_type_id', $ageType->id)->exists()) {
            return back()->withErrors(['delete' => "Can't delete \"{$ageType->name}\" — it's used in existing orders."]);
        }

        $ageType->delete();

        return back()->with('status', "Age type deleted.");
    }

    public function reorder(Request $request)
    {
        $this->authorizeManage();

        $data = $request->validate(['order' => 'required|array']);

        foreach ($data['order'] as $index => $id) {
            AgeType::where('id', $id)->where('shop_id', $this->shopId())->update(['display_order' => $index]);
        }

        return response()->json(['status' => 'ok']);
    }

    protected function authorizeManage(): void
    {
        abort_unless(Auth::guard('admin')->user()->hasPermission('products.manage'), 403);
    }

    protected function shopId(): int
    {
        return Auth::guard('admin')->user()->shop_id;
    }
}
