<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

session_start();
header('Content-Type: application/json');

// Uncomment to debug session role issues
// var_dump($_SESSION);

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

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

$sale_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($sale_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid sale ID']);
    exit;
}

// Adjust date column here if your DB uses 'created_at' instead of 'transaction_date'
$stmt = $conn->prepare("SELECT id, receipt_number, total_amount, created_at FROM sales_transactions WHERE id = ?");
$stmt->bind_param('i', $sale_id);
$stmt->execute();
$result = $stmt->get_result();
$sale = $result->fetch_assoc();

if (!$sale) {
    echo json_encode(['success' => false, 'message' => 'Sale not found']);
} else {
    // Rename created_at to transaction_date for consistent API response
    $sale['transaction_date'] = $sale['created_at'];
    unset($sale['created_at']);
    echo json_encode(['success' => true, 'sale' => $sale]);
}
