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

// Ensure user is logged in
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 transaction details
$sale_stmt = $conn->prepare("SELECT st.*, u.first_name, u.last_name, s.store_name, s.store_address, s.store_contact 
    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>
    <style>
        body {
            font-family: 'Courier New', Courier, monospace;
            background: #fff;
            color: #000;
            margin: 0;
            padding: 20px;
        }
        .receipt {
            max-width: 320px;
            margin: 0 auto;
            border: 1px solid #333;
            padding: 20px 25px;
            box-sizing: border-box;
            box-shadow: 0 0 8px rgba(0,0,0,0.15);
        }
        h2, h4 {
            text-align: center;
            margin: 6px 0;
            font-weight: bold;
            letter-spacing: 1.5px;
        }
        .store-info {
            text-align: center;
            font-size: 13px;
            margin-bottom: 15px;
            line-height: 1.3;
            white-space: pre-wrap;
        }
        .line {
            border-top: 1px dashed #666;
            margin: 15px 0;
        }
        table {
            width: 100%;
            font-size: 13px;
            border-collapse: collapse;
        }
        th, td {
            padding: 6px 4px;
        }
        th {
            font-weight: bold;
            border-bottom: 1px solid #666;
        }
        td {
            vertical-align: top;
        }
        tbody tr:hover {
            background: transparent;
        }
        td:nth-child(2), td:nth-child(3) {
            text-align: right;
            white-space: nowrap;
        }
        .totals td {
            font-weight: bold;
            border-top: 2px solid #333;
            padding-top: 10px;
            font-size: 14px;
        }
        .footer {
            text-align: center;
            margin-top: 18px;
            font-size: 12px;
            font-style: italic;
            color: #555;
            letter-spacing: 0.5px;
        }
        @media print {
            body {
                margin: 0;
                padding: 10px;
            }
            .receipt {
                border: none;
                box-shadow: none;
                max-width: 320px;
                margin: 0 auto;
                padding: 0;
            }
        }
    </style>
</head>
<body onload="window.print();">

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

    <div class="line"></div>

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

    <div class="line"></div>

    <table aria-label="Receipt Items">
        <thead>
            <tr>
                <th style="width:55%;">Item</th>
                <th style="width:15%;">Qty</th>
                <th style="width:30%;">Total</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($sale_items as $item): 
                $item_total = $item['total_price'];
            ?>
            <tr>
                <td><?= htmlspecialchars($item['product_name']) ?></td>
                <td><?= (int)$item['quantity'] ?></td>
                <td>MWK <?= number_format($item_total, 2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <div class="line"></div>

    <table class="totals" aria-label="Receipt Totals">
        <tr>
            <td>Subtotal:</td>
            <td>MWK <?= number_format($sale['total_amount'] - $sale['vat_total'] + $sale['discount_total'], 2) ?></td>
        </tr>
        <tr>
            <td>Discount:</td>
            <td>MWK <?= number_format($sale['discount_total'], 2) ?></td>
        </tr>
        <tr>
            <td>VAT:</td>
            <td>MWK <?= number_format($sale['vat_total'], 2) ?></td>
        </tr>
        <tr>
            <td>Total:</td>
            <td>MWK <?= number_format($sale['total_amount'], 2) ?></td>
        </tr>
        <tr>
            <td>Paid:</td>
            <td>MWK <?= number_format($sale['amount_paid'], 2) ?></td>
        </tr>
        <tr>
            <td>Change:</td>
            <td>MWK <?= number_format($sale['amount_paid'] - $sale['total_amount'], 2) ?></td>
        </tr>
        <tr>
            <td>Payment:</td>
            <td><?= htmlspecialchars($sale['payment_method']) ?></td>
        </tr>
    </table>

    <div class="line"></div>

    <div class="footer">
        Thank you for your business!<br>
        <?= date('Y-m-d H:i') ?>
    </div>
</div>

</body>
</html>
