<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\admin\SubscribePlan\CreateRequest;
use App\Http\Requests\admin\SubscribePlan\UpdateRequest;
use App\Models\SubscribePlan;
use Illuminate\Http\Request;

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

        if ($request->filled('q')) {
            $q = $request->q;
            $query->where('name', 'like', "%{$q}%");
        }

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

        return view('admin.subscribe-plans.index', compact('subscribePlans'));
    }

    public function create()
    {
        return view('admin.subscribe-plans.create');
    }

    public function store(CreateRequest $request)
    {
        $validated = $request->validated();
        $validated['is_active'] = $request->has('is_active');
        $validated['is_free'] = $request->has('is_free');

        SubscribePlan::create($validated);
        return redirect()->route('subscribe-plans.index');   
    }


    public function edit(SubscribePlan $subscribePlan)
    {
        return view('admin.subscribe-plans.update', compact('subscribePlan'));
    }
    
    public function update(UpdateRequest $request, SubscribePlan $subscribePlan)
    {
        $validated = $request->validated();
        $validated['is_active'] = $request->has('is_active');
        $validated['is_free'] = $request->has('is_free');

        $subscribePlan->update($validated);
        return redirect()->route('subscribe-plans.index');   
    }

    public function destroy(SubscribePlan $subscribePlan)
    {
        $subscribePlan->delete();
        return redirect()->route('subscribe-plans.index');
    }
}
