<?php

namespace App\Http\Controllers;

use App\Models\AdmissionGuide;
use Barryvdh\DomPDF\Facade\Pdf;

class AdmissionGuideController extends Controller
{
    public function index()
    {
        $guides = AdmissionGuide::with('country')->paginate(12);

        return view('admission-guides.index', compact('guides'));
    }

    public function show($slug)
    {
        $guide = AdmissionGuide::with('country')->where('slug', $slug)->firstOrFail();

        // Ensure $steps is always an array
        $steps = $guide->content;
        if (is_string($steps)) {
            $steps = json_decode($steps, true) ?? [];
        }
        if (! is_array($steps)) {
            $steps = [];
        }

        return view('admission-guides.show', compact('guide', 'steps'));
    }

    public function downloadChecklist($slug)
    {
        $guide = AdmissionGuide::where('slug', $slug)->firstOrFail();

        // Handle content as array or string
        $steps = $guide->content;
        if (is_string($steps)) {
            $steps = json_decode($steps, true) ?? [];
        }
        if (! is_array($steps)) {
            $steps = [];
        }

        $pdf = Pdf::loadView('admission-guides.pdf-checklist', compact('guide', 'steps'));

        return $pdf->download("checklist-{$guide->slug}.pdf");
    }
}
