<?php
session_start();
if (!isset($_SESSION['role_id']) || $_SESSION['role_id'] != 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

include('../../includes/config.php');

$transaction_id = $_GET['transaction_id'] ?? 0;
if (!is_numeric($transaction_id) || $transaction_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid transaction ID']);
    exit();
}

// Query to get individual sale items with product info
$sql = "SELECT si.*, p.product_name 
        FROM sales_items si 
        LEFT JOIN products p ON si.product_id = p.id
        WHERE si.transaction_id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $transaction_id);
$stmt->execute();
$result = $stmt->get_result();

$items = [];
while ($row = $result->fetch_assoc()) {
    $items[] = [
        'product_name' => $row['product_name'],
        'quantity' => $row['quantity'],
        'unit_price' => $row['unit_price'],
        'discount' => $row['discount'],
        'vat' => $row['vat'],
        'total' => $row['total']
    ];
}
$stmt->close();

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