<?php
date_default_timezone_set('Asia/Colombo');
include '../config.php';
header('Content-Type: application/json');

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (!$id) {
    echo json_encode(['success' => false, 'message' => 'No receipt ID provided']);
    exit;
}

$stmt = $conn->prepare("SELECT s.id, s.sale_date, c.name as customer_name FROM sales s LEFT JOIN customers c ON s.customer_id = c.id WHERE s.id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$sale = $stmt->get_result()->fetch_assoc();
if (!$sale) {
    echo json_encode(['success' => false, 'message' => 'Sale not found']);
    exit;
}

$stmt = $conn->prepare("SELECT si.id, si.sale_id, si.product_id, si.quantity, si.unit_price, si.total_price, si.refunded, p.name as product_name FROM sale_items si JOIN products p ON si.product_id = p.id WHERE si.sale_id = ?");
$stmt->bind_param('i', $id);
$stmt->execute();
$items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

$sale['items'] = $items;

echo json_encode(['success' => true, 'data' => $sale]);
