<?php
// file: order_detail_q.php
// Added batch number display functionality

include("../db/cn.php");
include("common/tx.php");
ob_start();

// Handle deletion request (keep this feature)
if (isset($_GET['delete_order_id'])) {
    $deleteOrderId = mysqli_real_escape_string($connection, $_GET['delete_order_id']);
    $deleteQuery = "DELETE FROM add_qot WHERE order_id = '$deleteOrderId'";
    mysqli_query($connection, $deleteQuery);

    echo "<script>
            window.location = 'order_detail_q.php?deleted=1';
          </script>";
    exit();
}

// Ensure session variables exist; if not, redirect or show limited view.
if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];

    // Fetch only quotation history (status = '')
    $saleHistoryResult = mysqli_query($connection, "SELECT * FROM add_qot WHERE status = '' ORDER BY date_time DESC");
} else {
    // If session not set, fetch nothing
    $saleHistoryResult = false;
}

// Collect rows and group by order_id
$saleHistoryData = array();
if ($saleHistoryResult) {
    while ($row = mysqli_fetch_assoc($saleHistoryResult)) {
        $saleHistoryData[] = $row;
    }
}

function groupDataByOrderId($data) {
    $groups = array();
    foreach ($data as $item) {
        $orderId = $item['order_id'];
        if (!isset($groups[$orderId])) {
            $groups[$orderId] = array();
        }
        $groups[$orderId][] = $item;
    }
    return $groups;
}

$orderGroups = groupDataByOrderId($saleHistoryData);

// Close DB connection
mysqli_close($connection);
ob_end_flush();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title><?php echo htmlspecialchars($tx ?? 'Orders'); ?></title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@200;300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/custom_css.css" />

