<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\{Voucher, Router, Plan};
use App\Jobs\GenerateVouchersJob;

class VoucherController extends Controller
{
    public function index() {
        $vouchers = Voucher::latest()->paginate(50);
        $routers = Router::all();
        $plans   = Plan::all();
        return view('vouchers.index', compact('vouchers','routers','plans'));
    }

    public function generate(Request $r) {
        $r->validate(['router_id'=>'required|integer','plan_id'=>'required|integer','qty'=>'required|integer|min:1|max:200']);
        $router = Router::findOrFail($r->router_id);
        $plan   = Plan::findOrFail($r->plan_id);
        dispatch(new GenerateVouchersJob($router, $plan, (int)$r->qty, $r->user()))->onQueue('routers');
        return back()->with('ok', __('Vouchers scheduled for generation.'));
    }

    public function print(Request $r) {
        $ids = array_filter(explode(',', (string)$r->query('ids','')));
        $vouchers = Voucher::whereIn('id', $ids)->get();
        return view('vouchers.print', compact('vouchers'));
    }
}
