<?php
session_start();

if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit();
}

include "db_connect.php";

if (empty($_GET['id'])) {
    echo "No receipt found.";
    exit;
}

$receiptId = $_GET['id'];
$cashier   = $_SESSION['username'] ?? 'Unknown';

// TAX SETTINGS
// selling_price and total_sale are assumed TAX-INCLUSIVE.
// We only split out the tax portion for display.
$TAX_RATE = 0.16; // 16% VAT (change if needed)

// Fetch sales linked to this receipt
$stmt = $conn->prepare("
    SELECT s.*, p.name 
    FROM sales s 
    JOIN products p ON s.product_id = p.id 
    WHERE s.receipt_id = ?
");
$stmt->bind_param("s", $receiptId);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo "No sales found for this receipt.";
    exit;
}

$sales             = [];
$totalAmount       = 0; // Gross total (incl. VAT)
$subtotalExclTax   = 0; // Net total (excl. VAT)
$totalTax          = 0; // Total VAT

while ($row = $result->fetch_assoc()) {
    $sales[] = $row;

    // Line totals (already tax-inclusive)
    $lineGross = (float)$row['total_sale'];
    $totalAmount += $lineGross;

    // Split into net + tax
    $lineNet  = $lineGross / (1 + $TAX_RATE);     // exclusive of VAT
    $lineTax  = $lineGross - $lineNet;

    $subtotalExclTax += $lineNet;
    $totalTax        += $lineTax;
}

$stmt->close();

// Use the first sale's datetime as sale time (all rows share same receipt_id)
$saleDateTime = isset($sales[0]['sale_datetime'])
    ? date("Y-m-d H:i", strtotime($sales[0]['sale_datetime']))
    : date("Y-m-d H:i");

$page_title = "Sales Receipt";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include "cashier_head.php"; ?>
    <style>
        /* Main layout */
        .cashier-main {
            display: flex;
            justify-content: center;
            align-items: flex-start;
            padding: 32px 24px;
        }

        .receipt-wrapper {
            width: 100%;
            max-width: 520px;
            display: flex;
            justify-content: center;
        }

        .receipt-card {
            width: 100%;
            background: #ffffff;
            border-radius: 18px;
            padding: 24px 28px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.5);
            color: #111827;
            font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        }

        .receipt-header {
            text-align: center;
            margin-bottom: 10px;
        }

        .receipt-header .brand {
            font-size: 22px;
            font-weight: 700;
            letter-spacing: 2px;
            color: #00FFE5; /* turquoise accent */
            text-transform: uppercase;
        }

        .receipt-header .shop-meta {
            font-size: 12px;
            color: #6b7280;
        }

        .receipt-divider {
            border-top: 1px dashed #d1d5db;
            margin: 12px 0 16px;
        }

        .receipt-title {
            text-align: center;
            font-size: 14px;
            font-weight: 600;
            letter-spacing: 0.16em;
            text-transform: uppercase;
            margin-bottom: 6px;
        }

        .receipt-meta {
            text-align: center;
            font-size: 12px;
            color: #6b7280;
            line-height: 1.5;
            margin-bottom: 10px;
        }

        .receipt-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
            margin-top: 4px;
        }

        .receipt-table th,
        .receipt-table td {
            padding: 6px 4px;
            text-align: right;
        }

        .receipt-table th:first-child,
        .receipt-table td:first-child {
            text-align: left;
        }

        .receipt-table thead th {
            border-bottom: 1px solid #e5e7eb;
            color: #374151;
            font-weight: 600;
        }

        .receipt-table tbody tr td {
            border-bottom: 1px dotted #e5e7eb;
        }

        .totals-row td {
            border-top: 1px solid #e5e7eb;
            padding-top: 6px;
        }

        .totals-row.label {
            font-weight: 500;
        }

        .totals-row.value {
            font-weight: 700;
        }

        .receipt-footer-text {
            text-align: center;
            margin-top: 14px;
            font-size: 12px;
            color: #4b5563;
        }

        .receipt-footer-text small {
            display: block;
            margin-top: 4px;
            color: #9ca3af;
        }

        .receipt-actions {
            margin-top: 18px;
            display: flex;
            justify-content: center;
            gap: 10px;
        }

        .receipt-btn {
            padding: 8px 18px;
            border-radius: 999px;
            border: none;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
        }

        .receipt-btn-primary {
            background: #00FFE5;
            color: #022c3a;
        }

        .receipt-btn-secondary {
            background: #f3f4f6;
            color: #111827;
        }

        .receipt-btn-primary:hover {
            filter: brightness(1.05);
        }

        .receipt-btn-secondary:hover {
            background: #e5e7eb;
        }

        /* PRINT VIEW: hide chrome and sidebar, keep only receipt content */
        @media print {
            body {
                background: #ffffff !important;
            }
            .cashier-sidebar,
            .cashier-topbar,
            footer {
                display: none !important;
            }
            .cashier-main {
                margin: 0;
                padding: 0;
            }
            .receipt-card {
                box-shadow: none;
                border-radius: 0;
            }
            .receipt-actions {
                display: none;
            }
        }
    </style>
