<?php
// uploader.php
$categories = [
    'images'   => ['folder' => 'assets/images/fulls',   'thumb_folder' => 'assets/images/thumbs',   'ext' => ['jpg','jpeg','png','gif','webp']],
    'archives' => ['folder' => 'assets/archives',      'thumb_folder' => 'assets/archives/thumbs', 'ext' => ['zip','rar','7z','tar','gz']],
    'pdfs'     => ['folder' => 'assets/pdfs',          'thumb_folder' => 'assets/pdfs/thumbs',     'ext' => ['pdf']],
    // Add more categories here
];

function loadJson($file) {
    if (file_exists($file)) {
        return json_decode(file_get_contents($file), true);
    }
    return ['category' => '', 'totalItems' => 0, 'items' => []];
}

function saveJson($file, $data) {
    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

function updateDbJson($category) {
    $dbFile = 'data/db.json';
    $db = loadJson($dbFile);
    if (!isset($db['categories'][$category])) {
        $db['categories'][$category] = [
            'name' => ucfirst($category),
            'file' => $category . '.json',
            'type' => $category
        ];
        saveJson($dbFile, $db);
    }
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['file'])) {
    $catKey = $_POST['category'] ?? '';
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');

    if (!isset($categories[$catKey])) {
        $message = "Invalid category!";
    } else {
        $file = $_FILES['file'];
        if ($file['error'] === UPLOAD_ERR_OK) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $filename = basename($file['name']);
            $catConfig = $categories[$catKey];

            // Use filename as title if empty
            if (empty($title)) {
                $title = pathinfo($filename, PATHINFO_FILENAME);
            }

            $uploadDir = $catConfig['folder'] . '/';
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

            $targetPath = $uploadDir . $filename;
            $thumbPath = '';

            // Move uploaded file
            if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                $filesize = filesize($targetPath);
                $sizeStr = round($filesize / (1024*1024), 1) . ' MB';

                // Generate thumbnail for images
                if ($catKey === 'images' && in_array($ext, $catConfig['ext'])) {
                    $thumbDir = $catConfig['thumb_folder'] . '/';
                    if (!is_dir($thumbDir)) mkdir($thumbDir, 0755, true);
                    $thumbPath = $thumbDir . $filename;

                    // Simple GD thumbnail (400px width)
                    list($width, $height) = getimagesize($targetPath);
                    $newWidth = 400;
                    $newHeight = (int)($height * $newWidth / $width);

                    $src = imagecreatefromstring(file_get_contents($targetPath));
                    $dst = imagecreatetruecolor($newWidth, $newHeight);
                    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
                    imagejpeg($dst, $thumbPath, 85);
                    imagedestroy($src);
                    imagedestroy($dst);
                } else {
                    // Default icon for non-images
                    $thumbPath = 'assets/archives/thumbs/' . strtolower($ext) . '-icon.png';
                }

                // Extract basic EXIF / metadata
                $dimensions = '';
                $exifInfo = '';
                if ($catKey === 'images' && function_exists('exif_read_data')) {
                    $exif = @exif_read_data($targetPath);
                    if ($exif) {
                        $dimensions = ($exif['COMPUTED']['Width'] ?? $width) . 'x' . ($exif['COMPUTED']['Height'] ?? $height);
                        $exifInfo = $exif['Model'] ?? '';
                    }
                }

                // Load and update category JSON
                $jsonFile = "data/{$catKey}.json";
                $data = loadJson($jsonFile);
                $data['category'] = $catKey;

                $newItem = [
                    "id" => $catKey . '-' . str_pad(count($data['items']) + 1, 3, '0', STR_PAD_LEFT),
                    "title" => $title,
                    "slug" => strtolower(str_replace(' ', '-', $title)),
                    "location" => $targetPath,
                    "full" => $targetPath,
                    "thumb" => $thumbPath,
                    "size" => $sizeStr,
                    "format" => strtoupper($ext),
                    "dimensions" => $dimensions,
                    "description" => $description ?: "Uploaded file: " . $filename,
                    "homepage" => "",
                    "tags" => [],
                    "dateAdded" => date('Y-m-d')
                ];

                $data['items'][] = $newItem;
                $data['totalItems'] = count($data['items']);

                saveJson($jsonFile, $data);
                updateDbJson($catKey);

                $message = "File uploaded successfully! Added to <strong>$catKey</strong>.";
            } else {
                $message = "Failed to upload file.";
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Uploader</title>
  <style>
    body { font-family: Arial, sans-serif; margin: 40px; background: #f4f4f4; }
    .container { max-width: 700px; margin: auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
    input, select, textarea { width: 100%; padding: 10px; margin: 8px 0; }
    button { padding: 12px 24px; background: #0066cc; color: white; border: none; border-radius: 6px; cursor: pointer; }
    .message { padding: 15px; margin: 15px 0; background: #d4edda; color: #155724; border-radius: 6px; }
  </style>
</head>
<body>
  <div class="container">
    <h1>File Uploader</h1>
    <?php if ($message) echo "<div class='message'>$message</div>"; ?>

    <form method="post" enctype="multipart/form-data">
      <label>Category</label>
      <select name="category" required>
        <option value="">-- Select Category --</option>
        <?php foreach (array_keys($categories) as $cat): ?>
          <option value="<?= $cat ?>"><?= ucfirst($cat) ?></option>
        <?php endforeach; ?>
      </select>

      <label>File</label>
      <input type="file" name="file" required>

      <label>Title (optional - uses filename if empty)</label>
      <input type="text" name="title" placeholder="Nice title for the file">

      <label>Description (optional)</label>
      <textarea name="description" rows="3" placeholder="Short description..."></textarea>

      <button type="submit">Upload & Add to Database</button>
    </form>
  </div>
</body>
</html>