<?php
session_start();
include('../../includes/config.php');

// Only allow logged-in users (cashiers, managers, admins)
if (!isset($_SESSION['user_id'])) {
    header('Location: ../../index.php');
    exit();
}

if (!isset($_GET['sale_id'])) {
    die("Missing sale ID.");
}

$sale_id = intval($_GET['sale_id']);

// Fetch sale transaction
$sale_stmt = $conn->prepare("SELECT st.*, u.first_name, u.last_name, s.store_name, s.store_address 
    FROM sales_transactions st
    LEFT JOIN users u ON st.sold_by = u.id
    LEFT JOIN stores s ON st.store_id = s.id
    WHERE st.id = ?");
$sale_stmt->bind_param("i", $sale_id);
$sale_stmt->execute();
$sale = $sale_stmt->get_result()->fetch_assoc();
$sale_stmt->close();

if (!$sale) die("Sale not found.");

// Fetch sale items
$items_stmt = $conn->prepare("SELECT si.*, p.product_name 
    FROM sales_items si
    LEFT JOIN products p ON si.product_id = p.id
    WHERE si.transaction_id = ?");
$items_stmt->bind_param("i", $sale_id);
$items_stmt->execute();
$sale_items = $items_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$items_stmt->close();

?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Receipt #<?= htmlspecialchars($sale['receipt_number']) ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
    body {
        font-family: 'Courier New', Courier, monospace;
        max-width: 400px;
        margin: 20px auto;
        padding: 15px;
        background: white;
        color: black;
        border: 1px solid #ccc;
        box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    h2, h3 {
        text-align: center;
        margin: 5px 0;
    }
    .store-info, .sale-info {
        text-align: center;
        margin-bottom: 10px;
    }
    table {
        width: 100%;
        border-collapse: collapse;
        font-size: 14px;
        margin-top: 10px;
        margin-bottom: 10px;
    }
    th, td {
        padding: 6px 4px;
        border-bottom: 1px dashed #aaa;
    }
    th {
        text-align: left;
    }
    .totals td {
        border-top: 1px solid #000;
    }
    .label {
        text-align: left;
        font-weight: bold;
    }
    .value {
        text-align: right;
    }
    .print-button-container {
        text-align: center;
        margin-top: 15px;
    }
    button {
        background-color: #ffa500;
        border: none;
        padding: 10px 20px;
        font-weight: bold;
        font-size: 16px;
        border-radius: 8px;
        cursor: pointer;
        color: black;
    }
    button:hover {
        background-color: #cc7a00;
    }
</style>
</head>
<body>

<div class="store-info">
    <h2><?= htmlspecialchars($sale['store_name']) ?></h2>
    <div><?= nl2br(htmlspecialchars($sale['store_address'])) ?></div>
</div>

<div class="sale-info">
    <div><strong>Receipt #: </strong><?= htmlspecialchars($sale['receipt_number']) ?></div>
    <div><strong>Date: </strong><?= date('Y-m-d H:i', strtotime($sale['created_at'])) ?></div>
    <div><strong>Cashier: </strong><?= htmlspecialchars($sale['first_name'] . ' ' . $sale['last_name']) ?></div>
    <?php if (!empty($sale['customer_name'])): ?>
    <div><strong>Customer: </strong><?= htmlspecialchars($sale['customer_name']) ?></div>
    <?php endif; ?>
</div>

<table aria-label="Receipt Items">
    <thead>
        <tr>
            <th>Product</th>
            <th>Qty</th>
            <th>Unit Price</th>
            <th>Discount</th>
            <th>VAT</th>
            <th>Total</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($sale_items as $item): 
            $unit_price = (float)$item['unit_price'];
            $quantity = (int)$item['quantity'];
            $discount = (float)$item['discount'];
            $vat_rate = (float)$item['vat_rate'];
            $line_total = $unit_price * $quantity - $discount;
            $line_vat = (($unit_price * $quantity - $discount) * $vat_rate) / 100;
        ?>
        <tr>
            <td><?= htmlspecialchars($item['product_name']) ?></td>
            <td><?= $quantity ?></td>
            <td><?= number_format($unit_price, 2) ?></td>
            <td><?= number_format($discount, 2) ?></td>
            <td><?= number_format($line_vat, 2) ?></td>
            <td><?= number_format($line_total + $line_vat, 2) ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<table class="totals" aria-label="Receipt Totals">
    <tbody>
        <tr>
            <td class="label">Subtotal:</td>
            <td class="value"><?= number_format((float)$sale['total_amount'] - (float)$sale['vat_total'] + (float)$sale['discount_total'], 2) ?></td>
        </tr>
        <tr>
            <td class="label">Discount Total:</td>
            <td class="value"><?= number_format((float)$sale['discount_total'], 2) ?></td>
        </tr>
        <tr>
            <td class="label">VAT Total:</td>
            <td class="value"><?= number_format((float)$sale['vat_total'], 2) ?></td>
        </tr>
        <tr>
            <td class="label">Grand Total:</td>
            <td class="value"><?= number_format((float)$sale['total_amount'], 2) ?></td>
        </tr>
        <tr>
            <td class="label">Amount Paid:</td>
            <td class="value"><?= number_format((float)$sale['amount_paid'], 2) ?></td>
        </tr>
        <tr>
            <td class="label">Change Due:</td>
            <td class="value"><?= number_format((float)$sale['amount_paid'] - (float)$sale['total_amount'], 2) ?></td>
        </tr>
    </tbody>
</table>

<div class="print-button-container">
    <button onclick="window.print()">Print Receipt</button>
</div>

</body>
</html>
