<?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');
$supplierId = isset($_GET['supplierId']) ? trim($_GET['supplierId']) : '';
$purchaseType = isset($_GET['purchaseType']) ? trim($_GET['purchaseType']) : '';

// 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 | GST Purchase Report</title>
    <style>
        :root {
            --primary-color: #1a1a1a;
            --success-color: #0d6e5f;
            --danger-color: #991b1b;
            --accent-color: #2c3e50;
            --border-color: #cbd5e0;
            --muted-text: #64748b;
            --background-color: #f8fafc;
        }

        * {
            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: #e2e8f0;
        }

        .print-container {
            max-width: 210mm;
            margin: 10px auto;
            padding: 15px;
            background: white;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .print-controls {
            display: flex;
            justify-content: flex-end;
            gap: 6px;
            margin-bottom: 10px;
        }

        .print-controls button {
            padding: 5px 10px;
            border: 1px solid var(--border-color);
            background: white;
            color: var(--accent-color);
            border-radius: 3px;
            font-size: 11px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .print-controls button:hover {
            background: var(--background-color);
        }

        .print-controls button.print {
            background: var(--accent-color);
            color: white;
            border-color: var(--accent-color);
        }

        .print-controls button.print:hover {
            background: var(--primary-color);
        }

        .print-header {
            border-bottom: 2px solid var(--primary-color);
            padding-bottom: 8px;
            margin-bottom: 12px;
        }

        .header-layout {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
        }

        .company-section {
            flex: 1;
            display: flex;
            align-items: flex-start;
            gap: 12px;
        }

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

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

        .company-info {
            flex: 1;
        }

        .company-name {
            font-size: 16px;
            font-weight: 700;
            letter-spacing: 0.5px;
            color: var(--primary-color);
            text-transform: uppercase;
        }

        .company-details {
            font-size: 9px;
            color: var(--muted-text);
            margin-top: 2px;
            line-height: 1.5;
        }

        .report-info {
            text-align: right;
            flex: 0 0 auto;
        }

        .report-title {
            font-size: 13px;
            font-weight: 700;
            color: var(--accent-color);
            margin-bottom: 4px;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

        .report-meta {
            font-size: 9px;
            color: var(--muted-text);
            line-height: 1.4;
        }

        .report-meta strong {
            color: var(--accent-color);
            font-weight: 600;
        }

        .summary-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 8px;
            margin-bottom: 10px;
        }

        .summary-card {
            background: white;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            padding: 8px;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        .summary-card h3 {
            font-size: 8px;
            text-transform: uppercase;
            color: var(--muted-text);
            letter-spacing: 0.3px;
            margin-bottom: 4px;
            font-weight: 600;
        }

        .summary-card .amount {
            font-size: 14px;
            font-weight: 700;
            color: var(--primary-color);
        }

        .summary-card.highlight {
            background: linear-gradient(135deg, #f0fdfa 0%, #e6fffa 100%);
            border-color: #5eead4;
        }

        .summary-card.highlight .amount {
            color: var(--success-color);
        }

        .transaction-info {
            font-size: 9px;
            color: var(--muted-text);
            margin-bottom: 6px;
            padding: 4px 0;
            border-bottom: 1px solid var(--border-color);
        }

        .table-wrapper {
            page-break-inside: auto;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            font-size: 9px;
            border: 1px solid var(--primary-color);
        }

        thead {
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        thead th {
            padding: 5px 6px;
            text-align: left;
            font-size: 8px;
            font-weight: 700;
            letter-spacing: 0.3px;
            text-transform: uppercase;
            background: var(--primary-color);
            color: white;
            border-right: 1px solid rgba(255,255,255,0.1);
        }

        thead th:last-child {
            border-right: none;
        }

        tbody td {
            padding: 4px 6px;
            border-bottom: 1px solid #e5e7eb;
            vertical-align: top;
        }

        tbody tr:nth-child(even) {
            background: #f9fafb;
        }

        tbody tr {
            page-break-inside: avoid;
        }

        .totals-section {
            page-break-inside: avoid;
            margin-top: 0;
        }

        tfoot {
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        tfoot td {
            padding: 6px 8px;
            font-weight: 700;
            background: #e5e7eb;
            border-top: 2px solid var(--primary-color);
            font-size: 10px;
        }

        tfoot tr:last-child td {
            background: var(--primary-color);
            color: white;
            font-size: 11px;
            padding: 8px;
        }

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

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

        .badge {
            display: inline-block;
            padding: 2px 5px;
            border-radius: 2px;
            font-size: 7px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

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

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

        .badge-online {
            background: #dbeafe;
            color: #1e40af;
        }

        .amount-positive {
            color: var(--success-color);
            font-weight: 600;
        }

        .status-message {
            text-align: center;
            padding: 30px 0;
            color: var(--muted-text);
            font-size: 12px;
        }

        .no-print {
            display: block;
        }

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

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

            body {
                background: white;
                font-size: 9px;
            }

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

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

            .print-header {
                margin-bottom: 10px;
                padding-bottom: 6px;
            }

            .summary-grid {
                margin-bottom: 8px;
            }

            table {
                font-size: 8px;
            }

            thead th {
                font-size: 7px;
                padding: 4px 5px;
            }

            tbody td {
                padding: 3px 5px;
            }

            tfoot td {
                padding: 5px 6px;
                font-size: 9px;
            }

            tfoot tr:last-child td {
                font-size: 10px;
                padding: 6px;
            }

            .table-wrapper {
                display: block;
            }

            .totals-section {
                page-break-before: auto;
                page-break-inside: avoid;
                page-break-after: avoid;
            }

            tbody tr {
                page-break-inside: avoid;
            }
        }

        @media (max-width: 768px) {
            .summary-grid {
                grid-template-columns: repeat(2, 1fr);
            }
        }
    </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 report data...
        </div>

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

        <div id="reportContent" style="display: none;">
            <div class="print-header">
                <div class="header-layout">
                    <div class="company-section">
                        <?php if ($storeSettings && !empty($storeSettings['StoreLogo1'])): ?>
                        <div class="logo-container">
                            <img src="../<?php echo htmlspecialchars($storeSettings['StoreLogo1']); ?>" alt="Logo">
                        </div>
                        <?php endif; ?>
                        <div class="company-info">
                            <div class="company-name"><?php echo strtoupper(htmlspecialchars($storeSettings['StoreName'] ?? 'STORE NAME')); ?></div>
                            <div class="company-details">
                                <?php if (!empty($storeSettings['Address'])): ?>
                                <?php echo htmlspecialchars($storeSettings['Address']); ?><br>
                                <?php endif; ?>
                                <?php if (!empty($storeSettings['City'])): ?>
                                <?php echo htmlspecialchars($storeSettings['City']); ?><?php echo !empty($storeSettings['Postcode']) ? ' - ' . htmlspecialchars($storeSettings['Postcode']) : ''; ?><br>
                                <?php endif; ?>
                                <?php if (!empty($storeSettings['Mobile'])): ?>
                                Ph: <?php echo htmlspecialchars($storeSettings['Mobile']); ?>
                                <?php endif; ?>
                                <?php if (!empty($storeSettings['GSTNumber'])): ?>
                                | GSTIN: <?php echo htmlspecialchars($storeSettings['GSTNumber']); ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <div class="report-info">
                        <div class="report-title">GST Purchase Report</div>
                        <div class="report-meta">
                            <div><strong>Period:</strong> <span id="reportPeriod">-</span></div>
                            <div id="supplierDiv"><strong>Supplier:</strong> <span id="reportSupplier">All Suppliers</span></div>
                            <div id="purchaseTypeDiv"><strong>Type:</strong> <span id="reportPurchaseType">All Types</span></div>
                            <div><strong>Generated:</strong> <span id="generatedDate">-</span></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="summary-grid">
                <div class="summary-card highlight">
                    <h3>Total Purchases</h3>
                    <div class="amount" id="totalPurchases">₹0.00</div>
                </div>
                <div class="summary-card">
                    <h3>Taxable Amount</h3>
                    <div class="amount" id="taxableAmount">₹0.00</div>
                </div>
                <div class="summary-card">
                    <h3>CGST Amount</h3>
                    <div class="amount" id="cgstAmount">₹0.00</div>
                </div>
                <div class="summary-card">
                    <h3>SGST Amount</h3>
                    <div class="amount" id="sgstAmount">₹0.00</div>
                </div>
                <div class="summary-card">
                    <h3>IGST Amount</h3>
                    <div class="amount" id="igstAmount">₹0.00</div>
                </div>
                <div class="summary-card highlight">
                    <h3>Total Tax</h3>
                    <div class="amount" id="totalTax">₹0.00</div>
                </div>
            </div>

            <div class="transaction-info">
                <strong>Transaction Count:</strong> <span id="transactionCount">0</span> purchases
            </div>

            <div class="table-wrapper">
                <table>
                    <thead>
                        <tr>
                            <th style="width: 3%;">S.No</th>
                            <th style="width: 5%;">Date</th>
                            <th style="width: 7%;">Bill No</th>
                            <th style="width: 7%;">Purchase Inv No</th>
                            <th style="width: 5%;">Inv Date</th>
                            <th style="width: 9%;">Supplier Name</th>
                            <th style="width: 7%;">GSTIN</th>
                            <th style="width: 5%;">Tax Type</th>
                            <th style="width: 7%;" class="text-right">Taxable Value</th>
                            <th style="width: 3%;" class="text-right">CGST%</th>
                            <th style="width: 5%;" class="text-right">CGST Amt</th>
                            <th style="width: 3%;" class="text-right">SGST%</th>
                            <th style="width: 5%;" class="text-right">SGST Amt</th>
                            <th style="width: 3%;" class="text-right">IGST%</th>
                            <th style="width: 5%;" class="text-right">IGST Amt</th>
                            <th style="width: 6%;" class="text-right">Total Tax</th>
                            <th style="width: 7%;" class="text-right">Total</th>
                        </tr>
                    </thead>
                    <tbody id="purchasesBody">
                        <tr><td colspan="17" class="text-center" style="padding: 20px;">No data</td></tr>
                    </tbody>
                </table>
                <table class="totals-section">
                    <tfoot>
                        <tr>
                            <td colspan="8" class="text-right" style="width: 46%;">PERIOD TOTALS:</td>
                            <td class="text-right" style="width: 7%;" id="totalTaxableFooter">₹0.00</td>
                            <td class="text-right" style="width: 3%;"></td>
                            <td class="text-right" style="width: 5%;" id="totalCGSTFooter">₹0.00</td>
                            <td class="text-right" style="width: 3%;"></td>
                            <td class="text-right" style="width: 5%;" id="totalSGSTFooter">₹0.00</td>
                            <td class="text-right" style="width: 3%;"></td>
                            <td class="text-right" style="width: 5%;" id="totalIGSTFooter">₹0.00</td>
                            <td class="text-right" style="width: 6%;" id="totalTaxFooter">₹0.00</td>
                            <td class="text-right" style="width: 7%;" id="totalFinalFooter">₹0.00</td>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div>

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

        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 = String(date.getFullYear()).substr(2);
            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 loadPrintReport() {
            const { startDate, endDate, supplierId, purchaseType } = PRINT_PARAMS;
            let apiUrl = `api/get-gst-purchases.php?startDate=${startDate}&endDate=${endDate}`;
            if (supplierId) {
                apiUrl += `&supplierId=${encodeURIComponent(supplierId)}`;
            }
            if (purchaseType) {
                apiUrl += `&purchaseType=${encodeURIComponent(purchaseType)}`;
            }

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

        function renderPrintReport(data) {
            const { summary, purchases, startDate, endDate, supplierInfo, purchaseTypeInfo } = data;

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

            const periodText = `${formatDate(startDate)} to ${formatDate(endDate)}`;
            document.getElementById('reportPeriod').textContent = periodText;
            
            if (supplierInfo) {
                const supplierLabel = `${supplierInfo.SupplierName}${supplierInfo.City ? ' - ' + supplierInfo.City : ''}`;
                document.getElementById('reportSupplier').textContent = supplierLabel;
            } else {
                document.getElementById('supplierDiv').style.display = 'none';
            }
            
            if (purchaseTypeInfo) {
                document.getElementById('reportPurchaseType').textContent = purchaseTypeInfo;
            } else {
                document.getElementById('purchaseTypeDiv').style.display = 'none';
            }
            
            document.getElementById('generatedDate').textContent = formatDateTime(new Date());

            document.getElementById('totalPurchases').textContent = formatCurrency(summary.totalPurchases);
            document.getElementById('taxableAmount').textContent = formatCurrency(summary.taxableAmount);
            document.getElementById('cgstAmount').textContent = formatCurrency(summary.cgstAmount);
            document.getElementById('sgstAmount').textContent = formatCurrency(summary.sgstAmount);
            document.getElementById('igstAmount').textContent = formatCurrency(summary.igstAmount);
            document.getElementById('totalTax').textContent = formatCurrency(summary.totalTax);

            renderPurchasesTable(purchases, summary);
        }

        function renderPurchasesTable(purchases, summary) {
            const tbody = document.getElementById('purchasesBody');

            document.getElementById('transactionCount').textContent = purchases.length;

            if (!purchases.length) {
                tbody.innerHTML = '<tr><td colspan="17" class="text-center" style="padding: 20px;">No purchases found for the selected period.</td></tr>';
            } else {
                let rows = '';
                let serialNo = 1;

                purchases.forEach(purchase => {
                    const isReturn = purchase.PurchaseType && purchase.PurchaseType.includes('RETURN');
                    const typeClass = purchase.PurchaseType === 'GST' ? 'badge-gst' : 
                                     purchase.PurchaseType === 'NON-GST' ? 'badge-non-gst' : 
                                     purchase.PurchaseType === 'ONLINE' ? 'badge-online' :
                                     isReturn ? 'badge-danger' : 'badge-gst';
                    
                    const taxTypeLabel = purchase.TaxType === 'INTER' ? 'Inter-State' : 'Intra-State';
                    const taxTypeClass = purchase.TaxType === 'INTER' ? 'badge-online' : 'badge-gst';
                    
                    const purchaseTypeDisplay = purchase.PurchaseTypeDescription || purchase.PurchaseType || '-';
                    
                    // For returns, show negative values
                    const multiplier = isReturn ? -1 : 1;
                    
                    rows += `
                        <tr ${isReturn ? 'style="background-color: #fff5f5;"' : ''}>
                            <td class="text-center">${serialNo++}</td>
                            <td>${formatDate(purchase.PurchaseDate)}</td>
                            <td>${purchase.InvoiceNumber}</td>
                            <td>${purchase.PurchaseInvoiceNumber || '-'}</td>
                            <td>${formatDate(purchase.PurchaseInvoiceDate)}</td>
                            <td>${purchase.SupplierName || 'Walk-in Supplier'}</td>
                            <td>${purchase.GSTNumber || '-'}</td>
                            <td><span class="badge ${taxTypeClass}">${taxTypeLabel}</span></td>
                            <td class="text-right" ${isReturn ? 'style="color: #991b1b;"' : ''}>${formatCurrency(purchase.TaxableAmount * multiplier)}</td>
                            <td class="text-right">${parseFloat(purchase.CGSTPercent || 0).toFixed(2)}%</td>
                            <td class="text-right" ${isReturn ? 'style="color: #991b1b;"' : ''}>${formatCurrency(purchase.CGSTAmount * multiplier)}</td>
                            <td class="text-right">${parseFloat(purchase.SGSTPercent || 0).toFixed(2)}%</td>
                            <td class="text-right" ${isReturn ? 'style="color: #991b1b;"' : ''}>${formatCurrency(purchase.SGSTAmount * multiplier)}</td>
                            <td class="text-right">${parseFloat(purchase.IGSTPercent || 0).toFixed(2)}%</td>
                            <td class="text-right" ${isReturn ? 'style="color: #991b1b;"' : ''}>${formatCurrency(purchase.IGSTAmount * multiplier)}</td>
                            <td class="text-right" ${isReturn ? 'style="color: #991b1b;"' : ''}>${formatCurrency(purchase.TotalTax * multiplier)}</td>
                            <td class="text-right amount-positive" ${isReturn ? 'style="color: #991b1b;"' : ''}>${formatCurrency(purchase.FinalAmount * multiplier)}</td>
                        </tr>
                    `;
                });

                tbody.innerHTML = rows;
            }

            document.getElementById('totalTaxableFooter').textContent = formatCurrency(summary.taxableAmount);
            document.getElementById('totalCGSTFooter').textContent = formatCurrency(summary.cgstAmount);
            document.getElementById('totalSGSTFooter').textContent = formatCurrency(summary.sgstAmount);
            document.getElementById('totalIGSTFooter').textContent = formatCurrency(summary.igstAmount);
            document.getElementById('totalTaxFooter').textContent = formatCurrency(summary.totalTax);
            document.getElementById('totalFinalFooter').textContent = formatCurrency(summary.totalPurchases);
        }

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