<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$host = "localhost";
$username = "juantufacturaya_pgweb";
$password = "Pgweb2025*";
$database = "juantufacturaya_pale";

$conn = mysqli_connect($host, $username, $password, $database);

// 👇 Forzar codificación UTF-8
mysqli_set_charset($conn, "utf8");

if (!$conn) {
    echo json_encode(["error" => "Connection failed: " . mysqli_connect_error()]);
    exit;
}

$sql = "
  SELECT
    pres.id_pres,
    pres.presentacion,
    pres.precio,
    pres.imagen AS archivo_imagen,
    prod.nombre AS nombre_producto,
    catg.descripcion AS categoria
  FROM tm_producto_pres pres
  INNER JOIN tm_producto prod
    ON pres.id_prod = prod.id_prod
  INNER JOIN tm_producto_catg catg
    ON prod.id_catg = catg.id_catg
  WHERE pres.estado = 'a'
    AND prod.estado = 'a'
    AND catg.estado = 'a'
    AND pres.delivery = 1
  ORDER BY catg.orden, prod.nombre, pres.ordenins
";

$result = mysqli_query($conn, $sql);
if (!$result) {
    echo json_encode(["error" => "Error en la consulta: " . mysqli_error($conn)]);
    mysqli_close($conn);
    exit;
}

$data = [];
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

mysqli_close($conn);
echo json_encode($data);
?>
