37035-vm/api/products/index.php
2025-12-18 10:12:51 +00:00

58 lines
1.8 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../includes/Database.php';
require_once __DIR__ . '/../../db/config.php';
try {
$db = Database::getInstance();
$pdoconn = $db->getConnection();
// Fetch all products with their translations
$stmt = $pdoconn->prepare("
SELECT
p.id,
p.sku,
p.price,
p.stock,
p.created_at,
p.updated_at,
pt.language_code,
l.name as language_name,
pt.name,
pt.description
FROM products p
JOIN product_translations pt ON p.id = pt.product_id
JOIN languages l ON pt.language_code = l.code
ORDER BY p.id, l.id
");
$stmt->execute();
$productsData = $stmt->fetchAll(PDO::FETCH_ASSOC);
$products = [];
foreach ($productsData as $row) {
$productId = $row['id'];
if (!isset($products[$productId])) {
$products[$productId] = [
'id' => (int)$productId,
'sku' => $row['sku'],
'price' => (float)$row['price'],
'stock' => (int)$row['stock'],
'created_at' => $row['created_at'],
'updated_at' => $row['updated_at'],
'translations' => []
];
}
$products[$productId]['translations'][] = [
'language_code' => $row['language_code'],
'language_name' => $row['language_name'],
'name' => $row['name'],
'description' => $row['description']
];
}
echo json_encode(['success' => true, 'data' => array_values($products)]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'error' => 'An internal server error occurred.']);
}