<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
require __DIR__ . '/../includes/db.php';

$id = (int)($_GET['id'] ?? 0);
if (!$id) {
  echo json_encode(['error' => 'invalid id']);
  exit;
}

$stmt = $pdo->prepare("SELECT * FROM purchase_invoices WHERE id=?");
$stmt->execute([$id]);
$invoice = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$invoice) {
  echo json_encode(['error' => 'not found']);
  exit;
}

$items = $pdo->prepare("SELECT product_id, qty, price FROM purchase_items WHERE invoice_id=?");
$items->execute([$id]);
$items = $items->fetchAll(PDO::FETCH_ASSOC);

$products = $pdo->query("SELECT id,name FROM products ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

header('Content-Type: application/json; charset=utf-8');
echo json_encode(['invoice' => $invoice, 'items' => $items, 'products' => $products]);