<style>
body { font-family: 'Quicksand', sans-serif; background: #f5f7fb; }
#table-container-single { max-height: 660px; overflow-y: auto; }
.bg-dark2 { background:#0A4657; color:#fff; display:inline-block; padding:4px 8px; border-radius:12px; }
.header { background: linear-gradient(90deg,#0a4657,#060606); color:#fff; position:fixed; top:0; width:100%; z-index:2; height:75px; }
.main-content { margin-top:80px; }
.table-sm td, .table-sm th { vertical-align: middle; }
.single-view-content { padding:8px; background: #fff; border-radius: 16px; box-shadow: 0 5px 20px rgba(0,0,0,0.08); }
.order-id-badge { background: #0A4657; color: #fff; padding: 6px 14px; border-radius: 40px; font-size: 14px; font-weight: 600; display: inline-block; }
.info-line { display: flex; align-items: center; gap: 12px; margin-bottom: 12px; padding: 6px 0; border-bottom: 1px solid #eee; }
.info-icon { width: 32px; height: 32px; background: #eef2fa; border-radius: 50%; display: inline-flex; align-items: center; justify-content: center; color: #0A4657; }
.summary-card { background: #f8f9fc; border-radius: 12px; padding: 12px; margin-top: 15px; }
.summary-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px dashed #dee2e6; }
.summary-grand { background: #0A4657; color: white; border-radius: 12px; padding: 12px; margin-top: 10px; font-weight: 700; }
.batch-badge { background: #e9ecef; color: #495057; padding: 2px 8px; border-radius: 20px; font-size: 11px; font-family: monospace; }
@media (max-width:880px){ .sidebar{display:none;} .main-content { margin-top: 70px; } }
</style>
</head>
<body>
<div class="container-fluid header">
    <div class="row align-items-center h-100">
        <div class="col-3">
            <img src="../img/logo231.png" style="margin-top:5px;" width="72" height="66" alt="Logo">
        </div>
        <div class="col-6 text-center">
            <h3 style="color:#fff; font-weight:700; text-transform:uppercase; line-height:60px; font-size:28px;">
                <?php echo htmlspecialchars($tx ?? 'Quotations'); ?>
            </h3>
        </div>
        <div class="col-3 text-end">
            <a href="addproduct.php" class="btn btn-light" style="margin-top:20px;"><i class="fas fa-arrow-left me-1"></i>Back</a>
        </div>
    </div>
</div>

<div class="container-fluid main-content" style="text-transform:capitalize;">
    <div class="row g-4">
        <div class="col-md-6">
            <!-- Only Quotation History tab remains -->
            <div class="card shadow-sm border-0 rounded-4">
                <div class="card-body p-0">
                    <ul class="nav nav-tabs border-0 pt-2 px-3">
                        <li class="nav-item">
                            <a class="nav-link active text-dark fw-semibold" id="saleHistory-tab" data-bs-toggle="tab" href="#saleHistory" role="tab">
                                <i class="fas fa-file-invoice me-1"></i> Quotation History
                            </a>
                        </li>
                    </ul>

                    <div class="tab-content p-3">
                        <div class="tab-pane fade show active" id="saleHistory" role="tabpanel">
                            <div class="mb-3">
                                <div class="input-group">
                                    <span class="input-group-text bg-white border-end-0"><i class="fas fa-search text-muted"></i></span>
                                    <input type="text" class="form-control border-start-0 ps-0" id="saleOrderID" placeholder="Search by Order ID, Customer, Amount...">
                                </div>
                            </div>
                            
                            <div style="max-height: 550px; overflow-y: auto;">
                                <table class="table table-hover table-sm text-center">
                                    <thead style="background:#212529; color:#fff; position: sticky; top: 0;">
                                        <tr>
                                            <th>Date</th>
                                            <th>Name</th>
                                            <th>Order</th>
                                            <th>Amount(Rs)</th>
                                            <th>Status</th>
                                            <th>Print</th>
                                            <!--<th>Edit</th>-->
                                            <th>Delete</th>
                                            <!--<th>Add Item</th>-->
                                        </tr>
                                    </thead>
                                    <tbody id="saleHistoryTableBody">
                                        <?php
                                        // Render rows: iterate in descending order already fetched but ensure keys preserve grouping order
                                        foreach ($orderGroups ? array_reverse($orderGroups, true) : [] as $orderId => $group):
                                            $subtotal = 0.0;
                                            foreach ($group as $orderRow) {
                                                $gross = floatval($orderRow['product_quantity']) * floatval($orderRow['product_price']);
                                                $discountAmount = ($gross * floatval($orderRow['discount'])) / 100;
                                                $productTotal = $gross - $discountAmount;
                                                $subtotal += $productTotal;
                                            }
                                        ?>
                                        <tr class="sale-history-row" data-order-id="<?php echo htmlspecialchars($orderId); ?>" style="cursor: pointer;">
                                            <td class="fw-semibold small"><?php echo htmlspecialchars($group[0]['date_time']); ?></td>
                                            <td class="fw-semibold"><?php echo htmlspecialchars($group[0]['customer_name']); ?></td>
                                            <td><span class="badge bg-dark bg-opacity-10 text-dark px-2 py-1 rounded-pill"><?php echo htmlspecialchars($orderId); ?></span></td>
                                            <td class="fw-bold text-success"><?php echo number_format($subtotal, 2); ?></td>
                                            <td><span class="badge bg-info bg-opacity-10 text-info px-2 py-1"><?php echo htmlspecialchars($group[0]['paid_by']); ?></span></td>
                                            <td>
                                                <a href="printq.php?order_id=<?php echo urlencode($orderId); ?>" target="_blank" class="btn btn-sm btn-outline-secondary" style="border-radius:20px;">
                                                    <i class="fas fa-print"></i>
                                                </a>
                                            </td>
                                            <!--<td>-->
                                            <!--    <a href="edit_order_q.php?order_id=<?php echo urlencode($orderId); ?>" class="btn btn-sm btn-outline-primary">-->
                                            <!--        <i class="fas fa-edit"></i>-->
                                            <!--    </a>-->
                                            <!--</td>-->
                                            <td>
                                                <a href="order_detail_q.php?delete_order_id=<?php echo urlencode($orderId); ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Are you sure you want to delete this order?');">
                                                    <i class="fas fa-trash-alt"></i>
                                                </a>
                                            </td>
                                            <!--<td>-->
                                            <!--    <a href="add_item_q.php?order_id=<?php echo urlencode($orderId); ?>" class="btn btn-sm btn-outline-success">-->
                                            <!--        <i class="fas fa-plus"></i>-->
                                            <!--    </a>-->
                                            <!--</td>-->
                                        </tr>
                                        <?php endforeach; ?>
                                        <?php if (empty($orderGroups)): ?>
                                        <tr>
                                            <td colspan="9" class="text-center text-muted py-4">No quotation records found</td>
                                        </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Single view column -->
        <div class="col-md-6">
            <div class="card shadow-sm border-0 rounded-4">
                <div class="card-body p-4" id="singleView">
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-receipt fa-3x mb-3 opacity-25"></i>
                        <p class="mb-0">Click on any quotation row to see full details</p>
                        <small class="text-muted">Includes batch numbers and product information</small>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Bootstrap 5 bundle -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>

<script>
/* order_detail_q.php - Enhanced with batch number display */
$(function () {

    // Expose PHP grouped data to JS (safe encode)
    const SALE_HISTORY = <?php echo json_encode($orderGroups ?? [], JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT); ?>;

    // --------- helper: parse date robustly ----------
    function parseDate(text) {
        const d = new Date(text);
        if (!isNaN(d)) return d;
        // Try replace common separators (fallback)
        const cleaned = text.replace(/-/g,'/').replace(/(\.\d+)?$/,'');
        const d2 = new Date(cleaned);
        return isNaN(d2) ? null : d2;
    }

    // --------- Sort sale history rows by date desc ----------
    (function sortSaleHistory() {
        const tbody = document.getElementById('saleHistoryTableBody');
        if (!tbody) return;
        const rows = Array.from(tbody.rows);
        rows.sort((a,b) => {
            const aText = a.cells && a.cells[0] ? a.cells[0].innerText.trim() : '';
            const bText = b.cells && b.cells[0] ? b.cells[0].innerText.trim() : '';
            const da = parseDate(aText), db = parseDate(bText);
            if (da && db) return db - da;
            if (da) return -1;
            if (db) return 1;
            return 0;
        });
        tbody.innerHTML = '';
        rows.forEach(r => tbody.appendChild(r));
    })();

    // --------- Filter table ----------
    function filterTable(selector, text) {
        $(selector + ' tr').each(function () {
            const content = $(this).text().toLowerCase();
            $(this).toggle(!text || content.indexOf(text.toLowerCase()) !== -1);
        });
    }
    $('#saleOrderID').on('input', function () {
        filterTable('#saleHistoryTableBody', $(this).val());
    });

    // --------- Render single view for an order (with batch numbers) ----------
    function renderSingleView(orderId) {
        const group = SALE_HISTORY[orderId];
        if (!group || !group.length) {
            $('#singleView').html('<div class="text-center text-muted py-5"><i class="fas fa-exclamation-circle fa-2x mb-2"></i><p>Order details not found.</p></div>');
            return;
        }

        // Compute subtotal and build rows with batch number
        let subtotal = 0;
        let rowsHtml = '';
        
        group.forEach(p => {
            const qty = parseFloat(p.product_quantity) || 0;
            const price = parseFloat(p.product_price) || 0;
            const saleCost = parseFloat(p.sale_cost) || 0;
            const discPct = parseFloat(p.discount) || 0;
            const inches = parseFloat(p.inches) || 1;
            const batchNo = p.batch_no || '-';
            
            // Gross calculation: qty * price (original calculation)
            const gross = qty * price;
            const discAmt = (gross * discPct) / 100;
            const total = gross - discAmt;
            subtotal += total;

            rowsHtml += `<tr style="border-bottom: 1px solid #eee;">
                <td style="padding: 10px 5px; font-weight: 600;">${escapeHtml(p.product_name || '')}</td>
                <td style="padding: 10px 5px;"><span class="batch-badge">${escapeHtml(batchNo)}</span></td>
                <td style="padding: 10px 5px;">${qty}</td>
                <td style="padding: 10px 5px;">${inches}</td>
                <td style="padding: 10px 5px;">${price.toFixed(2)}</td>
                <td style="padding: 10px 5px;">${saleCost.toFixed(2)}</td>
                <td style="padding: 10px 5px;">${gross.toFixed(2)}</td>
                <td style="padding: 10px 5px;">${discAmt.toFixed(2)}</td>
                <td style="padding: 10px 5px; font-weight: 700; color: #0A4657;">${total.toFixed(2)}</td>
            </tr>`;
        });

        const sale = group[0];
        const discountAmount = parseFloat(sale.discounted) || 0;
        const installation = parseFloat(sale.installation) || 0;
        const preAmount = parseFloat(sale.pre_amount) || 0;
        const grandAmount = parseFloat(sale.grand_amount) || 0;
        const cashAmount = parseFloat(sale.cash_amount) || 0;
        const changeAmount = parseFloat(sale.change_amount) || 0;
        
        const totalAfterDisc = subtotal - discountAmount;
        const finalGrand = totalAfterDisc + preAmount + installation;

        const html = `
            <div>
                <div class="d-flex justify-content-between align-items-center flex-wrap mb-4">
                    <div class="order-id-badge">
                        <i class="fas fa-hashtag me-1"></i> ${escapeHtml(orderId)}
                    </div>
                    <small class="text-muted"><i class="far fa-calendar-alt me-1"></i> ${escapeHtml(sale.date_time || '')}</small>
                </div>
                
                <div class="info-line">
                    <div class="info-icon"><i class="fas fa-user"></i></div>
                    <div><strong>Customer:</strong> ${escapeHtml(sale.customer_name || '-')}</div>
                </div>
                <div class="info-line">
                    <div class="info-icon"><i class="fas fa-phone-alt"></i></div>
                    <div><strong>Phone:</strong> ${escapeHtml(sale.customer_phone || '-')}</div>
                </div>
                <div class="info-line">
                    <div class="info-icon"><i class="fas fa-credit-card"></i></div>
                    <div><strong>Payment:</strong> ${escapeHtml(sale.paid_by || '-')}</div>
                </div>
                
                <hr class="my-3">
                
                <div style="max-height: 350px; overflow-y: auto;">
                    <table class="table table-sm">
                        <thead style="background: #f0f4f8; position: sticky; top: 0;">
                            <tr style="font-size: 12px;">
                                <th>Product</th>
                                <th>Batch No</th>
                                <th>Qty</th>
                                <th>Inches</th>
                                <th>Unit Price</th>
                                <th>Sale Cost</th>
                                <th>Gross</th>
                                <th>Disc</th>
                                <th>Total</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${rowsHtml}
                        </tbody>
                    </table>
                </div>
                
                <div class="summary-card">
                    <div class="summary-row">
                        <span>Subtotal</span>
                        <span class="fw-bold">Rs ${subtotal.toFixed(2)}</span>
                    </div>
                    <div class="summary-row">
                        <span>Discount (-)</span>
                        <span class="fw-bold text-danger">Rs ${discountAmount.toFixed(2)}</span>
                    </div>
                    <div class="summary-row">
                        <span>Total after discount</span>
                        <span class="fw-bold">Rs ${totalAfterDisc.toFixed(2)}</span>
                    </div>
                    <div class="summary-row">
                        <span>Installation</span>
                        <span class="fw-bold">Rs ${installation.toFixed(2)}</span>
                    </div>
                    <div class="summary-row">
                        <span>Pre Amount</span>
                        <span class="fw-bold">Rs ${preAmount.toFixed(2)}</span>
                    </div>
                    <div class="summary-grand d-flex justify-content-between align-items-center">
                        <span><i class="fas fa-calculator me-1"></i> Grand Total</span>
                        <span class="fs-5">Rs ${grandAmount > 0 ? grandAmount.toFixed(2) : finalGrand.toFixed(2)}</span>
                    </div>
                    ${cashAmount > 0 ? `<div class="summary-row mt-2">
                        <span>Cash Received</span>
                        <span class="fw-bold text-success">Rs ${cashAmount.toFixed(2)}</span>
                    </div>` : ''}
                    ${changeAmount > 0 ? `<div class="summary-row">
                        <span>Change Returned</span>
                        <span class="fw-bold">Rs ${changeAmount.toFixed(2)}</span>
                    </div>` : ''}
                </div>
                
                <div class="mt-4 d-flex justify-content-end gap-2">
                    <button class="btn btn-outline-secondary btn-sm rounded-pill" id="printSingleViewBtn">
                        <i class="fas fa-print me-1"></i> Print Quotation
                    </button>
                </div>
            </div>
        `;

        $('#singleView').html(html);
        
        // Attach print handler after HTML is inserted
        $('#printSingleViewBtn').off('click').on('click', function(e) {
            e.preventDefault();
            printSingleView(orderId);
        });
    }
    
    // Helper function to escape HTML
    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/[&<>]/g, function(m) {
            if (m === '&') return '&amp;';
            if (m === '<') return '&lt;';
            if (m === '>') return '&gt;';
            return m;
        }).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, function(c) {
            return c;
        });
    }

    // --------- Print a single view cleanly ----------
    function printSingleView(orderId) {
        const contentEl = document.getElementById('singleView');
        if (!contentEl) return;
        
        // Clone the content to avoid modifying the original
        const cloneContent = contentEl.cloneNode(true);
        
        // Remove the print button from the clone
        const printBtn = cloneContent.querySelector('#printSingleViewBtn');
        if (printBtn) printBtn.remove();
        
        const w = window.open('', '_blank', 'width=900,height=900,scrollbars=yes');
        if (!w) {
            alert('Pop-up blocked. Please allow pop-ups for this site to print.');
            return;
        }
        
        // Professional print CSS
        const style = `
            <style>
                * { margin: 0; padding: 0; box-sizing: border-box; }
                body { 
                    font-family: 'Segoe UI', Arial, sans-serif; 
                    padding: 30px 20px; 
                    background: white;
                    font-size: 12px;
                }
                .order-id-badge { 
                    background: #0A4657; 
                    color: white; 
                    padding: 6px 14px; 
                    border-radius: 40px; 
                    font-size: 14px; 
                    font-weight: 600; 
                    display: inline-block; 
                }
                .info-line { 
                    display: flex; 
                    align-items: center; 
                    gap: 12px; 
                    margin-bottom: 12px; 
                    padding: 6px 0; 
                    border-bottom: 1px solid #ddd; 
                }
                .info-icon { 
                    width: 32px; 
                    height: 32px; 
                    background: #eef2fa; 
                    border-radius: 50%; 
                    display: inline-flex; 
                    align-items: center; 
                    justify-content: center; 
                }
                .summary-card { 
                    background: #f8f9fc; 
                    border-radius: 8px; 
                    padding: 12px; 
                    margin-top: 15px; 
                }
                .summary-row { 
                    display: flex; 
                    justify-content: space-between; 
                    padding: 8px 0; 
                    border-bottom: 1px solid #dee2e6; 
                }
                .summary-grand { 
                    background: #0A4657; 
                    color: white; 
                    border-radius: 8px; 
                    padding: 12px; 
                    margin-top: 10px; 
                    display: flex;
                    justify-content: space-between;
                }
                .batch-badge { 
                    background: #e9ecef; 
                    color: #495057; 
                    padding: 2px 8px; 
                    border-radius: 20px; 
                    font-size: 10px; 
                    font-family: monospace; 
                }
                table { 
                    width: 100%; 
                    border-collapse: collapse; 
                    margin-top: 10px;
                }
                th, td { 
                    border: 1px solid #ddd; 
                    padding: 8px; 
                    text-align: center; 
                }
                th { 
                    background: #f2f2f2; 
                    font-weight: 600;
                }
                hr { margin: 15px 0; }
                @media print {
                    body { padding: 0; margin: 0; }
                    .no-print { display: none; }
                }
            </style>
        `;
        
        w.document.write(`<html><head><title>Quotation - ${escapeHtml(orderId)}</title>${style}</head><body>`);
        w.document.write(cloneContent.innerHTML);
        w.document.write('</body></html>');
        w.document.close();
        
        w.focus();
        setTimeout(() => {
            w.print();
        }, 300);
    }

    // --------- Row click binding (single handler) ----------
    $(document).on('click', '.sale-history-row', function (e) {
        // Don't trigger if clicking on action buttons (print, edit, delete, add item)
        if ($(e.target).closest('a, button').length) return;
        
        const orderId = $(this).data('order-id');
        if (!orderId) return;
        renderSingleView(orderId);
    });
    
    // Auto-select first row on page load (optional)
    const firstRow = $('.sale-history-row').first();
    if (firstRow.length && firstRow.data('order-id')) {
        renderSingleView(firstRow.data('order-id'));
    }
});
</script>
</body>
</html>