<?php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ACCOUNTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: index.php');
    exit();
}

$page_title = "Payment Reconciliation";

// Fetch unreconciled invoices
$invoices_query = "SELECT i.invoice_id, i.invoice_number, i.total_amount, i.amount_paid, i.balance,
                   u.full_name as patient_name, p.patient_number
                   FROM invoices i
                   JOIN patients p ON i.patient_id = p.patient_id
                   JOIN users u ON p.user_id = u.user_id
                   WHERE i.balance > 0 AND i.status != 'CANCELLED'
                   ORDER BY i.invoice_date DESC";
$invoices_result = mysqli_query($conn, $invoices_query);

// Fetch unallocated payments
$payments_query = "SELECT p.payment_id, p.payment_number, p.amount, p.payment_date, p.payment_method,
                   u.full_name as patient_name, pat.patient_number, i.invoice_number
                   FROM payments p
                   JOIN patients pat ON p.patient_id = pat.patient_id
                   JOIN users u ON pat.user_id = u.user_id
                   JOIN invoices i ON p.invoice_id = i.invoice_id
                   WHERE p.status = 'COMPLETED'
                   ORDER BY p.payment_date DESC
                   LIMIT 50";
$payments_result = mysqli_query($conn, $payments_query);

// Get reconciliation summary
$summary_query = "SELECT 
                  COUNT(DISTINCT i.invoice_id) as invoices_with_balance,
                  SUM(i.balance) as total_unreconciled,
                  COUNT(DISTINCT p.payment_id) as recent_payments,
                  SUM(p.amount) as recent_payment_amount
                  FROM invoices i
                  LEFT JOIN payments p ON p.invoice_id = i.invoice_id 
                      AND DATE(p.payment_date) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
                  WHERE i.balance > 0 AND i.status != 'CANCELLED'";
$summary_result = mysqli_query($conn, $summary_query);
$summary = mysqli_fetch_assoc($summary_result);

