<?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 = "Refunds & Credits";

// Fetch refunded payments - using exact schema
$query = "SELECT p.*, 
          i.invoice_number,
          pat.patient_number,
          u.full_name as patient_name,
          u.phone_primary,
          receiver.full_name as received_by_name
          FROM payments p
          JOIN invoices i ON p.invoice_id = i.invoice_id
          JOIN patients pat ON p.patient_id = pat.patient_id
          JOIN users u ON pat.user_id = u.user_id
          LEFT JOIN users receiver ON p.received_by = receiver.user_id
          WHERE p.status IN ('REFUNDED', 'REVERSED')
          ORDER BY p.updated_at DESC";

$result = mysqli_query($conn, $query);

// Get refundable payments
$refundable_query = "SELECT p.payment_id, p.payment_number, p.amount, p.payment_date, p.payment_method,
                     i.invoice_number, u.full_name as patient_name
                     FROM payments p
                     JOIN invoices i ON p.invoice_id = i.invoice_id
                     JOIN patients pat ON p.patient_id = pat.patient_id
                     JOIN users u ON pat.user_id = u.user_id
                     WHERE p.status = 'COMPLETED'
                     AND DATE(p.payment_date) >= DATE_SUB(CURDATE(), INTERVAL 90 DAY)
                     ORDER BY p.payment_date DESC";
$refundable_result = mysqli_query($conn, $refundable_query);

// Summary
$summary_query = "SELECT 
                  COUNT(*) as total_refunds,
                  SUM(CASE WHEN status = 'REFUNDED' THEN amount ELSE 0 END) as total_refunded,
                  SUM(CASE WHEN status = 'REVERSED' THEN amount ELSE 0 END) as total_reversed,
                  COUNT(CASE WHEN DATE(updated_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) THEN 1 END) as recent_refunds
                  FROM payments 
                  WHERE status IN ('REFUNDED', 'REVERSED')";
