<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once("connectioni.php");

// Assign the global mysqli connection to the $conn variable
$conn = $GLOBALS['dbinv'];

// Initialize variables
$dateFrom = $_POST['df'] ?? date('Y-m-01');
$dateTo   = $_POST['dto'] ?? date('Y-m-d');
$activeReport = $_POST['action'] ?? null;
$reportData = null;
$error = null;
$lastReportType = $_POST['last_report_type'] ?? null;


// Helper: format currency
function formatCurrency($amount) {
    return '   ' . number_format((float)$amount, 2);
}

// Process report requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $activeReport && $conn && !$error) {
    // 1. Secure the date inputs to prevent SQL injection
    $safe_dateFrom = $conn->real_escape_string($_POST['df']);
    $safe_dateTo   = $conn->real_escape_string($_POST['dto']);
    
    // We still want to keep original values for the HTML form inputs
    $dateFrom = $_POST['df'];
    $dateTo   = $_POST['dto'];
    
    if (empty($safe_dateFrom) || empty($safe_dateTo)) {
        $error = "Please select both From Date and To Date.";
    } else {
        if ($activeReport === 'date_wise') {
            // Date Wise Report
            $sql = "SELECT c_bal.refno, c_bal.sdate, vendor.NAME as vendor_name, 
                           c_bal.CUSCODE, c_bal.amount, c_bal.dep, c_bal.dev, c_bal.company
                    FROM c_bal 
                    INNER JOIN vendor ON c_bal.CUSCODE = vendor.CODE 
                    WHERE c_bal.trn_type = 'ARN' AND c_bal.cancell = '0' 
                      AND c_bal.sdate BETWEEN '$safe_dateFrom' AND '$safe_dateTo' 
                    ORDER BY c_bal.sdate";
            
            $result = $conn->query($sql);
            
            if ($result) {
                $reportData = [];
                $grandTotal = 0;
                while ($row = $result->fetch_assoc()) {
                    $reportData[] = $row;
                    $grandTotal += (float)$row['amount'];
                }
            } else {
                $error = "Date Wise query error: " . $conn->error;
            }
        } 
        elseif ($activeReport === 'supplier_wise') {
            // Supplier Wise Report
            $sql = "SELECT c_bal.refno, c_bal.sdate, vendor.NAME as vendor_name, 
                           c_bal.CUSCODE, c_bal.amount, c_bal.dep, c_bal.dev, c_bal.company
                    FROM c_bal 
                    INNER JOIN vendor ON c_bal.CUSCODE = vendor.CODE 
                    WHERE c_bal.trn_type = 'ARN' AND c_bal.cancell = '0' 
                      AND c_bal.sdate BETWEEN '$safe_dateFrom' AND '$safe_dateTo' 
                    ORDER BY c_bal.CUSCODE, c_bal.sdate";
                    
            $result = $conn->query($sql);
            
            if ($result) {
                $rows = [];
                while ($row = $result->fetch_assoc()) {
                    $rows[] = $row;
                }
                $reportData = $rows;
                $grandTotal = array_sum(array_column($rows, 'amount'));
            } else {
                $error = "Supplier Wise query error: " . $conn->error;
            }
        }
        elseif ($activeReport === 'summary') {
            // Summary Report
            $sql = "SELECT c_bal.CUSCODE, vendor.NAME as vendor_name, 
                           SUM(c_bal.amount) as total_amount,
                           COUNT(c_bal.refno) as transaction_count
                    FROM c_bal 
                    INNER JOIN vendor ON c_bal.CUSCODE = vendor.CODE 
                    WHERE c_bal.trn_type = 'ARN' AND c_bal.cancell = '0' 
                      AND c_bal.sdate BETWEEN '$safe_dateFrom' AND '$safe_dateTo' 
                    GROUP BY c_bal.CUSCODE, vendor.NAME
                    ORDER BY vendor_name";
                    
            $result = $conn->query($sql);
            
            if ($result) {
                $reportData = [];
                $grandTotal = 0;
                while ($row = $result->fetch_assoc()) {
                    $reportData[] = $row;
                    $grandTotal += (float)$row['total_amount'];
                }
            } else {
                $error = "Summary query error: " . $conn->error;
            }
        }
    }
}

