<?php
declare(strict_types=1);

function securePdfUpload(array $file): string
{
    if ($file['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Upload failed.');
    }

    if ($file['size'] > 2097152) {
        throw new RuntimeException('Maximum file size is 2 MB.');
    }

    $name = basename($file['name']);

    if (!preg_match('/^[A-Za-z0-9._ -]+\.pdf$/i', $name)) {
        throw new RuntimeException('Invalid filename.');
    }

    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if ($ext !== 'pdf') {
        throw new RuntimeException('Only PDF allowed.');
    }

    if (preg_match('/\.(php|phtml|phar|exe|js|jsp|asp)\./i', $name)) {
        throw new RuntimeException('Invalid filename.');
    }

$finfo = finfo_open(FILEINFO_MIME_TYPE);

$mime = finfo_file($finfo, $file['tmp_name']);

finfo_close($finfo);

if ($mime !== 'application/pdf') {
    throw new RuntimeException('Invalid PDF.');
}

    $fp=fopen($file['tmp_name'],'rb');
    $sig=fread($fp,4);
    fclose($fp);

    if ($sig !== '%PDF') {
        throw new RuntimeException('Fake PDF.');
    }

    $target = dirname(__DIR__,2).'/student/files/'.$name;

    if (file_exists($target)) {
        throw new RuntimeException('PDF already exists.');
    }

    if (!move_uploaded_file($file['tmp_name'],$target)) {
        throw new RuntimeException('Unable to save PDF.');
    }

    return $name;
}
