<?php
header("Content-Type: application/json");
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Ensure your security firewall checks are retained here if needed
require_once '../config/database.php';
$db = getDB();

// Base folder location for category image uploads matching your server setup
$baseUrl = "https://globinvest.online/api/uploads/categories/";

$res = $db->query("SELECT id, name_en, name_bn, image FROM categories ORDER BY id DESC");
$categories = [];

if ($res) {
    while ($row = $res->fetch_assoc()) {
        // ✅ THE FIX: If an image exists, build the complete full URL path dynamically
        $fullImageUrl = "";
        if (!empty($row['image'])) {
            $cleanImageName = str_replace('uploads/categories/', '', $row['image']);
            $fullImageUrl = $baseUrl . $cleanImageName;
        } else {
            $fullImageUrl = "https://globinvest.online/api/uploads/categories/placeholder.png";
        }

        $categories[] = [
            'id'      => $row['id'],
            'name_en' => $row['name_en'] ?? '',
            'name_bn' => $row['name_bn'] ?? '',
            'image'   => $fullImageUrl // Sends the clear fully qualified URL back to Flutter
        ];
    }
}

echo json_encode([
    'success' => true,
    'categories' => $categories
]);
exit;