<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Classroom;
use App\Models\Student;
use App\Models\Setting;
use Illuminate\Http\Request;

class PrintCardController extends Controller
{
    public function index()
    {
        $classrooms = Classroom::when(request()->q, function($classrooms) {
            $classrooms = $classrooms->where('title', 'like', '%'. request()->q . '%');
        })->latest()->paginate(5);
        
        $classrooms->appends(['q' => request()->q]);

        return inertia('Admin/PrintCard/Index', [
            'classrooms' => $classrooms,
        ]);
    }

    public function getStudents(Classroom $classroom)
    {
        $students = Student::where('classroom_id', $classroom->id)->get();
        return response()->json($students);
    }

    public function print(Request $request)
    {
        $request->validate([
            'student_ids'   => 'required|array|min:1',
            'student_ids.*' => 'integer',
            'paper_size'    => 'required|string|in:A4,Letter,Legal',
        ]);

        $students = Student::whereIn('id', $request->student_ids)
            ->with('classroom')
            ->get();

        $setting = Setting::first();

        return view('print.exam-cards', [
            'students'   => $students,
            'setting'    => $setting,
            'paper_size' => $request->paper_size,
        ]);
    }
}
