<?php
include 'auth_check.php';

$bill_number = $_GET['bill_number'] ?? '';
if ($bill_number === '') {
    exit('Invalid bill number.');
}

$itemsStmt = $conn->prepare("SELECT * FROM billing_data WHERE bill_number = ?");
$itemsStmt->bind_param("s", $bill_number);
$itemsStmt->execute();
$items = $itemsStmt->get_result();

$summaryStmt = $conn->prepare("SELECT * FROM selling_data WHERE bill_number = ? LIMIT 1");
$summaryStmt->bind_param("s", $bill_number);
$summaryStmt->execute();
$summary = $summaryStmt->get_result()->fetch_assoc();

function formatQtyForBill($qty) {
    if ($qty === null || $qty === '') {
        return '';
    }

    $qtyString = (string)$qty;

    if (strpos($qtyString, '.') !== false) {
        $qtyString = rtrim(rtrim($qtyString, '0'), '.');
    }

    return $qtyString;
}

function getBaseUnitFromStock($conn, $productName) {
    $stmt = $conn->prepare("SELECT unit FROM stock WHERE product_name = ? LIMIT 1");
    $stmt->bind_param("s", $productName);
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res && $res->num_rows > 0) {
        $row = $res->fetch_assoc();
        return trim((string)$row['unit']);
    }

    return '';
}

function getPrintedQtyText($conn, $row) {
    $qtyText = formatQtyForBill($row['qty']);
    $sellingMode = trim((string)($row['selling_mode'] ?? ''));
    $storedUnit = trim((string)($row['unit'] ?? ''));

    if ($sellingMode === 'mode_1') {
        return $qtyText;
    }

    if ($sellingMode === 'mode_2') {
        $baseUnit = getBaseUnitFromStock($conn, $row['product_name']);
        return $qtyText . $baseUnit;
    }

    return $qtyText . $storedUnit;
}