?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .stat-card, .chart-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.15);
            transition: all 0.2s;
        }
        
        .stat-icon {
            width: 48px;
            height: 48px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            margin-bottom: 1rem;
        }
        
        .stat-value {
            font-size: 1.875rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            font-weight: 500;
        }
        
        .reconcile-item {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 0.75rem;
            transition: all 0.2s;
        }
        
        .reconcile-item:hover {
            border-color: #6366f1;
            background: #f8fafc;
        }
        
        .reconcile-item.selected {
            border-color: #6366f1;
            background: #eef2ff;
        }
        
        .match-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 0.5rem;
        }
        
        .match-indicator.matched { background: #059669; }
        .match-indicator.partial { background: #f59e0b; }
        .match-indicator.unmatched { background: #dc2626; }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><?php echo $page_title; ?></h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="financial_dashboard.php">Financial</a></li>
                                        <li class="breadcrumb-item active">Reconciliation</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="ri-file-list-check-line me-2"></i>Payment Reconciliation</h4>
                                <p class="mb-0">Match payments to invoices and resolve discrepancies</p>
                            </div>
                            <div class="d-flex gap-2">
                                <button type="button" class="btn btn-light" id="autoReconcile">
                                    <i class="ri-magic-line me-1"></i> Auto Reconcile
                                </button>
                                <button type="button" class="btn btn-light" id="generateReport">
                                    <i class="ri-file-text-line me-1"></i> Report
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Summary Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon" style="background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white;">
                                    <i class="ri-file-warning-line"></i>
                                </div>
                                <div class="stat-value"><?php echo number_format($summary['invoices_with_balance'] ?? 0); ?></div>
                                <div class="stat-label">Invoices with Balance</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon" style="background: linear-gradient(135deg, #dc2626 0%, #991b1b 100%); color: white;">
                                    <i class="ri-money-dollar-circle-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['total_unreconciled'] ?? 0, 2); ?></div>
                                <div class="stat-label">Unreconciled Amount</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon" style="background: linear-gradient(135deg, #059669 0%, #047857 100%); color: white;">
                                    <i class="ri-exchange-line"></i>
                                </div>
                                <div class="stat-value"><?php echo number_format($summary['recent_payments'] ?? 0); ?></div>
                                <div class="stat-label">Recent Payments (7 Days)</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon" style="background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); color: white;">
                                    <i class="ri-check-double-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['recent_payment_amount'] ?? 0, 2); ?></div>
                                <div class="stat-label">Recent Payment Amount</div>
                            </div>
                        </div>
                    </div>

                    <!-- Reconciliation Interface -->
                    <div class="row">
                        <!-- Left: Invoices with Balance -->
                        <div class="col-lg-6">
                            <div class="chart-card">
                                <h5 class="mb-3"><i class="ri-file-list-line me-2"></i>Invoices with Outstanding Balance</h5>
                                <div style="max-height: 600px; overflow-y: auto;" id="invoicesList">
                                    <?php if (mysqli_num_rows($invoices_result) > 0): ?>
                                        <?php while ($invoice = mysqli_fetch_assoc($invoices_result)): 
                                            $match_class = '';
                                            if ($invoice['balance'] == 0) {
                                                $match_class = 'matched';
                                            } elseif ($invoice['amount_paid'] > 0) {
                                                $match_class = 'partial';
                                            } else {
                                                $match_class = 'unmatched';
                                            }
                                        ?>
                                        <div class="reconcile-item invoice-item" data-invoice-id="<?php echo $invoice['invoice_id']; ?>"
                                             data-balance="<?php echo $invoice['balance']; ?>">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div class="flex-grow-1">
                                                    <div class="d-flex align-items-center mb-2">
                                                        <span class="match-indicator <?php echo $match_class; ?>"></span>
                                                        <strong class="text-primary"><?php echo htmlspecialchars($invoice['invoice_number']); ?></strong>
                                                    </div>
                                                    <div class="mb-1"><?php echo htmlspecialchars($invoice['patient_name']); ?></div>
                                                    <small class="text-muted"><?php echo htmlspecialchars($invoice['patient_number']); ?></small>
                                                </div>
                                                <div class="text-end">
                                                    <div class="fw-medium">Total: KES <?php echo number_format($invoice['total_amount'], 2); ?></div>
                                                    <div class="text-success">Paid: KES <?php echo number_format($invoice['amount_paid'], 2); ?></div>
                                                    <div class="text-danger fw-bold">Balance: KES <?php echo number_format($invoice['balance'], 2); ?></div>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <div class="text-center py-5">
                                            <i class="ri-checkbox-circle-line text-success" style="font-size: 3rem;"></i>
                                            <p class="mt-2 text-muted">All invoices are fully reconciled!</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Right: Recent Payments -->
                        <div class="col-lg-6">
                            <div class="chart-card">
                                <h5 class="mb-3"><i class="ri-money-dollar-circle-line me-2"></i>Recent Payments</h5>
                                <div style="max-height: 600px; overflow-y: auto;" id="paymentsList">
                                    <?php if (mysqli_num_rows($payments_result) > 0): ?>
                                        <?php while ($payment = mysqli_fetch_assoc($payments_result)): ?>
                                        <div class="reconcile-item payment-item" data-payment-id="<?php echo $payment['payment_id']; ?>"
                                             data-amount="<?php echo $payment['amount']; ?>">
                                            <div class="d-flex justify-content-between align-items-start">
                                                <div class="flex-grow-1">
                                                    <div class="mb-2">
                                                        <strong class="text-success"><?php echo htmlspecialchars($payment['payment_number']); ?></strong>
                                                        <span class="badge bg-info ms-2"><?php echo str_replace('_', ' ', $payment['payment_method']); ?></span>
                                                    </div>
                                                    <div class="mb-1"><?php echo htmlspecialchars($payment['patient_name']); ?></div>
                                                    <small class="text-muted">
                                                        Invoice: <?php echo htmlspecialchars($payment['invoice_number']); ?> | 
                                                        <?php echo date('d M Y', strtotime($payment['payment_date'])); ?>
                                                    </small>
                                                </div>
                                                <div class="text-end">
                                                    <div class="fw-bold text-success">KES <?php echo number_format($payment['amount'], 2); ?></div>
                                                    <button type="button" class="btn btn-sm btn-outline-primary mt-2 view-payment-details"
                                                            data-payment-id="<?php echo $payment['payment_id']; ?>">
                                                        <i class="ri-eye-line me-1"></i> View
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <div class="text-center py-5">
                                            <i class="ri-money-dollar-circle-line text-muted" style="font-size: 3rem;"></i>
                                            <p class="mt-2 text-muted">No recent payments</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Discrepancy Resolution -->
                    <div class="chart-card">
                        <h5 class="mb-3"><i class="ri-alert-line me-2"></i>Discrepancy Resolution</h5>
                        <div class="alert alert-info">
                            <h6 class="alert-heading"><i class="ri-information-line me-2"></i>How to Reconcile:</h6>
                            <ul class="mb-0">
                                <li>Review invoices with outstanding balances on the left</li>
                                <li>Match them with corresponding payments on the right</li>
                                <li>Use the <strong>Auto Reconcile</strong> button to automatically match exact amounts</li>
                                <li>For discrepancies, investigate and manually adjust as needed</li>
                            </ul>
                        </div>

                        <div id="discrepancyReport"></div>
                    </div>
                    
                </div>
            </div>
        </div>

        <?php include 'layouts/footer.php'; ?>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Auto reconcile
        $('#autoReconcile').on('click', function() {
            Swal.fire({
                title: 'Auto Reconcile Payments?',
                text: 'This will automatically match payments to invoices with exact amounts',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: '<i class="ri-magic-line me-1"></i> Run Auto Reconcile',
                confirmButtonColor: '#6366f1'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Show loading
                    Swal.fire({
                        title: 'Reconciling...',
                        text: 'Please wait while we match payments',
                        allowOutsideClick: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });

                    $.ajax({
                        url: 'ajax/auto_reconcile_payments.php',
                        method: 'POST',
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Reconciliation Complete',
                                    html: `<strong>${response.matched}</strong> payment(s) matched successfully`,
                                    timer: 2000
                                }).then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire({
                                    icon: 'info',
                                    title: 'No Matches Found',
                                    text: response.message || 'No exact matches found for auto reconciliation'
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'Failed to run auto reconciliation'
                            });
                        }
                    });
                }
            });
        });

        // Generate report
        $('#generateReport').on('click', function() {
            window.open('reports/reconciliation_report.php', '_blank');
        });

        // View payment details
        $('.view-payment-details').on('click', function() {
            const paymentId = $(this).data('payment-id');
            window.location.href = 'view_payment.php?id=' + paymentId;
        });

        // Highlight invoice on click
        $('.invoice-item').on('click', function() {
            $('.invoice-item').removeClass('selected');
            $(this).addClass('selected');
        });

        // Highlight payment on click
        $('.payment-item').on('click', function() {
            $('.payment-item').removeClass('selected');
            $(this).addClass('selected');
        });
    });
    </script>
</body>
</html>