<?php

header('Content-Type: application/json');

$response = ['success' => false, 'categories' => [], 'message' => 'Terjadi kesalahan server awal.'];

if (!@include_once __DIR__ . '/../../config/config.php') {
    http_response_code(500); error_log("Failed to include config.php in get_categories.php");
    $response['message'] = 'Gagal memuat file konfigurasi.'; echo json_encode($response); exit;
}
if (!@include_once __DIR__ . '/../../includes/db_connect.php') {
    http_response_code(500); error_log("Failed to include db_connect.php in get_categories.php");
    $response['message'] = 'Gagal memuat file koneksi database.'; echo json_encode($response); exit;
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    error_log("PDO connection object (\$pdo) is not available or not a PDO instance in get_categories.php AFTER including db_connect.php. Check db_connect.php for errors.");
    $response['message'] = 'Koneksi database tidak berhasil diinisialisasi.';
    echo json_encode($response);
    exit;
}
$response = ['success' => false, 'categories' => [], 'message' => 'Gagal memuat kategori.'];

try {
    $stmt = $pdo->query("SELECT `id`, `name`, `icon_class` FROM `categories` WHERE `status` = 'active' ORDER BY `name` ASC");
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $response['success'] = true;
    $response['categories'] = $categories;
    unset($response['message']);

} catch (\PDOException $e) {
    error_log("AJAX Get Categories DB Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan saat mengambil data kategori.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_db'] = $e->getMessage(); }
    http_response_code(500);

} catch (\Throwable $e) {
    error_log("AJAX Get Categories General Error: " . $e->getMessage());
    $response['message'] = "Terjadi kesalahan internal server.";
    if (defined('DEBUG_MODE') && DEBUG_MODE === true) { $response['debug_php'] = $e->getMessage(); }
    http_response_code(500);
}

echo json_encode($response);
exit;
?>
