<?php

require_once __DIR__ . "/../db.php";
require_once __DIR__ . "/../session.php";

// Require authentication
requireAuth();

// Get current business
$current_business = getCurrentBusiness();
if (!$current_business) {
    header('Location: ' . BASE_URL . '/public/login.php');
    exit;
}

// Log activity
logActivity('receipt_view', 'Viewed receipt');

$order    = one("SELECT * FROM orders WHERE id=? AND business_id = ?", [$_GET['id'], $current_business['business_id']]);
$settings = one("SELECT * FROM settings WHERE id=?", [$current_business['business_id']]);
if (!$settings) {
    $settings = one("SELECT * FROM settings WHERE id=1");
}
$ois      = all_rows("SELECT * FROM order_items WHERE order_id=? ORDER BY id", [$_GET['id']]);

$subtotal = 0.0;
$tax      = 0.0;

// ✅ Calculate GST per line item
foreach ($ois as $oi) {
    $line_total = $oi['price'] * $oi['qty'];
    $subtotal  += $line_total;

    if ($oi['price'] <= 1000) {
        $gst_rate = 5.0;
    } else {
        $gst_rate = 12.0;
    }

    $tax += round($line_total * ($gst_rate / 100.0), 2);
}

$discount = (float)$order['discount'];
$taxable  = max(0.0, $subtotal - $discount);

// ✅ GST toggle
$gst_enabled = isset($order['gst_enabled']) ? (int)$order['gst_enabled'] : 1;
$tax_after_discount = 0.0;

if ($gst_enabled) {
    if ($discount > 0 && $subtotal > 0) {
        // proportionally reduce GST if discount applied
        $discount_ratio = $taxable / $subtotal;
        $tax_after_discount = round($tax * $discount_ratio, 2);
    } else {
        $tax_after_discount = $tax;
    }
}

$total = round($taxable + $tax_after_discount, 2);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Receipt #<?= e($order['id']) ?></title>
<style>
    body {
        font-family: 'Courier New', monospace;
        max-width: 280px;   /* thermal receipt width */
        margin: auto;
        font-size: 14px;
        background: rgba(255, 255, 255, 0.88);
        border-radius: 16px;
        padding: 1rem;
        box-shadow: 0 10px 30px rgba(0, 0, 0, .15);
        backdrop-filter: blur(2px);
    }
    h3 {
        text-align: center;
        margin: 5px 0;
        font-size: 18px;
    }
    .center { text-align: center; }
    hr { border: 1px dashed #000; margin: 6px 0; }
    table { width: 100%; border-collapse: collapse; font-size: 13px; }
    th, td { padding: 2px 0; }
    th { text-align: left; border-bottom: 1px dashed #000; }
    td:last-child, th:last-child { text-align: right; }
    .total { font-weight: bold; border-top: 1px dashed #000; padding-top: 5px; }
    .footer { text-align: center; margin-top: 8px; font-size: 13px; }
    .btn{
        display: flex; margin: 10px auto; padding: 5px 12px;
    }
</style>
</head>
<body>

<h3><?= e($settings['business_name']) ?></h3>
<div class="center">
    <?= e($settings['address']) ?><br>
    Ph: <?= e($settings['phone']) ?><br>
</div>
<hr>

<div>
Receipt: #<?= e($order['id']) ?> | <?= date("Y-m-d H:i", strtotime($order['created_at'])) ?>
</div>
<hr>

<!-- Item list -->
<table>
  <tr>
    <th>Item</th>
    <th>Qty</th>
    <th>Total</th>
  </tr>
  <?php foreach($ois as $oi): ?>
  <tr>
    <td><?= e($oi['item_name']) ?></td>
    <td><?= e($oi['qty']) ?></td>
    <td><?= e(number_format($oi['price'] * $oi['qty'],2)) ?></td>
  </tr>
  <?php endforeach; ?>
</table>
<hr>

<!-- Totals -->
<table>
  <tr><td>Subtotal</td><td>₹ <?= e(number_format($subtotal,2)) ?></td></tr>
  <tr><td>Discount</td><td>-₹ <?= e(number_format($discount,2)) ?></td></tr>
  <?php if ($gst_enabled): ?>
    <tr><td>GST</td><td>₹ <?= e(number_format($tax_after_discount,2)) ?></td></tr>
  <?php endif; ?>
  <tr class="total"><td>Total</td><td>₹ <?= e(number_format($total,2)) ?></td></tr>
</table>
<div class="footer">
    Paid via <strong><?= strtoupper($order['payment_method'] ?? 'CASH') ?></strong><br>
    -----------------------------<br>
    ⭐ Thanks! Visit Again ⭐
</div>

<!-- ✅ Back and Print buttons -->
 <div class="btn">
     <button onclick="window.location.href='orders.php'">Back</button>
     <button onclick="if(window.Android){Android.performPrint();}else{window.print();}">
    Print</button>
    </div>

</body>
</html>