</head>
<body>

<div class="cashier-shell">
    <?php include "cashier_sidebar.php"; ?>

    <main class="cashier-main">
        <div class="receipt-wrapper">
            <section class="receipt-card">

                <header class="receipt-header">
                    <div class="brand">WEBNEXER</div>
                    <div class="shop-meta">Location: Malava · Phone: 0799062742</div>
                </header>

                <div class="receipt-divider"></div>

                <div class="receipt-title">Sales receipt</div>
                <div class="receipt-meta">
                    Cashier: <?= htmlspecialchars($cashier) ?><br>
                    Receipt ID: <?= htmlspecialchars($receiptId) ?><br>
                    Date: <?= htmlspecialchars($saleDateTime) ?>
                </div>

                <table class="receipt-table">
                    <thead>
                        <tr>
                            <th>Item</th>
                            <th>Qty</th>
                            <th>Price (Incl. VAT)</th>
                            <th>Total (Incl. VAT)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($sales as $sale): ?>
                            <tr>
                                <td><?= htmlspecialchars($sale['name']) ?></td>
                                <td><?= (int)$sale['quantity'] ?></td>
                                <td><?= number_format($sale['selling_price'], 2) ?></td>
                                <td><?= number_format($sale['total_sale'], 2) ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                    <tfoot>
                        <tr class="totals-row label">
                            <td colspan="3">Subtotal (Excl. VAT)</td>
                            <td><?= number_format($subtotalExclTax, 2) ?></td>
                        </tr>
                        <tr class="totals-row label">
                            <td colspan="3">VAT (<?= (int)($TAX_RATE * 100) ?>%)</td>
                            <td><?= number_format($totalTax, 2) ?></td>
                        </tr>
                        <tr class="totals-row value">
                            <td colspan="3">Grand total (Incl. VAT)</td>
                            <td><?= number_format($totalAmount, 2) ?></td>
                        </tr>
                    </tfoot>
                </table>

                <p class="receipt-footer-text">
                    Thank you, come again!
                    <small>All prices are inclusive of VAT at <?= (int)($TAX_RATE * 100) ?>%.</small>
                </p>

                <div class="receipt-actions">
                    <button class="receipt-btn receipt-btn-primary" onclick="window.print()">
                        Print receipt
                    </button>
                    <button class="receipt-btn receipt-btn-secondary"
                            onclick="window.location.href='record_sales.php'">
                        Back to sales
                    </button>
                </div>

            </section>
        </div>
    </main>
</div>

<?php include "footer.php"; ?>

<?php
// Clear current receipt id after displaying
unset($_SESSION['receipt_id']);
?>
</body>
</html>
