<?php
require_once '../includes/auth.php';
require_once '../db.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

$sql = "
    SELECT si.*, c.name AS customer_name
    FROM sales_invoices si
    JOIN clients c ON c.id = si.client_id
    ORDER BY si.id DESC
";
$result = $conn->query($sql);
?>

<div class="content">
    <h2>Sales Invoices</h2>

    <a href="create.php" class="btn">+ Create Sales Invoice</a>

    <table class="list-table">
        <tr>
            <th>Invoice No</th>
            <th>Date</th>
            <th>Customer</th>
            <th>Gross</th>
            <th>Overall Discount</th>
            <th>GST</th>
            <th>Net Total</th>
            <th>Received</th>
            <th>Balance</th>
            <th>Status</th>
            <th>Action</th>
        </tr>

        <?php if ($result->num_rows > 0): ?>
            <?php while ($row = $result->fetch_assoc()): ?>
                <tr>
                    <td><?= htmlspecialchars($row['invoice_no']) ?></td>
                    <td><?= htmlspecialchars($row['invoice_date']) ?></td>
                    <td><?= htmlspecialchars($row['customer_name']) ?></td>

                    <td>₹ <?= number_format($row['gross_total'], 2) ?></td>

                    <td>
                        <?php
                        if ($row['overall_discount_type'] === 'percent') {
                            echo $row['overall_discount_value'] . '%';
                        } elseif ($row['overall_discount_type'] === 'amount') {
                            echo '₹ ' . number_format($row['overall_discount_value'], 2);
                        } else {
                            echo '-';
                        }
                        ?>
                    </td>

                    <td>₹ <?= number_format($row['total_gst'], 2) ?></td>
                    <td><b>₹ <?= number_format($row['net_total'], 2) ?></b></td>
                    <td>₹ <?= number_format($row['received_amount'], 2) ?></td>
                    <td>₹ <?= number_format($row['balance_amount'], 2) ?></td>
                    <td><?= ucfirst($row['status']) ?></td>

                    <td>
						<?php if ($row['status'] == 'draft') {
							echo '<a href="edit.php?id='.$row['id'].'" title="Edit">✏️</a> ';
							echo '<a href="javascript:void(0)" onclick="openThermalModal('.$row['id'].')" title="Thermal Print">🧾</a>';
							echo '<a href="delete.php?id='.$row['id'].'" onclick="return confirm(\'Delete this draft invoice?\')" 
									 title="Delete">🗑</a> ';
						} else {
							echo '<a href="javascript:void(0)" onclick="openThermalModal('.$row['id'].')" title="Thermal Print">🧾</a> ';
							echo '<a href="javascript:void(0)" onclick="openReturnPrint('.$row['id'].')" title="Sales Return">🔁</a>';
						} ?>
                    </td>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="11">No Sales Invoices Found.</td></tr>
        <?php endif; ?>
    </table>
</div>

<!-- Thermal Print Modal -->
<div id="thermalModal" class="modal-overlay">
    <div class="modal-box">
        <div class="modal-header">
            Thermal Print
            <span class="modal-close" onclick="closeThermalModal()">×</span>
        </div>

        <div class="modal-toggle">
            <label>
                <input type="radio" name="thermalType" value="invoice" checked>
                Invoice Copy
            </label>
            <label>
                <input type="radio" name="thermalType" value="transport">
                Transport Copy
            </label>
        </div>

        <div class="modal-body" id="thermalPreview">
            Loading...
        </div>

        <div class="modal-footer">
            <button onclick="printThermalPopup()">🖨 Print</button>
            <button onclick="closeThermalModal()">Close</button>
        </div>
    </div>
</div>


<?php require_once '../includes/footer.php'; ?>


<script>
let currentInvoiceId = 0;

function openThermalModal(invoiceId) {
    currentInvoiceId = invoiceId;
    document.getElementById('thermalModal').style.display = 'flex';
    loadThermalLayout('invoice');
}

function closeThermalModal() {
    document.getElementById('thermalModal').style.display = 'none';
}

function loadThermalLayout(type) {
    fetch(`layout_loader.php?id=${currentInvoiceId}&paper=thermal&type=${type}`)
        .then(r => r.text())
        .then(html => {
            document.getElementById('thermalPreview').innerHTML = html;
            if (typeof renderBarcodeAndQR === "function") {
                renderBarcodeAndQR();
            }
        });
}




function openReturnPrint(invoiceId) {
    fetch(`../sales_return/create.php?invoice_id=${invoiceId}`)
        .then(() => {
            window.location.href = `../sales_return/create.php?invoice_id=${invoiceId}`;
        });
}

document.querySelectorAll('input[name="thermalType"]').forEach(radio => {
    radio.addEventListener('change', function() {
        loadThermalLayout(this.value);
    });
});

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