$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" />
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #dc2626 0%, #991b1b 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;
        }
        
        .quick-action-btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            transition: all 0.2s;
        }
        
        .quick-action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
    </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">Refunds & Credits</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-refund-line me-2"></i>Refunds & Credits Management</h4>
                                <p class="mb-0">Process refunds and manage payment reversals</p>
                            </div>
                            <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#processRefundModal">
                                <i class="ri-refund-2-line me-1"></i> Process Refund
                            </button>
                        </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, #dc2626 0%, #991b1b 100%); color: white;">
                                    <i class="ri-refund-line"></i>
                                </div>
                                <div class="stat-value"><?php echo number_format($summary['total_refunds'] ?? 0); ?></div>
                                <div class="stat-label">Total Refunds Processed</div>
                            </div>
                        </div>
                        
                        <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-money-dollar-circle-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['total_refunded'] ?? 0, 2); ?></div>
                                <div class="stat-label">Total Amount Refunded</div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6">
                            <div class="stat-card">
                                <div class="stat-icon" style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); color: white;">
                                    <i class="ri-arrow-go-back-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['total_reversed'] ?? 0, 2); ?></div>
                                <div class="stat-label">Total Amount Reversed</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-calendar-line"></i>
                                </div>
                                <div class="stat-value"><?php echo number_format($summary['recent_refunds'] ?? 0); ?></div>
                                <div class="stat-label">Recent Refunds (30 Days)</div>
                            </div>
                        </div>
                    </div>

                    <!-- Refunds History -->
                    <div class="chart-card">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0"><i class="ri-history-line me-2"></i>Refunds & Reversals History</h5>
                            <button class="btn btn-outline-success btn-sm" id="exportRefunds">
                                <i class="ri-file-excel-line me-1"></i> Export
                            </button>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-hover" id="refundsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>Payment #</th>
                                        <th>Invoice #</th>
                                        <th>Patient</th>
                                        <th>Amount</th>
                                        <th>Method</th>
                                        <th>Original Date</th>
                                        <th>Refund Date</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (mysqli_num_rows($result) > 0): ?>
                                        <?php while ($refund = mysqli_fetch_assoc($result)): ?>
                                        <tr>
                                            <td><strong class="text-danger"><?php echo htmlspecialchars($refund['payment_number']); ?></strong></td>
                                            <td>
                                                <a href="view_invoice.php?id=<?php echo $refund['invoice_id']; ?>">
                                                    <?php echo htmlspecialchars($refund['invoice_number']); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <div class="fw-medium"><?php echo htmlspecialchars($refund['patient_name']); ?></div>
                                                <small class="text-muted"><?php echo htmlspecialchars($refund['patient_number']); ?></small>
                                            </td>
                                            <td><strong class="text-danger">KES <?php echo number_format($refund['amount'], 2); ?></strong></td>
                                            <td><span class="badge bg-info"><?php echo str_replace('_', ' ', $refund['payment_method']); ?></span></td>
                                            <td><?php echo date('d M Y', strtotime($refund['payment_date'])); ?></td>
                                            <td><?php echo date('d M Y', strtotime($refund['updated_at'])); ?></td>
                                            <td>
                                                <?php
                                                $statusColors = [
                                                    'REFUNDED' => 'danger',
                                                    'REVERSED' => 'dark'
                                                ];
                                                $color = $statusColors[$refund['status']] ?? 'secondary';
                                                echo '<span class="badge bg-' . $color . '">' . $refund['status'] . '</span>';
                                                ?>
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-outline-primary view-refund"
                                                        data-payment-id="<?php echo $refund['payment_id']; ?>">
                                                    <i class="ri-eye-line"></i>
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="9" class="text-center py-5">
                                                <div class="text-muted">
                                                    <i class="ri-refund-line" style="font-size: 3rem;"></i>
                                                    <p class="mt-3 mb-0">No refunds or reversals yet</p>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>

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

    <!-- Process Refund Modal -->
    <div class="modal fade" id="processRefundModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="ri-refund-2-line me-2"></i>Process Refund</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form id="refundForm">
                    <div class="modal-body">
                        <div class="alert alert-warning">
                            <i class="ri-alert-line me-2"></i>
                            <strong>Warning:</strong> This action cannot be undone. Please verify payment details before proceeding.
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Select Payment to Refund <span class="text-danger">*</span></label>
                            <select class="form-select select2-modal" name="payment_id" id="refund_payment_id" required>
                                <option value="">Search payment...</option>
                                <?php 
                                mysqli_data_seek($refundable_result, 0);
                                while ($pay = mysqli_fetch_assoc($refundable_result)): 
                                ?>
                                <option value="<?php echo $pay['payment_id']; ?>"
                                        data-amount="<?php echo $pay['amount']; ?>"
                                        data-method="<?php echo $pay['payment_method']; ?>">
                                    <?php echo $pay['payment_number'] . ' - ' . $pay['patient_name'] . ' (KES ' . number_format($pay['amount'], 2) . ')'; ?>
                                </option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <div id="refundDetails" style="display: none;">
                            <div class="alert alert-info">
                                <div class="row">
                                    <div class="col-6">
                                        <strong>Amount:</strong><br>
                                        <span id="refund_amount_display">KES 0.00</span>
                                    </div>
                                    <div class="col-6">
                                        <strong>Method:</strong><br>
                                        <span id="refund_method_display">-</span>
                                    </div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Refund Reason <span class="text-danger">*</span></label>
                                <select class="form-select" name="refund_reason" required>
                                    <option value="">Select reason...</option>
                                    <option value="DUPLICATE_PAYMENT">Duplicate Payment</option>
                                    <option value="OVERPAYMENT">Overpayment</option>
                                    <option value="SERVICE_NOT_PROVIDED">Service Not Provided</option>
                                    <option value="PATIENT_REQUEST">Patient Request</option>
                                    <option value="BILLING_ERROR">Billing Error</option>
                                    <option value="OTHER">Other</option>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Additional Notes <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="refund_notes" rows="3" required
                                          placeholder="Provide detailed reason for this refund..."></textarea>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Refund Method <span class="text-danger">*</span></label>
                                <select class="form-select" name="refund_method" required>
                                    <option value="ORIGINAL_METHOD">Same as Original Payment Method</option>
                                    <option value="CASH">Cash</option>
                                    <option value="BANK_TRANSFER">Bank Transfer</option>
                                    <option value="MPESA">M-Pesa</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger" id="processRefundBtn" disabled>
                            <i class="ri-refund-2-line me-1"></i> Process Refund
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize Select2
        $('.select2-modal').select2({
            theme: 'bootstrap-5',
            dropdownParent: $('#processRefundModal'),
            width: '100%'
        });

        // Initialize DataTable
        $('#refundsTable').DataTable({
            order: [[6, 'desc']], // Sort by refund date
            pageLength: 25
        });

        // Handle payment selection
        $('#refund_payment_id').on('change', function() {
            const selected = $(this).find(':selected');
            if ($(this).val()) {
                const amount = parseFloat(selected.data('amount'));
                const method = selected.data('method');
                
                $('#refund_amount_display').text('KES ' + amount.toFixed(2));
                $('#refund_method_display').text(method.replace(/_/g, ' '));
                $('#refundDetails').show();
                $('#processRefundBtn').prop('disabled', false);
            } else {
                $('#refundDetails').hide();
                $('#processRefundBtn').prop('disabled', true);
            }
        });

        // Handle refund form submission
        $('#refundForm').on('submit', function(e) {
            e.preventDefault();
            
            Swal.fire({
                title: 'Confirm Refund?',
                html: `<strong>This action cannot be undone!</strong><br><br>
                       Amount: <strong>${$('#refund_amount_display').text()}</strong>`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Process Refund',
                confirmButtonColor: '#dc2626',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    const formData = $(this).serialize();
                    
                    $.ajax({
                        url: 'ajax/process_refund.php',
                        method: 'POST',
                        data: formData,
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Refund Processed',
                                    text: 'Payment has been successfully refunded',
                                    timer: 2000
                                }).then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Refund Failed',
                                    text: response.message || 'Failed to process refund'
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'Network error. Please try again.'
                            });
                        }
                    });
                }
            });
        });

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

        // Export refunds
        $('#exportRefunds').on('click', function() {
            window.location.href = 'ajax/export_refunds.php';
        });
    });
    </script>
</body>
</html>