<?php
// scraper.php
header('Content-Type: application/json');

$allowedCategories = ['images', 'pdfs', 'archives', 'videos', 'misc'];

function loadJson($file) {
    if (file_exists($file)) {
        return json_decode(file_get_contents($file), true) ?: ['category' => '', 'totalItems' => 0, 'items' => []];
    }
    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);
    }
}

function getFileMetadata($filepath) {
    $info = [
        'size' => round(filesize($filepath) / (1024 * 1024), 1) . ' MB',
        'format' => strtoupper(pathinfo($filepath, PATHINFO_EXTENSION)),
        'dimensions' => '',
        'description' => 'Scanned file: ' . basename($filepath)
    ];

    $ext = strtolower(pathinfo($filepath, PATHINFO_EXTENSION));

    if (in_array($ext, ['jpg','jpeg','png','gif','webp']) && function_exists('exif_read_data')) {
        $exif = @exif_read_data($filepath);
        if ($exif && isset($exif['COMPUTED'])) {
            $info['dimensions'] = ($exif['COMPUTED']['Width'] ?? '') . 'x' . ($exif['COMPUTED']['Height'] ?? '');
        }
    }

    return $info;
}

$response = ['success' => false, 'messages' => []];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $category = $_POST['category'] ?? '';
    $folder = $_POST['folder'] ?? '';

    if (!in_array($category, $allowedCategories)) {
        $response['message'] = "Invalid category.";
    } elseif (empty($folder) || !is_dir($folder)) {
        $response['message'] = "Folder does not exist or is invalid.";
    } else {
        $jsonFile = "data/{$category}.json";
        $data = loadJson($jsonFile);
        $data['category'] = $category;

        $files = scandir($folder);
        $added = 0;
        $updated = 0;

        foreach ($files as $file) {
            if ($file === '.' || $file === '..') continue;

            $filepath = $folder . '/' . $file;
            if (!is_file($filepath)) continue;

            $filename = $file;
            $title = pathinfo($filename, PATHINFO_FILENAME);

            // Check if file already exists in JSON
            $exists = false;
            foreach ($data['items'] as &$item) {
                if (basename($item['full'] ?? '') === $filename) {
                    $exists = true;
                    // Update missing metadata
                    $meta = getFileMetadata($filepath);
                    if (empty($item['size'])) $item['size'] = $meta['size'];
                    if (empty($item['format'])) $item['format'] = $meta['format'];
                    if (empty($item['dimensions'])) $item['dimensions'] = $meta['dimensions'];
                    if (empty($item['description'])) $item['description'] = $meta['description'];
                    $updated++;
                    break;
                }
            }

            if (!$exists) {
                $meta = getFileMetadata($filepath);

                // Determine thumb path
                $thumbPath = '';
                if ($category === 'images') {
                    $thumbPath = 'assets/images/thumbs/' . $filename;
                } else {
                    $thumbPath = 'assets/archives/thumbs/' . strtolower($meta['format']) . '-icon.png';
                }

                $newItem = [
                    "id" => $category . '-' . str_pad(count($data['items']) + 1, 3, '0', STR_PAD_LEFT),
                    "title" => $title,
                    "slug" => strtolower(str_replace([' ', '_'], '-', $title)),
                    "location" => $filepath,
                    "full" => $filepath,
                    "thumb" => $thumbPath,
                    "size" => $meta['size'],
                    "format" => $meta['format'],
                    "dimensions" => $meta['dimensions'],
                    "description" => $meta['description'],
                    "homepage" => "",
                    "tags" => [],
                    "dateAdded" => date('Y-m-d')
                ];

                $data['items'][] = $newItem;
                $added++;
            }
        }

        $data['totalItems'] = count($data['items']);
        saveJson($jsonFile, $data);
        updateDbJson($category);

        $response['success'] = true;
        $response['messages'][] = "Scanned folder: <strong>$folder</strong>";
        $response['messages'][] = "Added: <strong>$added</strong> new files";
        $response['messages'][] = "Updated: <strong>$updated</strong> existing entries";
        $response['messages'][] = "Total items in $category.json: " . $data['totalItems'];
    }
}

echo json_encode($response);
?>