<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);

// Clean any previous output
if (ob_get_level()) { ob_end_clean(); }

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_FILES["images"]["name"][0])) {
        die("No files uploaded.");
    }

    $zipName = "converted_" . time() . ".zip";
    $zip = new ZipArchive();

    if ($zip->open($zipName, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== TRUE) {
        die("Failed to create ZIP file.");
    }

    $files = $_FILES["images"];

    // --- DPI BLOCK FOR 300 DPI ---
    $hex = chr(0x01) . chr(0x2C); // 300 DPI = 0x012C

    $jfif =
        "\xFF\xE0" .     // APP0 Marker
        "\x00\x10" .     // Block size
        "JFIF\0" .       // Identifier
        "\x01\x02" .     // Version
        "\x01" .         // DPI flag
        $hex .           // X DPI
        $hex .           // Y DPI
        "\x00\x00";      // Thumbnail

    // Loop images
    for ($i = 0; $i < count($files["name"]); $i++) {

        $tmp = $files["tmp_name"][$i];
        $filename = pathinfo($files["name"][$i], PATHINFO_FILENAME);

        if (!file_exists($tmp)) continue;

        $imgData = file_get_contents($tmp);
        $img = imagecreatefromstring($imgData);

        if (!$img) continue;

        // Capture JPEG
        ob_start();
        imagejpeg($img, NULL, 100);
        $jpeg = ob_get_clean();

        // Replace JFIF block with 300 DPI
        $jpeg = preg_replace('/\xFF\xE0....JFIF\0.{7}/', $jfif, $jpeg, 1);

        // Add to ZIP
        $zip->addFromString($filename . "_300dpi.jpg", $jpeg);

        imagedestroy($img);
    }

    $zip->close();

    // Send ZIP file
    clearstatcache();
    header("Content-Type: application/zip");
    header("Content-Disposition: attachment; filename=\"$zipName\"");
    header("Content-Length: " . filesize($zipName));  // <-- FIXED LINE
    header("Content-Transfer-Encoding: binary");

    while (ob_get_level()) { ob_end_clean(); }

    readfile($zipName);
    unlink($zipName);
    exit;
}
?>

<!DOCTYPE html>
<html>
<head><title>300 DPI Converter</title></head>
<body>

<h2>Select Images → Convert to 300 DPI → Download ZIP</h2>

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="images[]" multiple required accept=".jpg,.jpeg,.png">
    <br><br>
    <button type="submit">Convert</button>
</form>

</body>
</html>
