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

// 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 | Master Cash Flow 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: 297mm;
            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;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
        }

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

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

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

        .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: 2px 0;
        }

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

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

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

        .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, #ecfdf5 0%, #d1fae5 100%);
            border-color: #10b981;
        }

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

        .summary-card.cash-in {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border-color: #16a34a;
        }

        .summary-card.cash-out {
            background: linear-gradient(135deg, #fef2f2 0%, #fee2e2 100%);
            border-color: #dc2626;
        }

        .summary-card.upi-in {
            background: linear-gradient(135deg, #faf5ff 0%, #f3e8ff 100%);
            border-color: #7c3aed;
        }

        .summary-card.upi-out {
            background: linear-gradient(135deg, #fffbeb 0%, #fef3c7 100%);
            border-color: #d97706;
        }

        .sub-details {
            font-size: 7px;
            color: var(--muted-text);
            margin-top: 4px;
            padding-top: 4px;
            border-top: 1px solid var(--border-color);
        }

        .sub-details div {
            display: flex;
            justify-content: space-between;
            margin-bottom: 2px;
        }

        .section-title {
            font-size: 10px;
            font-weight: 700;
            color: var(--accent-color);
            margin: 10px 0 6px 0;
            padding-bottom: 4px;
            border-bottom: 1px solid var(--border-color);
        }

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

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

        thead th {
            padding: 4px 3px;
            text-align: left;
            font-size: 7px;
            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: 3px;
            border-bottom: 1px solid #e5e7eb;
            vertical-align: top;
        }

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

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

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

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

        tfoot tr.net-total-row td {
            background: var(--primary-color);
            color: white;
            font-size: 10px;
            padding: 6px 3px;
        }

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

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

        .amount-positive {
            color: #059669;
            font-weight: 600;
        }

        .amount-negative {
            color: #dc2626;
            font-weight: 600;
        }

        .amount-upi {
            color: #7c3aed;
            font-weight: 600;
        }

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

        .badge-sales { background: #dcfce7; color: #166534; }
        .badge-sales-return { background: #fee2e2; color: #991b1b; }
        .badge-customer-payment { background: #dbeafe; color: #1e40af; }
        .badge-purchase { background: #fef3c7; color: #92400e; }
        .badge-purchase-return { background: #e0f2fe; color: #075985; }
        .badge-supplier-payment { background: #fef2f2; color: #991b1b; }
        .badge-expense { background: #fce7f3; color: #9f1239; }

        .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: 7px;
            }

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

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

            table {
                font-size: 6.5px;
            }

            thead th {
                font-size: 6px;
                padding: 2px;
            }

            tbody td {
                padding: 2px;
            }

            tfoot td {
                padding: 3px 2px;
                font-size: 7px;
            }

            tfoot tr.net-total-row td {
                font-size: 8px;
                padding: 4px 2px;
            }
        }
    </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 cash flow 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">
                <?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']) || !empty($storeSettings['City'])): ?>
                    <div class="company-details">
                        <?php echo htmlspecialchars($storeSettings['Address'] ?? ''); ?>
                        <?php if (!empty($storeSettings['City'])): ?>
                        <?php echo !empty($storeSettings['Address']) ? ', ' : ''; ?>
                        <?php echo htmlspecialchars($storeSettings['City']); ?>
                        <?php echo !empty($storeSettings['Postcode']) ? ' - ' . htmlspecialchars($storeSettings['Postcode']) : ''; ?>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($storeSettings['Mobile']) || !empty($storeSettings['GSTNumber'])): ?>
                    <div class="company-details">
                        <?php if (!empty($storeSettings['Mobile'])): ?>Ph: <?php echo htmlspecialchars($storeSettings['Mobile']); ?><?php endif; ?>
                        <?php if (!empty($storeSettings['GSTNumber'])): ?>
                        <?php echo !empty($storeSettings['Mobile']) ? ' | ' : ''; ?>GSTIN: <?php echo htmlspecialchars($storeSettings['GSTNumber']); ?>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>
                    <div class="report-title">Master Cash Flow Report</div>
                    <div class="report-meta">
                        <div><strong>Period:</strong> <span id="reportPeriod">-</span></div>
                        <div id="filterInfo" style="margin-top: 2px;"></div>
                        <div><strong>Generated:</strong> <span id="generatedDate">-</span></div>
                    </div>
                </div>
            </div>

            <div class="summary-grid">
                <div class="summary-card cash-in">
                    <h3>Total Cash In</h3>
                    <div class="amount" id="totalCashIn">₹0.00</div>
                    <div class="sub-details">
                        <div><span>Sales:</span> <span id="salesCash">₹0</span></div>
                        <div><span>Cust Pay:</span> <span id="customerPaymentsCash">₹0</span></div>
                    </div>
                </div>
                
                <div class="summary-card cash-out">
                    <h3>Total Cash Out</h3>
                    <div class="amount" id="totalCashOut">₹0.00</div>
                    <div class="sub-details">
                        <div><span>Purchase:</span> <span id="purchasesCash">₹0</span></div>
                        <div><span>Supp Pay:</span> <span id="supplierPaymentsCash">₹0</span></div>
                        <div><span>Expense:</span> <span id="expensesCash">₹0</span></div>
                    </div>
                </div>
                
                <div class="summary-card highlight">
                    <h3>Net Cash Flow</h3>
                    <div class="amount" id="netCashFlow">₹0.00</div>
                </div>
                
                <div class="summary-card upi-in">
                    <h3>Total UPI In</h3>
                    <div class="amount" id="totalUpiIn">₹0.00</div>
                    <div class="sub-details">
                        <div><span>Sales:</span> <span id="salesUpi">₹0</span></div>
                        <div><span>Cust Pay:</span> <span id="customerPaymentsUpi">₹0</span></div>
                    </div>
                </div>
                
                <div class="summary-card upi-out">
                    <h3>Total UPI Out</h3>
                    <div class="amount" id="totalUpiOut">₹0.00</div>
                    <div class="sub-details">
                        <div><span>Purchase:</span> <span id="purchasesUpi">₹0</span></div>
                        <div><span>Supp Pay:</span> <span id="supplierPaymentsUpi">₹0</span></div>
                        <div><span>Expense:</span> <span id="expensesUpi">₹0</span></div>
                    </div>
                </div>
                
                <div class="summary-card highlight">
                    <h3>Net UPI Flow</h3>
                    <div class="amount" id="netUpiFlow">₹0.00</div>
                </div>
                
                <div class="summary-card">
                    <h3>Total Transactions</h3>
                    <div class="amount" id="totalTransactions">0</div>
                </div>
                
                <div class="summary-card highlight">
                    <h3>Net Total Flow</h3>
                    <div class="amount" id="netTotalFlow">₹0.00</div>
                </div>
            </div>

            <div class="section-title">
                All Cash Flow Transactions <span id="transactionCount">(0)</span>
            </div>

            <table>
                <thead>
                    <tr>
                        <th style="width: 3%;">No</th>
                        <th style="width: 7%;">Date</th>
                        <th style="width: 10%;">Type</th>
                        <th style="width: 10%;">Reference</th>
                        <th style="width: 15%;">Party</th>
                        <th style="width: 20%;">Description</th>
                        <th style="width: 8%;" class="text-right">Cash In</th>
                        <th style="width: 8%;" class="text-right">Cash Out</th>
                        <th style="width: 8%;" class="text-right">UPI In</th>
                        <th style="width: 8%;" class="text-right">UPI Out</th>
                    </tr>
                </thead>
                <tbody id="transactionsBody">
                    <tr><td colspan="10" class="text-center" style="padding: 20px;">No data</td></tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="6" class="text-right"><strong>TOTALS:</strong></td>
                        <td class="text-right" id="totalCashInFooter">₹0.00</td>
                        <td class="text-right" id="totalCashOutFooter">₹0.00</td>
                        <td class="text-right" id="totalUpiInFooter">₹0.00</td>
                        <td class="text-right" id="totalUpiOutFooter">₹0.00</td>
                    </tr>
                    <tr class="net-total-row">
                        <td colspan="6" class="text-right"><strong>NET FLOW:</strong></td>
                        <td colspan="2" class="text-right" id="netCashFlowFooter">₹0.00</td>
                        <td colspan="2" class="text-right" id="netUpiFlowFooter">₹0.00</td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>

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

        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 getBadgeClass(type) {
            const badgeMap = {
                'SALES': 'badge-sales',
                'SALES-RETURN': 'badge-sales-return',
                'CUSTOMER-PAYMENT': 'badge-customer-payment',
                'PURCHASE': 'badge-purchase',
                'PURCHASE-RETURN': 'badge-purchase-return',
                'SUPPLIER-PAYMENT': 'badge-supplier-payment',
                'EXPENSE': 'badge-expense'
            };
            return badgeMap[type] || 'badge-sales';
        }

        function loadPrintReport() {
            const { startDate, endDate, transactionType, paymentMode } = PRINT_PARAMS;
            let apiUrl = `api/get-cash-flow-report.php?startDate=${startDate}&endDate=${endDate}`;
            if (transactionType) {
                apiUrl += `&transactionType=${encodeURIComponent(transactionType)}`;
            }
            if (paymentMode) {
                apiUrl += `&paymentMode=${encodeURIComponent(paymentMode)}`;
            }

            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, transactions, startDate, endDate } = 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;
            
            // Filter info
            let filterInfo = '';
            if (PRINT_PARAMS.transactionType) {
                filterInfo += `<strong>Type:</strong> ${PRINT_PARAMS.transactionType.replace('-', ' ')} `;
            }
            if (PRINT_PARAMS.paymentMode) {
                filterInfo += `<strong>Mode:</strong> ${PRINT_PARAMS.paymentMode}`;
            }
            if (filterInfo) {
                document.getElementById('filterInfo').innerHTML = filterInfo;
            }
            
            document.getElementById('generatedDate').textContent = formatDateTime(new Date());

            // Update summary
            document.getElementById('totalCashIn').textContent = formatCurrency(summary.totalCashIn);
            document.getElementById('totalCashOut').textContent = formatCurrency(summary.totalCashOut);
            document.getElementById('netCashFlow').textContent = formatCurrency(summary.netCashFlow);
            document.getElementById('totalUpiIn').textContent = formatCurrency(summary.totalUpiIn);
            document.getElementById('totalUpiOut').textContent = formatCurrency(summary.totalUpiOut);
            document.getElementById('netUpiFlow').textContent = formatCurrency(summary.netUpiFlow);
            document.getElementById('totalTransactions').textContent = summary.totalTransactions;
            document.getElementById('netTotalFlow').textContent = formatCurrency(summary.netTotalFlow);

            document.getElementById('salesCash').textContent = formatCurrency(summary.salesCash);
            document.getElementById('salesUpi').textContent = formatCurrency(summary.salesUpi);
            document.getElementById('customerPaymentsCash').textContent = formatCurrency(summary.customerPaymentsCash);
            document.getElementById('customerPaymentsUpi').textContent = formatCurrency(summary.customerPaymentsUpi);
            document.getElementById('purchasesCash').textContent = formatCurrency(summary.purchasesCash);
            document.getElementById('purchasesUpi').textContent = formatCurrency(summary.purchasesUpi);
            document.getElementById('supplierPaymentsCash').textContent = formatCurrency(summary.supplierPaymentsCash);
            document.getElementById('supplierPaymentsUpi').textContent = formatCurrency(summary.supplierPaymentsUpi);
            document.getElementById('expensesCash').textContent = formatCurrency(summary.expensesCash);
            document.getElementById('expensesUpi').textContent = formatCurrency(summary.expensesUpi);

            renderTransactionsTable(transactions, summary);
        }

        function renderTransactionsTable(transactions, summary) {
            const tbody = document.getElementById('transactionsBody');
            document.getElementById('transactionCount').textContent = `(${transactions.length})`;

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

                transactions.forEach(txn => {
                    const badgeClass = getBadgeClass(txn.TransactionType);
                    
                    rows += `
                        <tr>
                            <td class="text-center">${serialNo++}</td>
                            <td>${formatDate(txn.TransactionDate)}</td>
                            <td><span class="transaction-badge ${badgeClass}">${txn.TransactionType.replace('-', ' ')}</span></td>
                            <td>${txn.Reference || '-'}</td>
                            <td><strong>${txn.Party}</strong></td>
                            <td>${txn.Description || '-'}</td>
                            <td class="text-right ${txn.CashIn > 0 ? 'amount-positive' : ''}">${txn.CashIn > 0 ? formatCurrency(txn.CashIn) : '-'}</td>
                            <td class="text-right ${txn.CashOut > 0 ? 'amount-negative' : ''}">${txn.CashOut > 0 ? formatCurrency(txn.CashOut) : '-'}</td>
                            <td class="text-right ${txn.UpiIn > 0 ? 'amount-upi' : ''}">${txn.UpiIn > 0 ? formatCurrency(txn.UpiIn) : '-'}</td>
                            <td class="text-right ${txn.UpiOut > 0 ? 'amount-upi' : ''}">${txn.UpiOut > 0 ? formatCurrency(txn.UpiOut) : '-'}</td>
                        </tr>
                    `;
                });

                tbody.innerHTML = rows;
            }

            document.getElementById('totalCashInFooter').textContent = formatCurrency(summary.totalCashIn);
            document.getElementById('totalCashOutFooter').textContent = formatCurrency(summary.totalCashOut);
            document.getElementById('totalUpiInFooter').textContent = formatCurrency(summary.totalUpiIn);
            document.getElementById('totalUpiOutFooter').textContent = formatCurrency(summary.totalUpiOut);
            document.getElementById('netCashFlowFooter').textContent = formatCurrency(summary.netCashFlow);
            document.getElementById('netUpiFlowFooter').textContent = formatCurrency(summary.netUpiFlow);
        }

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