<?php
require('../config.php'); // include your DB connection

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

// ✅ Check DB connection
if (!$db) {
    echo json_encode(['status' => 'error', 'message' => 'Database connection failed']);
    exit;
}

// ✅ Check for type in the request
$type = isset($_GET['type']) ? $_GET['type'] : '';

if ($type === 'category') {
    $sql = "SELECT id, category_name AS name FROM template_category ORDER BY category_name ASC";
} else {
    // default to languages if not category
    $sql = "SELECT id, name FROM languages ORDER BY name ASC";
}

$result = mysqli_query($db, $sql);

if (!$result) {
    echo json_encode(['status' => 'error', 'message' => mysqli_error($db)]);
    exit;
}

$options = [];
while ($row = mysqli_fetch_assoc($result)) {
    $options[] = [
        'id' => $row['id'],
        'name' => $row['name']
    ];
}

// ✅ Response key based on type
$responseKey = ($type === 'category') ? 'categories' : 'languages';

echo json_encode([
    'status' => 'success',
    $responseKey => $options
]);

mysqli_close($db);
?>
