<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
// $html->check_user_type("ADMIN");

$submit_btn = new button();
$submit_btn->value("ADD BOOKING");
$submit_btn->onclick("add_booking()");

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $uploadDir = "uploads/";
    $filePath = $uploadDir . basename($_FILES['file']['name']);
    // Current code is vulnerable - no file validation
    move_uploaded_file($_FILES['file']['tmp_name'], $filePath);

    // Should add validation like:
    $allowedTypes = ['application/pdf', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'];
    if (!in_array($_FILES['file']['type'], $allowedTypes)) {
        die("Invalid file type");
    }

    // Ensure output folder exists
    $outputDir = "pages/";
    if (!is_dir($outputDir)) {
        mkdir($outputDir, 0777, true);
    }

    // If file is pptx -> convert to pdf first
    $ext = pathinfo($filePath, PATHINFO_EXTENSION);
    if ($ext === "pptx") {
        $pdfPath = $uploadDir . uniqid("converted_") . ".pdf";
        // Convert pptx to pdf (requires libreoffice installed on server)
        exec("libreoffice --headless --convert-to pdf --outdir $uploadDir $filePath");
        $filePath = preg_replace('/\.pptx$/i', '.pdf', $filePath);
    }

    // Split PDF into images
    $imagick = new \Imagick();
    $imagick->setResolution(150, 150);
    $imagick->readImage($filePath);

    $pageNum = 1;
    foreach ($imagick as $page) {
        $page->setImageFormat('jpg');
        $pagePath = $outputDir . "page_" . $pageNum . ".jpg";
        $page->writeImage($pagePath);
        $pageNum++;
    }

    echo "✅ Pages saved in 'pages/' folder.<br>";
    echo "<a href='slideshow.php'>Go to slideshow</a>";
}
?>

<div class="form_down">
    <h2>Upload PDF or PPTX</h2>
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="file" required>
        <button type="submit">Upload & Split</button>
    </form>
</div>