<?php
session_start();
include_once('../includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:../logout.php');
    exit();
}

$startDate = isset($_GET['startDate']) && $_GET['startDate'] ? $_GET['startDate'] : date('Y-m-01');
$endDate = isset($_GET['endDate']) && $_GET['endDate'] ? $_GET['endDate'] : date('Y-m-t');
$customerId = isset($_GET['customerId']) ? trim($_GET['customerId']) : '';
$salesType = isset($_GET['salesType']) ? trim($_GET['salesType']) : '';
$paymentStatus = isset($_GET['paymentStatus']) ? trim($_GET['paymentStatus']) : '';

// Get store settings
$storeSettingsQuery = "SELECT * FROM tblstore_settings WHERE StoreCode = 'ST0002' LIMIT 1";
$storeSettingsResult = mysqli_query($con, $storeSettingsQuery);
$storeSettings = null;

if ($storeSettingsResult && mysqli_num_rows($storeSettingsResult) > 0) {
    $storeSettings = mysqli_fetch_assoc($storeSettingsResult);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Print | Detailed Sales Report</title>
    <style>
        @page {
            size: A4;
            margin: 8mm;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Arial', 'Helvetica Neue', sans-serif;
            font-size: 10px;
            color: #1a1a1a;
            line-height: 1.3;
            background: #f5f5f5;
        }

        .print-container {
            max-width: 210mm;
            margin: 10px auto;
            padding: 0;
            background: white;
        }

        .print-controls {
            display: flex;
            justify-content: flex-end;
            gap: 8px;
            padding: 12px;
            background: white;
            border-bottom: 2px solid #ddd;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .print-controls button {
            padding: 8px 16px;
            border: 1px solid #ccc;
            background: white;
            color: #333;
            border-radius: 4px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .print-controls button:hover {
            background: #f0f0f0;
        }

        .print-controls button.print {
            background: #1976d2;
            color: white;
            border-color: #1976d2;
        }

        .print-controls button.print:hover {
            background: #1565c0;
        }

        /* Report Header */
        .report-header {
            text-align: center;
            padding: 15px;
            border-bottom: 3px solid #1a1a1a;
            margin-bottom: 15px;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
        }

        .logo-container {
            flex-shrink: 0;
        }

        .logo-container img {
            width: 70px;
            height: 70px;
            object-fit: contain;
        }

        .header-text {
            flex: 1;
            text-align: center;
        }

        .company-name {
            font-size: 18px;
            font-weight: bold;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 5px;
        }

        .company-details {
            font-size: 9px;
            color: #64748b;
            margin: 3px 0;
        }

        .report-title {
            font-size: 14px;
            font-weight: bold;
            color: #1976d2;
            margin: 8px 0;
        }

        .report-meta {
            font-size: 9px;
            color: #666;
            margin-top: 5px;
        }

        /* Invoice Card */
        .invoice-card {
            border: 2px solid #1a1a1a;
            margin-bottom: 20px;
            page-break-inside: avoid;
            background: white;
        }

        .invoice-header {
            background: #1a1a1a;
            color: white;
            padding: 8px 12px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .invoice-number {
            font-size: 12px;
            font-weight: bold;
        }

        .invoice-date {
            font-size: 10px;
        }

        .invoice-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            padding: 12px;
            border-bottom: 1px solid #ddd;
        }

        .detail-section h4 {
            font-size: 10px;
            font-weight: bold;
            margin-bottom: 6px;
            color: #1976d2;
            text-transform: uppercase;
        }

        .detail-row {
            display: flex;
            font-size: 9px;
            margin: 3px 0;
        }

        .detail-label {
            font-weight: bold;
            width: 100px;
            flex-shrink: 0;
        }

        .detail-value {
            flex: 1;
        }

        /* Items Table */
        .items-section {
            padding: 0;
        }

        .items-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 9px;
        }

        .items-table thead {
            background: #f0f0f0;
        }

        .items-table th {
            padding: 6px 4px;
            text-align: left;
            font-weight: bold;
            border: 1px solid #ddd;
            font-size: 8px;
            text-transform: uppercase;
        }

        .items-table td {
            padding: 5px 4px;
            border: 1px solid #ddd;
            vertical-align: top;
        }

        .items-table tbody tr:nth-child(even) {
            background: #fafafa;
        }

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

        .text-center {
            text-align: center;
        }

        /* Summary Section */
        .invoice-summary {
            padding: 12px;
            background: #f9f9f9;
        }

        .summary-grid {
            display: grid;
            grid-template-columns: 2fr 1fr;
            gap: 15px;
        }

        .gst-breakdown {
            font-size: 9px;
        }

        .gst-breakdown h4 {
            font-size: 10px;
            font-weight: bold;
            margin-bottom: 6px;
            color: #1976d2;
        }

        .gst-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 5px;
        }

        .gst-table th,
        .gst-table td {
            padding: 4px;
            border: 1px solid #ddd;
            font-size: 8px;
        }

        .gst-table th {
            background: #e0e0e0;
            font-weight: bold;
        }

        .totals-section {
            font-size: 9px;
        }

        .total-row {
            display: flex;
            justify-content: space-between;
            padding: 4px 0;
            border-bottom: 1px solid #e0e0e0;
        }

        .total-row.grand {
            font-weight: bold;
            font-size: 11px;
            background: #1a1a1a;
            color: white;
            padding: 8px 10px;
            margin-top: 5px;
            border-radius: 3px;
        }

        .total-row.highlight {
            background: #e3f2fd;
            padding: 5px 10px;
            font-weight: bold;
        }

        .payment-info {
            margin-top: 8px;
            padding: 8px;
            background: white;
            border: 1px solid #ddd;
            border-radius: 3px;
        }

        .payment-info h5 {
            font-size: 9px;
            font-weight: bold;
            margin-bottom: 4px;
            color: #1976d2;
        }

        .badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 8px;
            font-weight: bold;
            text-transform: uppercase;
        }

        .badge-paid {
            background: #d1fae5;
            color: #065f46;
        }

        .badge-unpaid {
            background: #fee2e2;
            color: #991b1b;
        }

        .badge-partial {
            background: #fef3c7;
            color: #92400e;
        }

        .separator {
            height: 20px;
            border-bottom: 2px dashed #ccc;
            margin: 15px 0;
        }

        .status-message {
            text-align: center;
            padding: 40px 20px;
            color: #666;
            font-size: 12px;
        }

        .no-print {
            display: block;
        }

        /* Overall Summary */
        .overall-summary {
            background: #1a1a1a;
            color: white;
            padding: 15px;
            margin: 20px 0;
            border-radius: 5px;
        }

        .overall-summary h3 {
            font-size: 12px;
            margin-bottom: 10px;
            text-transform: uppercase;
        }

        .summary-stats {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
        }

        .stat-box {
            background: rgba(255,255,255,0.1);
            padding: 8px;
            border-radius: 3px;
            text-align: center;
        }

        .stat-label {
            font-size: 8px;
            opacity: 0.8;
            margin-bottom: 4px;
        }

        .stat-value {
            font-size: 13px;
            font-weight: bold;
        }

        @media print {
            @page {
                size: A4;
                margin: 8mm;
            }

            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }

            body {
                background: white;
            }

            .print-container {
                margin: 0;
                padding: 0;
                max-width: 100%;
            }

            .no-print {
                display: none !important;
            }

            .invoice-card {
                page-break-inside: avoid;
                break-inside: avoid;
            }

            .separator {
                page-break-after: avoid;
            }
        }
    </style>
