<?php
session_start();
include_once('../includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:../login.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']) : '';

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

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

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

        .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-title {
            font-size: 13px;
            font-weight: 700;
            color: var(--accent-color);
            margin-bottom: 4px;
            text-transform: uppercase;
        }

        .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: 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);
            margin-bottom: 4px;
        }

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

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

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

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

        .summary-card.debit .amount {
            color: var(--danger-color);
        }

        .summary-card.balance-positive {
            background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
            border-color: #86efac;
        }

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

        .summary-card.balance-negative {
            background: linear-gradient(135deg, #fff1f2 0%, #ffe4e6 100%);
            border-color: #fda4af;
        }

        .summary-card.balance-negative .amount {
            color: var(--danger-color);
        }

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

        thead th {
            padding: 5px 6px;
            text-align: left;
            font-size: 8px;
            font-weight: 700;
            text-transform: uppercase;
            background: var(--primary-color);
            color: white;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

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

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

        tbody tr.opening-balance {
            background: #f3f4f6;
            font-weight: 600;
        }

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

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

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

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

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

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

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

        .amount-negative {
            color: var(--danger-color);
            font-weight: 600;
        }

        .no-print {
            display: block;
        }

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

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

            .print-container {
                margin: 0;
                padding: 0;
                box-shadow: none;
            }

            .no-print {
                display: none !important;
            }
        }
    </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" style="text-align: center; padding: 40px;">
            ⏳ Loading report data...
        </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" style="text-align: right;">
                        <div class="report-title">Customer Ledger Report</div>
                        <div class="report-meta">
                            <div><strong>Period:</strong> <span id="reportPeriod">-</span></div>
                            <div><strong>Customer:</strong> <span id="reportCustomer">All Customers</span></div>
                            <div><strong>Generated:</strong> <span id="generatedDate">-</span></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="summary-grid">
                <div class="summary-card" id="openingCard">
                    <h3>Opening Balance</h3>
                    <div class="amount" id="openingBalance">₹0.00</div>
                </div>
                <div class="summary-card debit">
                    <h3>Total Sales</h3>
                    <div class="amount" id="totalDebitCard">₹0.00</div>
                </div>
                <div class="summary-card credit">
                    <h3>Total Payments</h3>
                    <div class="amount" id="totalCreditCard">₹0.00</div>
                </div>
                <div class="summary-card" id="closingCard">
                    <h3>Outstanding Balance</h3>
                    <div class="amount" id="closingBalance">₹0.00</div>
                </div>
            </div>

            <div style="font-size: 9px; color: var(--muted-text); margin-bottom: 6px; padding: 4px 0; border-bottom: 1px solid var(--border-color);">
                <strong>Transaction Count:</strong> <span id="transactionCount">0</span> entries
            </div>

            <table>
                <thead>
                    <tr>
                        <th style="width: 10%;">Date</th>
                        <th style="width: 15%;">Invoice No</th>
                        <th style="width: 18%;">Customer</th>
                        <th style="width: 12%;">Type</th>
                        <th style="width: 20%;">Notes</th>
                        <th style="width: 12%;" class="text-right">Debit (₹)</th>
                        <th style="width: 12%;" class="text-right">Credit (₹)</th>
                        <th style="width: 1%;"></th>
                    </tr>
                </thead>
                <tbody id="ledgerBody">
                    <tr><td colspan="8" style="text-align: center; padding: 20px;">No data</td></tr>
                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="5" class="text-right">PERIOD TOTALS:</td>
                        <td class="text-right amount-negative" id="totalDebit">₹0.00</td>
                        <td class="text-right amount-positive" id="totalCredit">₹0.00</td>
                        <td></td>
                    </tr>
                    <tr>
                        <td colspan="6" class="text-right">OUTSTANDING BALANCE:</td>
                        <td class="text-right" id="closingBalanceFooter">₹0.00</td>
                        <td></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>

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

        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, customerId } = PRINT_PARAMS;
            let apiUrl = `api/get-customer-ledger.php?startDate=${startDate}&endDate=${endDate}`;
            if (customerId) {
                apiUrl += `&customerId=${encodeURIComponent(customerId)}`;
            }

            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(() => {
                    alert('Unable to load report');
                });
        }

        function renderPrintReport(data) {
            const { summary, transactions, startDate, endDate, customerInfo } = 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;
            
            const customerLabel = customerInfo ? `${customerInfo.CustomerName}${customerInfo.Mobile ? ' - ' + customerInfo.Mobile : ''}` : 'All Customers';
            document.getElementById('reportCustomer').textContent = customerLabel;
            
            document.getElementById('generatedDate').textContent = formatDateTime(new Date());

            document.getElementById('openingBalance').textContent = formatCurrency(summary.openingBalance);
            document.getElementById('openingCard').className = `summary-card ${summary.openingBalance >= 0 ? 'balance-negative' : 'balance-positive'}`;

            document.getElementById('totalDebitCard').textContent = formatCurrency(summary.totalSales);
            document.getElementById('totalCreditCard').textContent = formatCurrency(summary.totalPayments);

            document.getElementById('closingBalance').textContent = formatCurrency(summary.closingBalance);
            document.getElementById('closingBalanceFooter').textContent = formatCurrency(summary.closingBalance);
            document.getElementById('closingCard').className = `summary-card ${summary.closingBalance >= 0 ? 'balance-negative' : 'balance-positive'}`;
            document.getElementById('closingBalanceFooter').className = `text-right ${summary.closingBalance >= 0 ? 'amount-negative' : 'amount-positive'}`;

            renderLedger(transactions, summary);
        }

        function renderLedger(transactions, summary) {
            const tbody = document.getElementById('ledgerBody');

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

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

                rows += `
                    <tr class="opening-balance">
                        <td colspan="5">OPENING BALANCE</td>
                        <td class="text-right">${summary.openingBalance >= 0 ? formatCurrency(summary.openingBalance) : '-'}</td>
                        <td class="text-right">${summary.openingBalance < 0 ? formatCurrency(Math.abs(summary.openingBalance)) : '-'}</td>
                        <td></td>
                    </tr>
                `;

                transactions.forEach(txn => {
                    const typeClass = txn.TransactionType === 'Sale' ? 'badge-sale' : 'badge-payment';
                    
                    rows += `
                        <tr>
                            <td>${formatDate(txn.TransactionDate)}</td>
                            <td>${txn.InvoiceNumber || '-'}</td>
                            <td>${txn.CustomerName || '-'}</td>
                            <td><span class="badge ${typeClass}">${txn.TransactionType}</span></td>
                            <td title="${txn.Notes || '-'}">${(txn.Notes || '-').substring(0, 40)}</td>
                            <td class="text-right ${txn.DebitAmount ? 'amount-negative' : ''}">${txn.DebitAmount ? formatCurrency(txn.DebitAmount) : '-'}</td>
                            <td class="text-right ${txn.CreditAmount ? 'amount-positive' : ''}">${txn.CreditAmount ? formatCurrency(txn.CreditAmount) : '-'}</td>
                            <td></td>
                        </tr>
                    `;
                });

                tbody.innerHTML = rows;
            }

            document.getElementById('totalDebit').textContent = formatCurrency(summary.totalSales);
            document.getElementById('totalCredit').textContent = formatCurrency(summary.totalPayments);
        }

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