$grossTotal = (float)($summary['total_amount'] ?? 0);
$totalDiscount = (float)($summary['total_discount'] ?? 0);
$netTotal = $grossTotal - $totalDiscount;
if ($netTotal < 0) {
    $netTotal = 0;
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Print Bill</title>
    <style>
        body{
            font-family: Arial, "Noto Sans Sinhala", "Iskoola Pota", "Malithi Web", "Segoe UI", sans-serif;
            padding: 0;
            margin: 0;
            background: #fff;
            color: #111;
            font-size: 11.5px;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        .bill{
            width: 290px;
            max-width: 290px;
            margin: 0 auto;
            padding: 0 4px 6px 4px;
        }

        .center{text-align:center;}

        .logo-box{
            width: 100px;
            height: 100px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 1px auto;
        }

        .logo-box img{
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            display: block;
        }

        .shop-name{
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 1px;
            line-height: 1.1;
        }

        .shop-meta{
            font-size: 10.5px;
            line-height: 1.2;
            margin-bottom: 4px;
        }

        .bill-meta{
            font-size: 10.5px;
            line-height: 1.45;
            border-top: 1px solid #111;
            border-bottom: 1px solid #111;
            padding: 5px 0;
            margin-bottom: 5px;
        }

        .bill-meta strong{
            font-weight: 700;
        }

        .bill-table{
            width: 100%;
            border-collapse: collapse;
            table-layout: fixed;
            margin-top: 1px;
        }

        .bill-table thead th{
            font-size: 9.5px;
            font-weight: bold;
            padding: 4px 1px 5px 1px;
            border-bottom: 1px solid #111;
            text-align: center;
            line-height: 1.1;
        }

        .bill-table thead th.item-head{
            text-align: left;
        }

        .bill-table td{
            padding: 2px 1px;
            font-size: 10.5px;
            vertical-align: top;
        }

        .item-name-col{
            width: 30px;
            text-align: left;
        }

        .qty-col{
            width: 30px;
            text-align: center;
        }

        .price-col{
            width: 30px;
            text-align: center;
        }

        .discount-col{
            width: 30px;
            text-align: center;
        }

        .total-col{
            width: 30px;
            text-align: center;
        }

        .item-name-row td{
            padding-top: 5px;
            padding-bottom: 1px;
            border-bottom: none;
        }

        .item-name{
            width: 180px;
            font-weight: normal;
            line-height: 1.15;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: clip;
        }

        .item-value-row td{
            padding-top: 0;
            padding-bottom: 5px;
            border-bottom: 2px dashed #444;
            vertical-align: middle;
        }

        .summary{
            margin-top: 5px;
            border-top: 1px solid #111;
            padding-top: 5px;
            font-size: 11.5px;
            line-height: 1.6;
        }

        .summary-row{
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 8px;
        }

        .summary-row span:last-child,
        .summary-row strong:last-child{
            min-width: 86px;
            text-align: right;
        }

        .summary-row strong{
            font-size: 12.5px;
        }

        .footer-note{
            margin-top: 10px;
            text-align: center;
            font-size: 10.5px;
            font-weight: bold;
            line-height: 1.45;
        }

        .footer-note-sinhala{
            margin-top: 4px;
            font-family: "Noto Sans Sinhala", "Iskoola Pota", "Malithi Web", Arial, sans-serif;
        }

        @page{
            size: 3in auto;
            margin: 1mm 3mm 3mm 3mm;
        }

        @media print{
            html, body{
                padding: 0;
                margin: 0;
            }

            body{
                font-size: 16px;
            }

            .bill{
                width: 290px;
                max-width: 290px;
                margin: 0 auto;
                padding: 0 3px 4px 3px;
            }

            .logo-box{
                margin-top: 0;
                margin-bottom: 1px;
            }

            .shop-name{
                font-size: 25px;
            }

            .shop-meta{
                font-size: 13px;
            }

            .bill-meta{
                font-size: 12px;
            }

            .bill-table thead th{
                font-size: 12px;
            }

            .bill-table td{
                font-size: 14px;
            }

            .summary{
                font-size: 15px;
            }

            .summary-row strong{
                font-size: 16px;
            }

            .footer-note{
                font-size: 14px;
            }
        }
    </style>
</head>
<body onload="window.print()">
<div class="bill">
    <div class="center">
        <div class="logo-box">
            <img src="../agrosys/logo/logo2.png" alt="Logo">
        </div>
        <div class="shop-name">Krushi Sewa Piyasa</div>
        <div class="shop-meta">Address : Kandy Road, Nelundeniya<br>Mobile: 071-439-4580</div>
    </div>

    <div class="bill-meta">
        <div><strong>Bill No:</strong> <?php echo htmlspecialchars($bill_number); ?></div>
        <div><strong>Date:</strong> <?php echo htmlspecialchars($summary['entered_date']); ?> <?php echo htmlspecialchars($summary['entered_time']); ?></div>
        <div><strong>Casher :</strong> <?php echo htmlspecialchars($_SESSION['name']); ?></div>
    </div>

    <table class="bill-table">
        <thead>
            <tr>
                <th class="item-head item-name-col">Item</th>
                <th class="qty-col">Qty</th>
                <th class="price-col">U:Price</th>
                <th class="discount-col">Discount</th>
                <th class="total-col">Amount</th>
            </tr>
        </thead>
        <tbody>
            <?php while($row = $items->fetch_assoc()) {
                $rate = (float)$row['selling_price'];
                $discount = (float)$row['discount'];
                $lineTotal = (float)$row['line_total'];
                $displayQty = getPrintedQtyText($conn, $row);
            ?>
            <tr class="item-name-row">
                <td class="item-name-col">
                    <div class="item-name"><?php echo htmlspecialchars($row['product_name']); ?></div>
                </td>
                <td class="qty-col"></td>
                <td class="price-col"></td>
                <td class="discount-col"></td>
                <td class="total-col"></td>
            </tr>
            <tr class="item-value-row">
                <td class="item-name-col"></td>
                <td class="qty-col"><?php echo htmlspecialchars($displayQty); ?></td>
                <td class="price-col"><?php echo number_format($rate, 2); ?></td>
                <td class="discount-col"><?php echo number_format($discount, 2); ?></td>
                <td class="total-col"><?php echo number_format($lineTotal, 2); ?></td>
            </tr>
            <?php } ?>
        </tbody>
    </table>

    <div class="summary">
        <div class="summary-row"><strong>Total :</strong><strong><?php echo number_format($grossTotal, 2); ?></strong></div>
        <div class="summary-row"><span>Total Discount :</span><span><?php echo number_format($totalDiscount, 2); ?></span></div>
        <div class="summary-row"><span>Net Total :</span><span><?php echo number_format($netTotal, 2); ?></span></div>
        <div class="summary-row"><span>Received :</span><span><?php echo number_format($summary['received_amount'],2); ?></span></div>
        <div class="summary-row"><strong>Balance :</strong><strong><?php echo number_format($summary['balance_amount'],2); ?></strong></div>
    </div>

    <div class="footer-note">
        Thankyou | Visit Us Again.<br>
        <div class="footer-note-sinhala">ඔබ මිලදී ගත් භාණ්ඩ, වෙනස් කිරීමට අවශ්‍ය නම් හෝ කිසියම් ගැටළුවක් ඇත්නම්, කරුණාකර බිල්පත සමඟ භාණ්ඩ රැගෙන එන්න.</div>
    </div>
</div>
</body>
</html>