</head>
<body>
    <div class="print-container">
        <div class="print-controls no-print">
            <button type="button" class="print" onclick="window.print()">🖨️ Print Report</button>
            <button type="button" onclick="window.close()">✕ Close</button>
        </div>

        <div id="loadingState" class="status-message">
            ⏳ Loading detailed report data...
        </div>

        <div id="errorState" class="status-message" style="display: none; color: #991b1b;">
            ⚠️ Unable to load report. Please close this tab and try again.
        </div>

        <div id="reportContent" style="display: none;">
            <div class="report-header">
                <?php if ($storeSettings && !empty($storeSettings['StoreLogo1'])): ?>
                <div class="logo-container">
                    <img src="../<?php echo htmlspecialchars($storeSettings['StoreLogo1']); ?>" alt="Logo">
                </div>
                <?php endif; ?>
                <div class="header-text">
                    <div class="company-name"><?php echo strtoupper(htmlspecialchars($storeSettings['StoreName'] ?? 'STORE NAME')); ?></div>
                    <?php if (!empty($storeSettings['Address'])): ?>
                    <div class="company-details"><?php echo htmlspecialchars($storeSettings['Address']); ?></div>
                    <?php endif; ?>
                    <?php if (!empty($storeSettings['City'])): ?>
                    <div class="company-details"><?php echo htmlspecialchars($storeSettings['City']); ?><?php echo !empty($storeSettings['Postcode']) ? ' - ' . htmlspecialchars($storeSettings['Postcode']) : ''; ?> | Ph: <?php echo htmlspecialchars($storeSettings['Mobile'] ?? ''); ?></div>
                    <?php endif; ?>
                    <?php if (!empty($storeSettings['GSTNumber'])): ?>
                    <div class="company-details">GSTIN: <?php echo htmlspecialchars($storeSettings['GSTNumber']); ?></div>
                    <?php endif; ?>
                    <div class="report-title">Detailed Sales Report</div>
                    <div class="report-meta">
                        <strong>Period:</strong> <span id="reportPeriod"></span><br>
                        <span id="filterInfo"></span><br>
                        <strong>Generated:</strong> <span id="generatedDate"></span>
                    </div>
                </div>
            </div>

            <div class="overall-summary">
                <h3>Overall Summary</h3>
                <div class="summary-stats">
                    <div class="stat-box">
                        <div class="stat-label">Total Invoices</div>
                        <div class="stat-value" id="overallBills">0</div>
                    </div>
                    <div class="stat-box">
                        <div class="stat-label">Total Sales</div>
                        <div class="stat-value" id="overallSales">₹0.00</div>
                    </div>
                    <div class="stat-box">
                        <div class="stat-label">Total Profit</div>
                        <div class="stat-value" id="overallProfit">₹0.00</div>
                    </div>
                    <div class="stat-box">
                        <div class="stat-label">Outstanding</div>
                        <div class="stat-value" id="overallOutstanding">₹0.00</div>
                    </div>
                </div>
            </div>

            <div id="invoicesContainer">
                <!-- Invoices will be rendered here -->
            </div>
        </div>
    </div>

    <script>
        const PRINT_PARAMS = <?php echo json_encode([
            'startDate' => $startDate,
            'endDate' => $endDate,
            'customerId' => $customerId,
            'salesType' => $salesType,
            'paymentStatus' => $paymentStatus,
        ]); ?>;

        function formatCurrency(amount) {
            return '₹' + Number(amount || 0).toLocaleString('en-IN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }

        function formatDate(dateStr) {
            if (!dateStr) return '-';
            const date = new Date(dateStr);
            const day = String(date.getDate()).padStart(2, '0');
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const year = date.getFullYear();
            return `${day}/${month}/${year}`;
        }

        function formatDateTime(date) {
            return date.toLocaleString('en-IN', {
                day: '2-digit',
                month: 'short',
                year: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        function loadDetailedReport() {
            const { startDate, endDate, customerId, salesType, paymentStatus } = PRINT_PARAMS;
            let apiUrl = `api/get-detailed-sales.php?startDate=${startDate}&endDate=${endDate}`;
            if (customerId) {
                apiUrl += `&customerId=${encodeURIComponent(customerId)}`;
            }
            if (salesType) {
                apiUrl += `&salesType=${encodeURIComponent(salesType)}`;
            }
            if (paymentStatus) {
                apiUrl += `&paymentStatus=${encodeURIComponent(paymentStatus)}`;
            }

            fetch(apiUrl)
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.message || 'API error');
                    }
                    renderDetailedReport(data);
                    setTimeout(() => window.print(), 500);
                })
                .catch(error => {
                    console.error('Error loading report:', error);
                    document.getElementById('loadingState').style.display = 'none';
                    document.getElementById('errorState').style.display = 'block';
                });
        }

        function renderDetailedReport(data) {
            const { invoices, summary, startDate, endDate, filters } = data;

            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('reportContent').style.display = 'block';

            // Set header info
            document.getElementById('reportPeriod').textContent = `${formatDate(startDate)} to ${formatDate(endDate)}`;
            
            let filterText = '';
            if (filters.customerName) {
                filterText += `Customer: ${filters.customerName} | `;
            }
            if (filters.salesType) {
                filterText += `Type: ${filters.salesType} | `;
            }
            if (filters.paymentStatus) {
                filterText += `Payment: ${filters.paymentStatus} | `;
            }
            document.getElementById('filterInfo').textContent = filterText || 'All Transactions';
            document.getElementById('generatedDate').textContent = formatDateTime(new Date());

            // Set overall summary
            document.getElementById('overallBills').textContent = summary.totalBills;
            document.getElementById('overallSales').textContent = formatCurrency(summary.totalBillAmount);
            document.getElementById('overallProfit').textContent = formatCurrency(summary.totalProfit);
            document.getElementById('overallOutstanding').textContent = formatCurrency(summary.totalUnpaid);

            // Render invoices
            renderInvoices(invoices);
        }

        function renderInvoices(invoices) {
            const container = document.getElementById('invoicesContainer');

            if (!invoices || invoices.length === 0) {
                container.innerHTML = '<div class="status-message">No invoices found for the selected criteria.</div>';
                return;
            }

            let html = '';

            invoices.forEach((invoice, index) => {
                const isReturn = invoice.SalesType && invoice.SalesType.includes('RETURN');
                const paymentStatusClass = invoice.PaymentStatus === 'Paid' ? 'badge-paid' : 
                                          invoice.PaymentStatus === 'Unpaid' ? 'badge-unpaid' : 
                                          'badge-partial';

                html += `
                    <div class="invoice-card">
                        <div class="invoice-header">
                            <div class="invoice-number">
                                Invoice: ${invoice.InvoiceNumber}
                                ${isReturn ? ' <span style="color: #ff6b6b;">(RETURN)</span>' : ''}
                            </div>
                            <div class="invoice-date">
                                Date: ${formatDate(invoice.SaleDate)} | 
                                <span class="badge ${paymentStatusClass}">${invoice.PaymentStatus}</span>
                            </div>
                        </div>

                        <div class="invoice-details">
                            <div class="detail-section">
                                <h4>Customer Information</h4>
                                <div class="detail-row">
                                    <span class="detail-label">Name:</span>
                                    <span class="detail-value">${invoice.CustomerName || 'N/A'}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Mobile:</span>
                                    <span class="detail-value">${invoice.Mobile || 'N/A'}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Address:</span>
                                    <span class="detail-value">${invoice.Address || 'N/A'}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">City:</span>
                                    <span class="detail-value">${invoice.City || 'N/A'}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">GST Number:</span>
                                    <span class="detail-value">${invoice.GSTNumber || 'N/A'}</span>
                                </div>
                            </div>

                            <div class="detail-section">
                                <h4>Invoice Details</h4>
                                <div class="detail-row">
                                    <span class="detail-label">Sales Type:</span>
                                    <span class="detail-value">${invoice.SalesType || 'N/A'}</span>
                                </div>
                                <div class="detail-row">
                                    <span class="detail-label">Payment Mode:</span>
                                    <span class="detail-value">${getPaymentMode(invoice)}</span>
                                </div>
                                ${invoice.ReferenceNumber ? `
                                <div class="detail-row">
                                    <span class="detail-label">Reference:</span>
                                    <span class="detail-value">${invoice.ReferenceNumber}</span>
                                </div>
                                ` : ''}
                                ${invoice.TransportName ? `
                                <div class="detail-row">
                                    <span class="detail-label">Transport:</span>
                                    <span class="detail-value">${invoice.TransportName}</span>
                                </div>
                                ` : ''}
                                ${invoice.VehicleNumber ? `
                                <div class="detail-row">
                                    <span class="detail-label">Vehicle:</span>
                                    <span class="detail-value">${invoice.VehicleNumber}</span>
                                </div>
                                ` : ''}
                            </div>
                        </div>

                        <div class="items-section">
                            <table class="items-table">
                                <thead>
                                    <tr>
                                        <th style="width: 4%;">S.No</th>
                                        <th style="width: 25%;">Product Name</th>
                                        <th style="width: 8%;">HSN Code</th>
                                        <th style="width: 7%;" class="text-right">Rate</th>
                                        <th style="width: 7%;" class="text-right">Qty</th>
                                        <th style="width: 8%;" class="text-right">Discount</th>
                                        <th style="width: 10%;" class="text-right">Taxable</th>
                                        <th style="width: 5%;" class="text-center">Tax %</th>
                                        <th style="width: 8%;" class="text-right">CGST</th>
                                        <th style="width: 8%;" class="text-right">SGST</th>
                                        <th style="width: 10%;" class="text-right">Amount</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${renderInvoiceItems(invoice.items, isReturn)}
                                </tbody>
                            </table>
                        </div>

                        <div class="invoice-summary">
                            <div class="summary-grid">
                                <div class="gst-breakdown">
                                    <h4>GST Summary</h4>
                                    ${renderGSTSummary(invoice.gstSummary)}
                                </div>

                                <div class="totals-section">
                                    <div class="total-row">
                                        <span>Sub Total:</span>
                                        <span>${formatCurrency(invoice.SubTotal)}</span>
                                    </div>
                                    ${invoice.DiscountAmount > 0 ? `
                                    <div class="total-row">
                                        <span>Discount:</span>
                                        <span>-${formatCurrency(invoice.DiscountAmount)}</span>
                                    </div>
                                    ` : ''}
                                    ${invoice.CooliAmount > 0 ? `
                                    <div class="total-row">
                                        <span>Cooli Amount:</span>
                                        <span>${formatCurrency(invoice.CooliAmount)}</span>
                                    </div>
                                    ` : ''}
                                    ${invoice.TransportGSTAmount > 0 ? `
                                    <div class="total-row">
                                        <span>Transport GST:</span>
                                        <span>${formatCurrency(invoice.TransportGSTAmount)}</span>
                                    </div>
                                    ` : ''}
                                    ${invoice.RoundOffAmount != 0 ? `
                                    <div class="total-row">
                                        <span>Round Off:</span>
                                        <span>${formatCurrency(invoice.RoundOffAmount)}</span>
                                    </div>
                                    ` : ''}
                                    <div class="total-row grand">
                                        <span>FINAL AMOUNT:</span>
                                        <span>${formatCurrency(invoice.FinalAmount)}</span>
                                    </div>

                                    <div class="payment-info">
                                        <h5>Payment Breakdown</h5>
                                        ${invoice.CashAmount > 0 ? `
                                        <div class="total-row">
                                            <span>Cash:</span>
                                            <span>${formatCurrency(invoice.CashAmount)}</span>
                                        </div>
                                        ` : ''}
                                        ${invoice.UpiAmount > 0 ? `
                                        <div class="total-row">
                                            <span>UPI:</span>
                                            <span>${formatCurrency(invoice.UpiAmount)}</span>
                                        </div>
                                        ` : ''}
                                        ${invoice.CreditAmount > 0 ? `
                                        <div class="total-row">
                                            <span>Credit:</span>
                                            <span>${formatCurrency(invoice.CreditAmount)}</span>
                                        </div>
                                        ` : ''}
                                        <div class="total-row highlight">
                                            <span>Paid Amount:</span>
                                            <span>${formatCurrency(invoice.PaymentAmount)}</span>
                                        </div>
                                        ${(invoice.FinalAmount - invoice.PaymentAmount) > 0 ? `
                                        <div class="total-row" style="color: #991b1b;">
                                            <span>Outstanding:</span>
                                            <span>${formatCurrency(invoice.FinalAmount - invoice.PaymentAmount)}</span>
                                        </div>
                                        ` : ''}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    ${index < invoices.length - 1 ? '<div class="separator"></div>' : ''}
                `;
            });

            container.innerHTML = html;
        }

        function renderInvoiceItems(items, isReturn) {
            if (!items || items.length === 0) {
                return '<tr><td colspan="11" class="text-center">No items</td></tr>';
            }

            let html = '';
            let sno = 1;

            items.forEach(item => {
                const multiplier = isReturn ? -1 : 1;
                html += `
                    <tr>
                        <td class="text-center">${sno++}</td>
                        <td>${item.ProductName || 'N/A'}</td>
                        <td class="text-center">${item.HSNCode || '-'}</td>
                        <td class="text-right">${formatCurrency(item.Rate)}</td>
                        <td class="text-right">${Number(item.Quantity).toFixed(2)}</td>
                        <td class="text-right">${formatCurrency(item.DiscountAmount)}</td>
                        <td class="text-right">${formatCurrency(item.TaxableAmount * multiplier)}</td>
                        <td class="text-center">${Number(item.TaxPercentage).toFixed(0)}%</td>
                        <td class="text-right">${formatCurrency(item.CGSTAmount * multiplier)}</td>
                        <td class="text-right">${formatCurrency(item.SGSTAmount * multiplier)}</td>
                        <td class="text-right">${formatCurrency(item.FinalAmount * multiplier)}</td>
                    </tr>
                `;
            });

            return html;
        }

        function renderGSTSummary(gstSummary) {
            if (!gstSummary || Object.keys(gstSummary).length === 0) {
                return '<p style="font-size: 9px; color: #666;">No GST breakdown available</p>';
            }

            let html = `
                <table class="gst-table">
                    <thead>
                        <tr>
                            <th>Tax %</th>
                            <th class="text-right">Taxable</th>
                            <th class="text-right">CGST</th>
                            <th class="text-right">SGST</th>
                            <th class="text-right">Total Tax</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

            for (const [rate, amounts] of Object.entries(gstSummary)) {
                html += `
                    <tr>
                        <td>${rate}%</td>
                        <td class="text-right">${formatCurrency(amounts.taxable)}</td>
                        <td class="text-right">${formatCurrency(amounts.cgst)}</td>
                        <td class="text-right">${formatCurrency(amounts.sgst)}</td>
                        <td class="text-right">${formatCurrency(amounts.total)}</td>
                    </tr>
                `;
            }

            html += `
                    </tbody>
                </table>
            `;

            return html;
        }

        function getPaymentMode(invoice) {
            let modes = [];
            if (invoice.CashAmount > 0) modes.push('Cash');
            if (invoice.UpiAmount > 0) modes.push('UPI');
            if (invoice.CreditAmount > 0) modes.push('Credit');
            return modes.length > 0 ? modes.join(' + ') : (invoice.PaymentMode || 'N/A');
        }

        document.addEventListener('DOMContentLoaded', loadDetailedReport);
    </script>
</body>
</html>
