<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Artesaos\SEOTools\Facades\SEOTools;
use Artesaos\SEOTools\Facades\SEOMeta;

class DownloadController extends Controller
{
    public function index()
    {
        $title = 'Downloadable Forms | Polytechnic College of Davao del Sur';
        $description = settings()->site_meta_description ?? '';
        $keywords = settings()->site_meta_keywords ?? '';
        $imgURL = settings()->site_logo ? asset('images/site/' . settings()->site_logo) : '';
        $currentUrl = url()->current();

        // SEO
        SEOTools::setTitle($title);
        SEOTools::setDescription($description);
        SEOMeta::setKeywords($keywords);
        SEOTools::opengraph()->setUrl($currentUrl)->addImage($imgURL)->addProperty('type', 'articles');
        SEOTools::twitter()->setUrl($currentUrl)->setSite('@larablog')->addImage($imgURL);

        return view('front.pages.downloadable-forms', ['pageTitle' => $title]);
    }

    public function download($filename)
    {
        // Security: allow only specific known files to avoid path traversal
        $safeFilenames = [
            'enrollment-form-front' => 'ENROLLMENT-FRONT',
            'enrollment-form-back' => 'ENROLLMENT-BACK',
            'application-for-leave' => 'LEAVE-APPLI',
            'pagibig-loan' => 'MultipurposeLoanApplication',
            'sss-loan' => 'SSS-MLP',
        ];

        if (!array_key_exists($filename, $safeFilenames)) {
            abort(404, 'Invalid file requested.');
        }

        $realFile = $safeFilenames[$filename];
        $path = public_path("front/forms/{$realFile}.pdf");

        if (!file_exists($path)) {
            abort(404, 'File not found.');
        }

        return response()->download($path, "{$realFile}.pdf");
    }
}
