<?php
session_start();
include 'db.php';

$last_sale = null;
$last_items = [];
$fbr_enabled = false;
$branch_info = null;

$receipt_font_size = 16; // default
$result = $conn->query("SELECT value FROM settings WHERE code = 'receipt_font_size' AND is_active = 1 LIMIT 1");
if ($result && $row = $result->fetch_assoc()) {
    $receipt_font_size = intval($row['value']);
}

// Load FBR config
$fbr_result = $conn->query("SELECT is_enabled FROM fbr_config LIMIT 1");
if ($fbr_result && $fbr_row = $fbr_result->fetch_assoc()) {
    $fbr_enabled = intval($fbr_row['is_enabled']) === 1;
}

// Load branch info
$branch_result = $conn->query("SELECT * FROM branch_info LIMIT 1");
if ($branch_result && $branch_result->num_rows > 0) {
    $branch_info = $branch_result->fetch_assoc();
}

// Load sale + items
if (!empty($_GET['sale_id'])) {
    $sale_id = intval($_GET['sale_id']);
    $sale_result = $conn->query("SELECT * FROM sales WHERE id = $sale_id LIMIT 1");
    if ($sale_result && $sale_result->num_rows > 0) {
        $last_sale = $sale_result->fetch_assoc();
    }

    $items_result = $conn->query("SELECT * FROM sale_items WHERE sale_id = $sale_id");
    while ($item = $items_result->fetch_assoc()) {
        $last_items[] = $item;
    }
}

