<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\admin\CreateVersionStore;
use App\Http\Requests\admin\UpdateVersionStore;
use App\Models\Version;
use Illuminate\Http\Request;

class VersionController extends Controller
{
    public function index(Request $request)
    {
        $query = Version::query();

        if ($request->filled('q')) {
            $q = $request->q;
            $query->where(function ($qry) use ($q) {
                $qry->where('code', 'like', "%{$q}%")
                    ->orWhere('number', 'like', "%{$q}%")
                    ->orWhere('type', 'like', "%{$q}%");
            });
        }

        $perPage = min(max((int) $request->input('per_page', 15), 10), 100);
        $versions = $query->paginate($perPage)->withQueryString();

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

    public function create()
    {
        return view('admin.versions.create');
    }

    public function store(CreateVersionStore $request)
    {
        $validated = $request->validated();
        if (isset($validated['force_update'])) {
            $validated['force_update'] = $validated['force_update'] == 'on' ? 1 : 0;
        }
        Version::create($validated);
        return redirect(route('versions.index'));
    }

    public function edit(Version $version)
    {
        return view('admin.versions.update', compact('version'));
    }

    public function update(UpdateVersionStore $request, Version $version)
    {
        $validated = $request->validated();
        if (isset($validated['force_update'])) {
            $validated['force_update'] = $validated['force_update'] == 'on' ? 1 : 0;
        }
        $version->update($validated);
        return redirect(route('versions.index'));
    }

    public function destroy(Version $version)
    {
        $version->delete();
        return redirect(route('versions.index'));
    }
}
