<?php
session_start();
require_once '../includes/auth.php';

header('Content-Type: application/json; charset=utf-8');

if (!function_exists('prd_img_slugify')) {
    function prd_img_slugify($text) {
        $text = trim((string)$text);
        $text = preg_replace('/\s+/u', '-', $text);
        $text = preg_replace('/[^\p{Arabic}\p{L}\p{N}\-_]+/u', '-', $text);
        $text = preg_replace('/-+/u', '-', $text);
        $text = trim($text, '-');
        $text = mb_strtolower($text, 'UTF-8');
        return $text !== '' ? $text : 'general';
    }
}

function prd_img_safe_folder($folder) {
    $folder = trim((string)$folder);
    $folder = basename($folder);
    $folder = preg_replace('/[^\p{Arabic}\p{L}\p{N}\-_]+/u', '', $folder);
    return trim($folder, '.-/\\');
}

$brand = trim((string)($_GET['brand'] ?? ''));
$brandSlug = prd_img_slugify($brand);
$mode = trim((string)($_GET['mode'] ?? 'folders'));
$folder = prd_img_safe_folder($_GET['folder'] ?? '');

$baseFs = dirname(__DIR__) . '/uploads/products/';
$baseUrl = '../uploads/products/';
$allowedExt = ['jpg','jpeg','png','webp','gif'];

function prd_img_count_images($dirFs, $allowedExt) {
    if (!is_dir($dirFs)) return 0;
    $files = @scandir($dirFs) ?: [];
    $count = 0;
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') continue;
        $full = rtrim($dirFs, '/\\') . DIRECTORY_SEPARATOR . $file;
        if (!is_file($full)) continue;
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (in_array($ext, $allowedExt, true)) $count++;
    }
    return $count;
}

function prd_img_collect_images($dirFs, $relPrefix, $baseUrl, $allowedExt, $limit = 240) {
    $images = [];
    if (!is_dir($dirFs)) return $images;
    $files = @scandir($dirFs) ?: [];
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') continue;
        $full = rtrim($dirFs, '/\\') . DIRECTORY_SEPARATOR . $file;
        if (is_dir($full)) continue;
        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExt, true)) continue;
        $rel = ltrim($relPrefix . $file, '/');
        $images[] = [
            'path' => $rel,
            'name' => $file,
            'url'  => $baseUrl . str_replace('%2F', '/', rawurlencode($rel)),
            'mtime'=> @filemtime($full) ?: 0,
        ];
        if (count($images) >= $limit) break;
    }
    usort($images, function($a, $b){ return ($b['mtime'] ?? 0) <=> ($a['mtime'] ?? 0); });
    return $images;
}

try {
    if (!is_dir($baseFs)) {
        @mkdir($baseFs, 0775, true);
    }

    if ($mode === 'images') {
        if ($folder === '' || !is_dir($baseFs . $folder)) {
            echo json_encode([
                'success' => true,
                'brand_slug' => $brandSlug,
                'folder' => $folder,
                'items' => [],
                'message' => 'folder_empty_or_missing',
            ], JSON_UNESCAPED_UNICODE);
            exit;
        }
        $items = prd_img_collect_images($baseFs . $folder . '/', $folder . '/', $baseUrl, $allowedExt);
        echo json_encode([
            'success' => true,
            'brand_slug' => $brandSlug,
            'folder' => $folder,
            'items' => $items,
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $folders = [];
    $entries = @scandir($baseFs) ?: [];

    // Root legacy files folder, only if old images exist directly under uploads/products.
    $rootCount = prd_img_count_images($baseFs, $allowedExt);
    if ($rootCount > 0) {
        $folders[] = [
            'slug' => '__root__',
            'name' => 'صور قديمة بدون فولدر',
            'count' => $rootCount,
            'is_selected_brand' => false,
            'mtime' => @filemtime($baseFs) ?: 0,
        ];
    }

    foreach ($entries as $entry) {
        if ($entry === '.' || $entry === '..') continue;
        $dir = $baseFs . $entry;
        if (!is_dir($dir)) continue;
        $safe = prd_img_safe_folder($entry);
        if ($safe === '') continue;
        $count = prd_img_count_images($dir, $allowedExt);
        $folders[] = [
            'slug' => $safe,
            'name' => $entry,
            'count' => $count,
            'is_selected_brand' => ($safe === $brandSlug),
            'mtime' => @filemtime($dir) ?: 0,
        ];
    }

    usort($folders, function($a, $b) {
        if (($a['is_selected_brand'] ?? false) !== ($b['is_selected_brand'] ?? false)) {
            return ($b['is_selected_brand'] ?? false) <=> ($a['is_selected_brand'] ?? false);
        }
        if (($a['count'] ?? 0) !== ($b['count'] ?? 0)) {
            return ($b['count'] ?? 0) <=> ($a['count'] ?? 0);
        }
        return strnatcasecmp((string)$a['name'], (string)$b['name']);
    });

    echo json_encode([
        'success' => true,
        'brand_slug' => $brandSlug,
        'folders' => $folders,
    ], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage(), 'folders' => [], 'items' => []], JSON_UNESCAPED_UNICODE);
}