$receipt_logo_width = 100; // default
$result = $conn->query("SELECT value FROM settings WHERE code = 'receipt_logo_width' AND is_active = 1 LIMIT 1");
if ($result && $row = $result->fetch_assoc()) {
    $receipt_logo_width = intval($row['value']);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Receipt</title>
    <style>
body {
    font-family: Arial, sans-serif;
    font-size: <?= $receipt_font_size ?>px;
    margin: 0;
    padding: 0;
    background: #fff;
}

.receipt-wrapper {
    max-width: 700px;
    margin: auto;
    padding: 15px;
    border: 0.5px solid #444;
    box-sizing: border-box;
}

h6, p {
    margin: 0;
    padding: 0;
    font-size: <?= $receipt_font_size ?>px;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 10px;
    border: 0.5px solid #444;
}

td, th {
    padding: 6px;
    font-size: <?= $receipt_font_size ?>px;
    border: 0.5px solid #444;
}

.text-end {
    text-align: right;
}

.center {
    text-align: center;
}

.logo {
    margin-bottom: 5px;
}

.barcode-img {
    margin-top: 10px;
    max-width: 150px;
}

hr {
    border: 0.5px dashed #666;
    margin: 8px 0;
}


.summary-table {
    width: 100%;
    max-width: 300px;
    margin-left: auto;
    margin-top: 10px;
    border: none;
    font-size: <?= $receipt_font_size ?>px;
}

.summary-table td {
    padding: 4px 0;
    border: none;
   border-bottom: 1px solid #ccc; /* Underline each row */
}

.summary-table tr:last-child td {
    border-bottom: 2px solid #000; /* Stronger line under Total */
}

.summary-table .label {
    text-align: left;
}

.summary-table .value {
    text-align: right;
}

.summary-table .total {
    font-weight: bold;
    font-size: <?= $receipt_font_size + 1 ?>px;
    padding-top: 6px;
    border-top: 1px solid #ccc;
}


/* ✅ Print-specific layout fix */
@media print {
    @page {
        margin: 10mm 2mm 10mm 5mm; /* top, right, bottom, left */
    }

    body {
        margin: 0;
        padding: 0;
        font-size: <?= $receipt_font_size + 2 ?>px;
    }

    .receipt-wrapper {
        margin: 0;                 /* Remove auto centering */
        padding: 20px;
        width: auto;              /* Let it use full available width */
        box-sizing: border-box;
    }

    td, th, p, h6 {
        font-size: <?= $receipt_font_size + 2 ?>px;
    }

    img {
        max-width: 100%;
        height: auto;
    }
}




    </style>


</head>
<body>

<div class="receipt-wrapper">

<div class="center">
    <img src="assets/img/branch_logo.png" width="<?= $receipt_logo_width ?>" alt="Logo" class="logo"><br>

    <?php if ($branch_info): ?>
        <h6><?= htmlspecialchars($branch_info['branch_name']) ?></h6>
        <p><?= nl2br(htmlspecialchars($branch_info['branch_address'])) ?></p>

        <?php if (!empty($branch_info['branch_phone'])): ?>
            <p><strong>Phone:</strong> <?= htmlspecialchars($branch_info['branch_phone']) ?></p>
        <?php endif; ?>

        <?php if (!empty($branch_info['ntn'])): ?>
            <p><strong>NTN:</strong> <?= htmlspecialchars($branch_info['ntn']) ?></p>
        <?php endif; ?>

        <?php if (!empty($branch_info['strn'])): ?>
            <p><strong>STRN:</strong> <?= htmlspecialchars($branch_info['strn']) ?></p>
        <?php endif; ?>
    <?php endif; ?>
</div>

<hr>

<?php if (!empty($last_sale)): ?>
    <h6 class="center">Sale Invoice</h6>

    <p><strong>Name:</strong> <?= htmlspecialchars($last_sale['customer_name']) ?></p>
    <p><strong>Invoice No:</strong> <?= htmlspecialchars($last_sale['invoice_number']) ?></p>

    <?php if ($fbr_enabled && !empty($last_sale['fbr_invoice_number'])): ?>
        <p><strong>FBR Inv#:</strong> <?= htmlspecialchars($last_sale['fbr_invoice_number']) ?></p>
    <?php endif; ?>

    <p><strong>Date:</strong> <?= date('d.m.Y', strtotime($last_sale['sale_date'] ?? $last_sale['created_at'])) ?></p>

    <hr>

    <table>
        <thead>
            <tr>
                <th>#</th>
                <th>Item</th>
                <th>Qty</th>
                <th class="text-end">Total</th>
            </tr>
        </thead>
        <tbody>
        <?php
        $i = 1;
        $subtotal = 0;
        foreach ($last_items as $item):
            $line_total = $item['unit_price'] * $item['quantity'];
            $subtotal += $line_total;
        ?>
            <tr>
                <td><?= $i++ ?>.</td>
                <td><?= htmlspecialchars($item['item_name']) ?></td>
                <td><?= $item['quantity'] ?></td>
                <td class="text-end">Rs <?= number_format($line_total, 2) ?></td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>

    <hr>
<table class="summary-table">
    <tr>
        <td class="label">Subtotal</td>
        <td class="value">Rs <?= number_format($subtotal, 2) ?></td>
    </tr>
    <tr>
        <td>Discount :</td>
        <td class="text-end">
            <?php
            if (!empty($last_sale['discount_type']) && $last_sale['discount_type'] === 'percent') {
                echo number_format($last_sale['discount_value'], 2) . '%';
            } elseif (!empty($last_sale['discount_type']) && $last_sale['discount_type'] === 'fixed') {
                echo 'Rs ' . number_format($last_sale['discount_value'], 2);
            } else {
                echo 'Rs ' . number_format($last_sale['discount_amount'] ?? 0, 2);
            }
            ?>
            (Rs <?= number_format($last_sale['discount_amount'] ?? 0, 2) ?>)
        </td>
    </tr>
    <tr>
        <td class="label">Tax</td>
        <td class="value">Rs <?= number_format($last_sale['tax_amount'], 2) ?></td>
    </tr>
    <tr>
        <td class="label total">Total</td>
        <td class="value total">Rs <?= number_format($last_sale['net_amount'], 2) ?></td>
    </tr>
</table>



    <div class="center">
        <?php if ($fbr_enabled && !empty($last_sale['fbr_qr_base64'])): ?>
            <img src="data:image/png;base64,<?= $last_sale['fbr_qr_base64'] ?>" class="barcode-img" alt="FBR QR Code">
        <?php elseif (!empty($last_sale['fbr_qr_filename'])): ?>
            <img src="uploads/qr/<?= htmlspecialchars($last_sale['fbr_qr_filename']) ?>" class="barcode-img" alt="FBR QR Code">
        <?php endif; ?>

        <p>Sale #<?= $last_sale['id'] ?></p>
        <p>Thanks for your business!</p>

   <div style="margin-top: 10px; font-size: 12px; text-align: center;">
    <p><strong>Software by:</strong><br> IT Resources</p>
    <p>📞 0311-391-7777</p>
</div>


    <script>
        window.onload = function () {
            window.print();
        };
    </script>

<?php else: ?>
    <p class="center">No sale data found.</p>
<?php endif; ?>



</body>
</html>

