<?php
require 'vendor/autoload.php';
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\SimpleType\Jc;

function getAllPngFiles($dir) {
    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    $pngFiles = [];
    foreach ($rii as $file) {
        if (!$file->isDir() && preg_match('/\.(png|PNG)$/', $file->getFilename())) {
            $pngFiles[] = $file->getPathname();
        }
    }
    return $pngFiles;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['qrzip']) || $_FILES['qrzip']['error'] !== 0) {
        die("Upload failed.");
    }

    $uploadDir = 'uploads/';
    if (!is_dir($uploadDir)) mkdir($uploadDir);
    $zipPath = $uploadDir . basename($_FILES['qrzip']['name']);
    move_uploaded_file($_FILES['qrzip']['tmp_name'], $zipPath);

    $extractDir = $uploadDir . 'extracted/';
    if (!is_dir($extractDir)) mkdir($extractDir);

    $zip = new ZipArchive;
    if ($zip->open($zipPath) === TRUE) {
        $zip->extractTo($extractDir);
        $zip->close();
    } else {
        die("Failed to extract ZIP file.");
    }
    unlink($zipPath);

    $files = getAllPngFiles($extractDir);
    if (count($files) == 0) die("No PNG files found in zip.");

    $gradeName = pathinfo($_FILES['qrzip']['name'], PATHINFO_FILENAME);
    $outputDocx = "qr_" . $gradeName . ".docx";

    $phpWord = new PhpWord();
    $section = $phpWord->addSection();
    // Table style: no border, no margin, center alignment
    $phpWord->addTableStyle('qrTable', [
        'alignment' => Jc::CENTER
    ]);
    $table = $section->addTable('qrTable');

    // --- 150x150px SETTINGS ---
    $imgWidth = 150; // pixels
    $imgHeight = 150; // pixels
    $cellWidth = 2000; // twips, ~2cm for spacing

    $perRow = 3;
    $count = 0;

    sort($files);

    foreach ($files as $file) {
        $filename = basename($file, '.png');
        $filename = basename($filename, '.PNG');
        $parts = preg_split('/_+/', $filename);

        // Format name as LAST, FIRST MIDDLE if possible
        $last = isset($parts[0]) ? strtoupper(trim($parts[0])) : '';
        $first = isset($parts[1]) ? strtoupper(trim($parts[1])) : '';
        $middle = isset($parts[2]) ? strtoupper(trim($parts[2])) : '';
        $name = $last;
        if ($first !== '' || $middle !== '') {
            $name .= ', ' . $first;
            if ($middle !== '') {
                $name .= ' ' . $middle;
            }
        }

        if ($count % $perRow === 0) $table->addRow();

        $cell = $table->addCell($cellWidth, [
            'valign' => 'center'
        ]);
        // Use original size, no stretching
        if (file_exists($file)) {
            $cell->addImage(realpath($file), [
                'width' => $imgWidth,
                'height' => $imgHeight,
                'alignment' => Jc::CENTER
            ]);
        } else {
            $cell->addText("Image not found", ['size' => 8]);
        }

        // Centered name below QR
        $cell->addText($name, ['size' => 10, 'bold' => true], ['alignment' => Jc::CENTER]);
        $count++;
    }

    $writer = IOFactory::createWriter($phpWord, 'Word2007');
    $writer->save($outputDocx);

    // Clean up extracted files and directory
    foreach ($files as $f) unlink($f);
    $dirIter = new RecursiveDirectoryIterator($extractDir, RecursiveDirectoryIterator::SKIP_DOTS);
    $iter = new RecursiveIteratorIterator($dirIter, RecursiveIteratorIterator::CHILD_FIRST);
    foreach ($iter as $path) {
        $path->isDir() ? rmdir($path) : unlink($path);
    }
    rmdir($extractDir);

    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=\"$outputDocx\"");
    header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
    header("Content-Length: " . filesize($outputDocx));
    readfile($outputDocx);
    unlink($outputDocx);
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Upload QR ZIP</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 40px;
      background-color: #121212;
      color: #f0f0f0;
    }
    .container {
      max-width: 400px;
      margin: auto;
      padding: 20px;
      border: 1px solid #444;
      border-radius: 10px;
      background-color: #1e1e1e;
    }
    h2 { text-align: center; color: #ffffff; }
    input[type=file] {
      display: block;
      margin: 20px auto;
      background-color: #2a2a2a;
      color: #ffffff;
      border: none;
      padding: 10px;
      border-radius: 5px;
    }
    button {
      display: block;
      margin: 0 auto;
      padding: 10px 20px;
      font-size: 16px;
      cursor: pointer;
      background-color: #2e7d32;
      color: #fff;
      border: none;
      border-radius: 5px;
    }
    button:hover {
      background-color: #388e3c;
    }
    .back-btn {
      display: block;
      width: 100%;
      margin: 0 0 18px 0;
      background: #007bff;
      color: #fff;
      font-weight: bold;
      font-size: 15px;
      border-radius: 5px;
      border: none;
      text-align: center;
      text-decoration: none;
      padding: 10px 0;
      transition: background 0.2s;
    }
    .back-btn:hover {
      background: #0056b3;
    }
  </style>
</head>
<body>
  <div class="container">
    <a href="dashboard.php" class="back-btn">&larr; Back to Dashboard</a>
    <h2>Upload ZIP of QR Images</h2>
    <form method="POST" enctype="multipart/form-data">
      <input type="file" name="qrzip" accept=".zip" required>
      <button type="submit">Upload & Generate Word File</button>
    </form>
  </div>
</body>
</html>