<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include_once 'Database.php';
include_once 'Items.php';

$database = new Database();
$db = $database->getConnection();

$items = new Items($db);

$items->id = (isset($_GET['id']) && $_GET['id']) ? $_GET['id'] : '0';

$result = $items->read();

if($result->num_rows > 0){ 
$itemRecords=array();
$itemRecords["items"]=array(); 
while ($item = $result->fetch_assoc()) { 
extract($item); 
$itemDetails=array(
"id" => $id,
"ruc" => $ruc,
"nombre" => $nombre,
"nombre_comercial" => $nombre_comercial,
"direccion" => $direccion, 
"created_at" => $created_at
); 
array_push($itemRecords["items"], $itemDetails);
} 
http_response_code(200); 
echo json_encode($itemRecords);
}else{ 
http_response_code(404); 
echo json_encode(
array("message" => "No item found.")
);
} 
?>

<?php
function read(){ 
if($this->id) {
$stmt = $this->conn->prepare("SELECT * FROM ".$this->itemsTable." WHERE id = ?");
$stmt->bind_param("i", $this->id); 
} else {
$stmt = $this->conn->prepare("SELECT * FROM ".$this->itemsTable); 
} 
$stmt->execute(); 
$result = $stmt->get_result(); 
return $result; 
}
?>