// Remember last report type for View button functionality
$lastReportType = $activeReport ?: $lastReportType;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>Purchase Report | Date Wise | Supplier Wise | Summary</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            background: linear-gradient(145deg, #d4dee8 0%, #c2cedc 100%);
            font-family: 'Segoe UI', 'Roboto', system-ui, -apple-system, sans-serif;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        /* Main container - thin frame, light glass */
        .report-container {
            max-width: 1600px;
            width: 100%;
            background: rgba(248, 250, 252, 0.94);
            backdrop-filter: blur(0);
            border-radius: 28px;
            box-shadow: 0 20px 35px -12px rgba(0, 0, 0, 0.12), inset 0 1px 0 rgba(255,255,255,0.8);
            border: 1px solid rgba(156, 180, 194, 0.6);
            overflow: hidden;
            transition: all 0.2s;
        }

        /* Top action bar - overl shape buttons */
        .action-bar {
            background: #eaf1f7;
            padding: 14px 28px;
            border-bottom: 1px solid #cbdbe2;
            display: flex;
            gap: 18px;
            flex-wrap: wrap;
            box-shadow: 0 1px 2px rgba(0,0,0,0.02);
        }

        .shape-btn {
            background: #f5f9fe;
            border: none;
            padding: 9px 26px;
            font-size: 1rem;
            font-weight: 600;
            border-radius: 50px;
            color: #1e4a6b;
            cursor: pointer;
            transition: 0.2s;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05), inset 0 1px 0 white;
            border: 1px solid #caddf0;
        }

        .shape-btn:hover {
            background: #ffffff;
            transform: translateY(-2px);
            box-shadow: 0 8px 18px rgba(0, 32, 64, 0.12);
            border-color: #9bb6cc;
        }

        /* Filter panel */
        .filter-panel {
            padding: 22px 28px 20px 28px;
            background: #f9fbfd;
            border-bottom: 1px solid #e2e8f0;
        }

        .date-group {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            align-items: flex-end;
            margin-bottom: 22px;
            background: #ffffffd9;
            padding: 12px 20px;
            border-radius: 48px;
            box-shadow: inset 0 0 0 1px #eef2f6, 0 2px 5px rgba(0,0,0,0.02);
        }

        .date-field {
            display: flex;
            flex-direction: column;
            gap: 6px;
        }

        .date-field label {
            font-size: 0.75rem;
            font-weight: 700;
            color: #2c5a7a;
            letter-spacing: 0.5px;
            margin-left: 6px;
        }

        .date-field input {
            border: 1px solid #cbdde9;
            padding: 10px 14px;
            border-radius: 40px;
            font-size: 0.9rem;
            background: white;
            width: 190px;
            font-family: monospace;
        }

        .date-field input:focus {
            border-color: #5f9bc2;
            outline: none;
            box-shadow: 0 0 0 3px rgba(79, 141, 191, 0.2);
        }

        .report-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
            margin-top: 6px;
        }

        .primary-btn {
            background: #eef3fc;
            border: 1px solid #b9cee4;
            padding: 10px 28px;
            border-radius: 44px;
            font-weight: 700;
            font-size: 0.85rem;
            color: #1f6392;
            cursor: pointer;
            transition: 0.2s;
        }

        .primary-btn:hover {
            background: #ffffff;
            border-color: #7fa3c2;
            color: #0a4468;
            transform: scale(0.98);
        }

        /* Data area - scrollable grid */
        .data-area {
            padding: 20px 28px 32px 28px;
            background: #ffffffcc;
            max-height: 65vh;
            overflow-x: auto;
            overflow-y: auto;
            border-top: 1px solid #e2edf5;
        }

        .report-title {
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 20px;
            color: #1f4e6e;
            border-left: 5px solid #4f8db2;
            padding-left: 15px;
            background: linear-gradient(90deg, #eef4fa, transparent);
        }

        .report-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.85rem;
            border-radius: 18px;
            overflow: hidden;
            box-shadow: 0 1px 2px rgba(0,0,0,0.03);
        }

        .report-table th {
            background: #e4edf5;
            color: #1c4e70;
            padding: 12px 8px;
            font-weight: 700;
            border-bottom: 2px solid #cbdde9;
            text-align: center;
        }

        .report-table td {
            padding: 10px 6px;
            border-bottom: 1px solid #e2edf2;
            text-align: center;
            background-color: #fffffffa;
            color: #1f2e3c;
        }

        .report-table tr:hover td {
            background-color: #f1f7fd;
        }

        .subtotal-row td {
            background-color: #e9f0f7 !important;
            font-weight: 700;
            border-top: 1px solid #c5d8ea;
            border-bottom: 1px solid #c5d8ea;
        }

        .grand-total-row td {
            background: #eef3fa;
            font-weight: 800;
            border-top: 2px solid #bdd4e8;
        }

        .empty-msg {
            text-align: center;
            padding: 48px 20px;
            color: #6f8eaa;
            background: #f8fbfe;
            border-radius: 24px;
        }

        .error-msg {
            background: #ffe6e5;
            border-left: 6px solid #dc3545;
            color: #a12a32;
            padding: 16px;
            border-radius: 20px;
            margin-bottom: 18px;
        }

        footer {
            font-size: 0.7rem;
            text-align: center;
            padding: 14px;
            border-top: 1px solid #dee9f0;
            background: #f4f9fe;
            color: #66809a;
        }

        /* Print styles */
        @media print {
            body {
                background: white;
                padding: 0;
                margin: 0;
            }
            .action-bar, .filter-panel, footer, .primary-btn, .shape-btn, .report-buttons, .date-group {
                display: none !important;
            }
            .data-area {
                padding: 0;
                overflow: visible;
                max-height: none;
            }
            .report-container {
                box-shadow: none;
                border: none;
                background: white;
            }
            .report-table th {
                background: #eef2f5;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
        }
    </style>
</head>
<body>
<div class="report-container">
    <!-- Top overl shape buttons -->
    <div class="action-bar">
        <button class="shape-btn" id="viewBtn">👁️ View</button>
        <button class="shape-btn" id="printBtn">🖨️ Print</button>
        <button class="shape-btn" id="exitBtn">✖ Exit</button>
    </div>

    <!-- Filter form -->
    <div class="filter-panel">
        <form method="POST" id="reportForm">
            <div class="date-group">
                <div class="date-field">
                    <label>📅 From Date (df)</label>
                    <input type="date" name="df" value="<?= htmlspecialchars($dateFrom) ?>" required>
                </div>
                <div class="date-field">
                    <label>📅 To Date (dto)</label>
                    <input type="date" name="dto" value="<?= htmlspecialchars($dateTo) ?>" required>
                </div>
            </div>
            <div class="report-buttons">
                <button type="submit" name="action" value="date_wise" class="primary-btn">📋 Date Wise Report</button>
                <button type="submit" name="action" value="supplier_wise" class="primary-btn">🏢 Supplier Wise Report</button>
                <button type="submit" name="action" value="summary" class="primary-btn">📊 Summary</button>
            </div>
            <input type="hidden" name="last_report_type" id="lastReportType" value="<?= htmlspecialchars($lastReportType ?? '') ?>">
        </form>
    </div>

    <!-- Report Display Area -->
    <div class="data-area" id="printableArea">
        <?php if ($error): ?>
            <div class="error-msg">⚠️ <?= htmlspecialchars($error) ?></div>
        <?php elseif ($activeReport && isset($reportData)): ?>
            <?php if ($activeReport === 'date_wise'): ?>
                <div class="report-title">📄 DATE WISE PURCHASE REPORT (<?= htmlspecialchars($dateFrom) ?> → <?= htmlspecialchars($dateTo) ?>)</div>
                <?php if (empty($reportData)): ?>
                    <div class="empty-msg">No records found for the selected date range.</div>
                <?php else: ?>
                    <table class="report-table">
                        <thead>
                            <tr><th>Ref No</th><th>Date</th><th>Supplier Name</th><th>CUSCODE</th><th>Amount</th><th>Dep</th><th>Dev</th><th>Company</th></tr>
                        </thead>
                        <tbody>
                            <?php $total = 0; foreach ($reportData as $row): $total += $row['amount']; ?>
                            <tr>
                                <td><?= htmlspecialchars($row['refno']) ?></td>
                                <td><?= htmlspecialchars(date('d-m-Y', strtotime($row['sdate']))) ?></td>
                                <td><?= htmlspecialchars($row['vendor_name']) ?></td>
                                <td><?= htmlspecialchars($row['CUSCODE']) ?></td>
                                <td style="text-align:right"><?= formatCurrency($row['amount']) ?></td>
                                <td><?= htmlspecialchars($row['dep'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($row['dev'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($row['company'] ?? '-') ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr class="grand-total-row">
                                <td colspan="4" style="text-align:right; font-weight:800;">GRAND TOTAL →</td>
                                <td style="text-align:right; font-weight:800;"><?= formatCurrency($total) ?></td>
                                <td colspan="3"></td>
                            </tr>
                        </tfoot>
                    </table>
                    <div style="margin-top:12px; text-align:right; color:#496e8a;">Records: <?= count($reportData) ?> | Total: <?= formatCurrency($total) ?></div>
                <?php endif; ?>

            <?php elseif ($activeReport === 'supplier_wise'): ?>
                <div class="report-title">🏭 SUPPLIER WISE TRANSACTIONS (<?= htmlspecialchars($dateFrom) ?> → <?= htmlspecialchars($dateTo) ?>)</div>
                <?php if (empty($reportData)): ?>
                    <div class="empty-msg">No transactions found.</div>
                <?php else: ?>
                    <table class="report-table">
                        <thead>
                            <tr><th>Ref No</th><th>Date</th><th>Supplier Name</th><th>CUSCODE</th><th>Amount</th><th>Dep</th><th>Dev</th><th>Company</th></tr>
                        </thead>
                        <tbody>
                            <?php
                            $currentSupplier = null;
                            $supplierSubtotal = 0;
                            $grandTotalSupplier = 0;
                            foreach ($reportData as $row):
                                $supplierKey = $row['CUSCODE'];
                                if ($currentSupplier !== $supplierKey) {
                                    // Show subtotal for previous supplier
                                    if ($currentSupplier !== null) {
                                        echo '<tr class="subtotal-row">';
                                        echo '<td colspan="4" style="text-align:right; font-weight:700;">Subtotal (' . htmlspecialchars($currentSupplierName) . ')</td>';
                                        echo '<td style="text-align:right; font-weight:700;">' . formatCurrency($supplierSubtotal) . '</td>';
                                        echo '<td colspan="3"></td></tr>';
                                        $grandTotalSupplier += $supplierSubtotal;
                                    }
                                    // Reset for new supplier
                                    $currentSupplier = $supplierKey;
                                    $currentSupplierName = $row['vendor_name'];
                                    $supplierSubtotal = 0;
                                }
                                $supplierSubtotal += $row['amount'];
                            ?>
                            <tr>
                                <td><?= htmlspecialchars($row['refno']) ?></td>
                                <td><?= htmlspecialchars(date('d-m-Y', strtotime($row['sdate']))) ?></td>
                                <td><?= htmlspecialchars($row['vendor_name']) ?></td>
                                <td><?= htmlspecialchars($row['CUSCODE']) ?></td>
                                <td style="text-align:right"><?= formatCurrency($row['amount']) ?></td>
                                <td><?= htmlspecialchars($row['dep'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($row['dev'] ?? '-') ?></td>
                                <td><?= htmlspecialchars($row['company'] ?? '-') ?></td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if ($currentSupplier !== null): ?>
                                <tr class="subtotal-row">
                                    <td colspan="4" style="text-align:right; font-weight:700;">Subtotal (<?= htmlspecialchars($currentSupplierName) ?>)</td>
                                    <td style="text-align:right; font-weight:700;"><?= formatCurrency($supplierSubtotal) ?></td>
                                    <td colspan="3"></td>
                                </tr>
                                <?php $grandTotalSupplier += $supplierSubtotal; ?>
                            <?php endif; ?>
                        </tbody>
                        <tfoot>
                            <tr class="grand-total-row">
                                <td colspan="4" style="text-align:right; font-weight:800;">GRAND TOTAL</td>
                                <td style="text-align:right; font-weight:800;"><?= formatCurrency($grandTotalSupplier) ?></td>
                                <td colspan="3"></td>
                            </tr>
                        </tfoot>
                    </table>
                <?php endif; ?>

            <?php elseif ($activeReport === 'summary'): ?>
                <div class="report-title">📊 SUMMARY REPORT – SUPPLIER WISE TOTALS (<?= htmlspecialchars($dateFrom) ?> → <?= htmlspecialchars($dateTo) ?>)</div>
                <?php if (empty($reportData)): ?>
                    <div class="empty-msg">No data available for summary.</div>
                <?php else: ?>
                    <table class="report-table">
                        <thead>
                            <tr><th>CUSCODE</th><th>Supplier Name</th><th>Total Amount</th><th>Transactions</th></tr>
                        </thead>
                        <tbody>
                            <?php $summaryTotal = 0; foreach ($reportData as $row): $summaryTotal += $row['total_amount']; ?>
                            <tr>
                                <td><?= htmlspecialchars($row['CUSCODE']) ?></td>
                                <td style="text-align:left"><?= htmlspecialchars($row['vendor_name']) ?></td>
                                <td style="text-align:right; font-weight:600;"><?= formatCurrency($row['total_amount']) ?></td>
                                <td><?= (int)$row['transaction_count'] ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                        <tfoot>
                            <tr class="grand-total-row">
                                <td colspan="2" style="text-align:right; font-weight:800;">GRAND TOTAL →</td>
                                <td style="text-align:right; font-weight:800;"><?= formatCurrency($summaryTotal) ?></td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                <?php endif; ?>
            <?php endif; ?>
        <?php else: ?>
            <div class="empty-msg">
                ✨ Select date range and click one of the reports above ✨<br>
                <span style="font-size:0.85rem;">Date Wise | Supplier Wise (with subtotals) | Summary (grouped totals)</span>
            </div>
        <?php endif; ?>
    </div>
    <footer>
        Purchase Report Engine | c_bal (trn_type='ARN', cancell='0') | Vendor Master
    </footer>
</div>

<script>
    (function() {
        const viewBtn = document.getElementById('viewBtn');
        const printBtn = document.getElementById('printBtn');
        const exitBtn = document.getElementById('exitBtn');
        const reportForm = document.getElementById('reportForm');
        const lastReportHidden = document.getElementById('lastReportType');
        
        // View button: resubmit last report type
        viewBtn.addEventListener('click', function(e) {
            e.preventDefault();
            const lastType = lastReportHidden ? lastReportHidden.value : '';
            if (!lastType) {
                alert('No previous report to refresh. Generate a report first.');
                return;
            }
            // Create hidden input for action
            const actionInput = document.createElement('input');
            actionInput.type = 'hidden';
            actionInput.name = 'action';
            actionInput.value = lastType;
            reportForm.appendChild(actionInput);
            reportForm.submit();
        });
        
        // Print button: print the visible report area
        printBtn.addEventListener('click', function() {
            window.print();
        });
        
        // Exit button: reset to clean state (clear report, reset dates)
        exitBtn.addEventListener('click', function(e) {
            if (confirm('Reset the report view? All unsaved data will be cleared.')) {
                const today = new Date();
                const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
                const yyyy = today.getFullYear();
                const mm = String(today.getMonth() + 1).padStart(2, '0');
                const dd = String(today.getDate()).padStart(2, '0');
                const yyyyFirst = firstDay.getFullYear();
                const mmFirst = String(firstDay.getMonth() + 1).padStart(2, '0');
                const ddFirst = String(firstDay.getDate()).padStart(2, '0');
                const defaultFrom = `${yyyyFirst}-${mmFirst}-${ddFirst}`;
                const defaultTo = `${yyyy}-${mm}-${dd}`;
                window.location.href = window.location.pathname + `?reset=1&df=${defaultFrom}&dto=${defaultTo}`;
            }
        });
        
        // Handle URL reset parameter
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('reset') === '1') {
            const newFrom = urlParams.get('df') || document.querySelector('input[name="df"]').value;
            const newTo = urlParams.get('dto') || document.querySelector('input[name="dto"]').value;
            const dfInput = document.querySelector('input[name="df"]');
            const dtoInput = document.querySelector('input[name="dto"]');
            if (dfInput) dfInput.value = newFrom;
            if (dtoInput) dtoInput.value = newTo;
            history.replaceState(null, '', window.location.pathname);
        }
        
        // Ensure form validation before submit
        const submitBtns = document.querySelectorAll('button[type="submit"]');
        submitBtns.forEach(btn => {
            btn.addEventListener('click', function(e) {
                const df = document.querySelector('input[name="df"]').value;
                const dto = document.querySelector('input[name="dto"]').value;
                if (!df || !dto) {
                    e.preventDefault();
                    alert('Please select both From Date and To Date.');
                }
            });
        });
    })();
</script>
</body>
</html>
<?php
if (isset($conn) && $conn) {
    $conn->close();
}
?>