<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ProductCategory;
use App\Models\ProductVersion;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ProductVersionController extends Controller
{
    public function index()
    {
        $versions = ProductVersion::with('category')
            ->orderByDesc('created_at')
            ->paginate(10);

        return view('admin.product-versions.index', compact('versions'));
    }

    public function categoryVersions(ProductCategory $category)
    {
        $versions = ProductVersion::with('category')
            ->where('category_id', $category->id)
            ->where('status', 'published')
            ->orderByDesc('created_at')
            ->paginate(10);

        return view('admin.product-versions.index', compact('versions'));
    }

    /**
     * Return published versions as JSON for AJAX usage in modals
     */
    public function categoryVersionsJson(ProductCategory $category)
    {
        $versions = ProductVersion::where('category_id', $category->id)
            ->where('status', 'published')
            ->orderByDesc('created_at')
            ->get(['id','version','changelog','note','release_type','status','created_at']);

        return response()->json([
            'success' => true,
            'category' => ['id' => $category->id, 'name' => $category->name],
            'versions' => $versions,
        ]);
    }

    public function create(ProductCategory $productCategory)
    {
        return view('admin.product-versions.create', compact('productCategory'));
    }

    public function store(Request $request, ProductCategory $productCategory)
    {
        $validated = $request->validate([
            'version' => [
                'required',
                'string',
                'max:50',
                Rule::unique('product_versions', 'version')
                    ->where(fn($query) => $query->where('category_id', $productCategory->id)),
            ],
            'changelog' => ['nullable', 'string'],
            'note' => ['nullable', 'string'],
            'status' => ['required', 'in:draft,published,archived'],
            'release_type' => ['required', 'in:minor,moderate,major'],
        ]);

        $validated['category_id'] = $productCategory->id;

        ProductVersion::create($validated);

        return redirect()
            ->route('admin.product-categories.edit', $productCategory)
            ->with('success', 'Version added successfully.');
    }

    public function edit(ProductCategory $productCategory, ProductVersion $productVersion)
    {
        if ($productVersion->category_id !== $productCategory->id) {
            abort(404);
        }

        return view('admin.product-versions.edit', compact('productCategory', 'productVersion'));
    }

    public function update(Request $request, ProductCategory $productCategory, ProductVersion $productVersion)
    {
        if ($productVersion->category_id !== $productCategory->id) {
            abort(404);
        }

        $validated = $request->validate([
            'version' => [
                'required',
                'string',
                'max:50',
                Rule::unique('product_versions', 'version')
                    ->where(fn($query) => $query->where('category_id', $productCategory->id))
                    ->ignore($productVersion->id),
            ],
            'changelog' => ['nullable', 'string'],
            'note' => ['nullable', 'string'],
            'status' => ['required', 'in:draft,published,archived'],
            'release_type' => ['required', 'in:minor,moderate,major'],
        ]);

        $productVersion->update($validated);

        return redirect()
            ->route('admin.product-categories.edit', $productCategory)
            ->with('success', 'Version updated successfully.');
    }

    public function destroy(ProductCategory $productCategory, ProductVersion $productVersion)
    {
        if ($productVersion->category_id !== $productCategory->id) {
            abort(404);
        }

        $productVersion->delete();

        return redirect()
            ->route('admin.product-categories.edit', $productCategory)
            ->with('success', 'Version deleted successfully.');
    }
}
