<?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', 'BILLING_CLERK', 'ACCOUNTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: index.php');
    exit();
}

$page_title = "All Payments";

// Fetch all 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 ('COMPLETED', 'PENDING')
          ORDER BY p.payment_date DESC, p.created_at DESC";

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

// Calculate summary statistics
$summary_query = "SELECT 
                  COUNT(*) as total_payments,
                  SUM(CASE WHEN status = 'COMPLETED' THEN amount ELSE 0 END) as total_collected,
                  SUM(CASE WHEN DATE(payment_date) = CURDATE() AND status = 'COMPLETED' THEN amount ELSE 0 END) as today_collected,
                  SUM(CASE WHEN payment_method = 'CASH' AND status = 'COMPLETED' THEN amount ELSE 0 END) as cash_collected,
                  SUM(CASE WHEN payment_method = 'MPESA' AND status = 'COMPLETED' THEN amount ELSE 0 END) as mpesa_collected,
                  SUM(CASE WHEN payment_method = 'CARD' AND status = 'COMPLETED' THEN amount ELSE 0 END) as card_collected,
                  SUM(CASE WHEN payment_method = 'INSURANCE_DIRECT' AND status = 'COMPLETED' THEN amount ELSE 0 END) as insurance_collected
                  FROM payments 
                  WHERE DATE(payment_date) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)";
$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, #059669 0%, #047857 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 {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            transition: transform 0.2s;
            margin-bottom: 1.5rem;
        }
        
        .stat-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.15);
        }
        
        .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;
        }
        
        .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;
        }
        
        .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);
        }
        
        .payment-mode-badge {
            padding: 0.375rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .payment-mode-badge.cash { background: #dcfce7; color: #166534; }
        .payment-mode-badge.mpesa { background: #dbeafe; color: #1e40af; }
        .payment-mode-badge.card { background: #fef3c7; color: #92400e; }
        .payment-mode-badge.insurancedirect { background: #f3e8ff; color: #6b21a8; }
        .payment-mode-badge.cheque { background: #e0f2fe; color: #075985; }
        .payment-mode-badge.banktransfer { background: #fce7f3; color: #831843; }
        .payment-mode-badge.corporate { background: #fef9c3; color: #854d0e; }
    </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">Payments</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-money-dollar-circle-line me-2"></i>Payment Records</h4>
                                <p class="mb-0">View and manage all payment transactions</p>
                            </div>
                            <a href="record_payment.php" class="btn btn-light">
                                <i class="ri-add-line me-1"></i> Record Payment
                            </a>
                        </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, #059669 0%, #047857 100%); color: white;">
                                    <i class="ri-exchange-dollar-line"></i>
                                </div>
                                <div class="stat-value"><?php echo number_format($summary['total_payments'] ?? 0); ?></div>
                                <div class="stat-label">Total Transactions (30 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-money-dollar-circle-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['total_collected'] ?? 0, 2); ?></div>
                                <div class="stat-label">Total Collected (30 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, #f59e0b 0%, #d97706 100%); color: white;">
                                    <i class="ri-calendar-check-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['today_collected'] ?? 0, 2); ?></div>
                                <div class="stat-label">Today's Collections</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-smartphone-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['mpesa_collected'] ?? 0, 2); ?></div>
                                <div class="stat-label">M-Pesa Collections</div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="chart-card">
                                <h5 class="mb-3">Quick Actions</h5>
                                <div class="d-flex flex-wrap gap-2">
                                    <a href="record_payment.php" class="btn btn-success quick-action-btn">
                                        <i class="ri-add-line"></i> New Payment
                                    </a>
                                    <a href="mpesa_transactions.php" class="btn btn-primary quick-action-btn">
                                        <i class="ri-smartphone-line"></i> M-Pesa Transactions
                                    </a>
                                    <a href="payment_reconciliation.php" class="btn btn-info quick-action-btn">
                                        <i class="ri-file-list-check-line"></i> Reconciliation
                                    </a>
                                    <button type="button" class="btn btn-outline-success quick-action-btn" id="exportPayments">
                                        <i class="ri-file-excel-line"></i> Export
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Payments Table -->
                    <div class="chart-card">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <h5 class="mb-0"><i class="ri-file-list-line me-2"></i>Payment History</h5>
                            <div class="d-flex gap-2">
                                <button class="btn btn-outline-primary btn-sm" id="filterPayments">
                                    <i class="ri-filter-line me-1"></i> Filter
                                </button>
                                <button class="btn btn-outline-primary btn-sm" id="printList">
                                    <i class="ri-printer-line me-1"></i> Print
                                </button>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-hover" id="paymentsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>Payment #</th>
                                        <th>Date</th>
                                        <th>Invoice #</th>
                                        <th>Patient</th>
                                        <th>Amount</th>
                                        <th>Method</th>
                                        <th>Reference</th>
                                        <th>Received By</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (mysqli_num_rows($result) > 0): ?>
                                        <?php while ($payment = mysqli_fetch_assoc($result)): ?>
                                        <tr>
                                            <td>
                                                <strong class="text-primary"><?php echo htmlspecialchars($payment['payment_number']); ?></strong>
                                            </td>
                                            <td><?php echo date('d M Y H:i', strtotime($payment['payment_date'])); ?></td>
                                            <td>
                                                <a href="view_invoice.php?id=<?php echo $payment['invoice_id']; ?>">
                                                    <?php echo htmlspecialchars($payment['invoice_number']); ?>
                                                </a>
                                            </td>
                                            <td>
                                                <div class="fw-medium"><?php echo htmlspecialchars($payment['patient_name']); ?></div>
                                                <small class="text-muted"><?php echo htmlspecialchars($payment['patient_number']); ?></small>
                                            </td>
                                            <td>
                                                <strong class="text-success">KES <?php echo number_format($payment['amount'], 2); ?></strong>
                                            </td>
                                            <td>
                                                <span class="payment-mode-badge <?php echo strtolower(str_replace('_', '', $payment['payment_method'])); ?>">
                                                    <?php echo str_replace('_', ' ', $payment['payment_method']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if ($payment['payment_reference']): ?>
                                                    <small><?php echo htmlspecialchars($payment['payment_reference']); ?></small>
                                                <?php else: ?>
                                                    <small class="text-muted">-</small>
                                                <?php endif; ?>
                                            </td>
                                            <td><small><?php echo htmlspecialchars($payment['received_by_name']); ?></small></td>
                                            <td>
                                                <?php
                                                $statusColors = [
                                                    'COMPLETED' => 'success',
                                                    'PENDING' => 'warning',
                                                    'FAILED' => 'danger',
                                                    'REVERSED' => 'dark',
                                                    'REFUNDED' => 'info'
                                                ];
                                                $color = $statusColors[$payment['status']] ?? 'secondary';
                                                echo '<span class="badge bg-' . $color . '">' . $payment['status'] . '</span>';
                                                ?>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <button type="button" class="btn btn-outline-primary view-payment" 
                                                            data-payment-id="<?php echo $payment['payment_id']; ?>" 
                                                            title="View Details">
                                                        <i class="ri-eye-line"></i>
                                                    </button>
                                                    <button type="button" class="btn btn-outline-success print-receipt" 
                                                            data-payment-id="<?php echo $payment['payment_id']; ?>" 
                                                            title="Print Receipt">
                                                        <i class="ri-printer-line"></i>
                                                    </button>
                                                    <?php if ($payment['status'] == 'COMPLETED' && in_array($_SESSION['role_code'], ['SUPER_ADMIN', 'HOSPITAL_ADMIN'])): ?>
                                                    <button type="button" class="btn btn-outline-danger reverse-payment" 
                                                            data-payment-id="<?php echo $payment['payment_id']; ?>" 
                                                            data-amount="<?php echo $payment['amount']; ?>"
                                                            title="Reverse Payment">
                                                        <i class="ri-arrow-go-back-line"></i>
                                                    </button>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="10" class="text-center py-5">
                                                <div class="text-muted">
                                                    <i class="ri-money-dollar-circle-line" style="font-size: 3rem;"></i>
                                                    <p class="mt-3 mb-0">No payments recorded yet</p>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </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 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>
    $(document).ready(function() {
        // Initialize DataTable
        const table = $('#paymentsTable').DataTable({
            order: [[1, 'desc']], // Sort by date descending
            pageLength: 25,
            columnDefs: [
                { orderable: false, targets: [9] } // Disable sorting for actions
            ],
            language: {
                search: "_INPUT_",
                searchPlaceholder: "Search payments..."
            }
        });

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

        // Print receipt
        $('.print-receipt').on('click', function() {
            const paymentId = $(this).data('payment-id');
            window.open('print_receipt.php?id=' + paymentId, '_blank');
        });

        // Reverse payment
        $('.reverse-payment').on('click', function() {
            const paymentId = $(this).data('payment-id');
            const amount = $(this).data('amount');
            
            Swal.fire({
                title: 'Reverse Payment?',
                html: `Are you sure you want to reverse this payment of <strong>KES ${parseFloat(amount).toFixed(2)}</strong>?<br><br>
                       <strong>This action cannot be undone!</strong>`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Reverse It',
                confirmButtonColor: '#dc2626',
                cancelButtonText: 'Cancel',
                input: 'textarea',
                inputLabel: 'Reason for reversal (required):',
                inputPlaceholder: 'Enter reason for payment reversal...',
                inputValidator: (value) => {
                    if (!value) {
                        return 'You must provide a reason for reversal!'
                    }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: 'ajax/reverse_payment.php',
                        method: 'POST',
                        data: { 
                            payment_id: paymentId,
                            reason: result.value
                        },
                        dataType: 'json',
                        success: function(response) {
                            if (response.success) {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Payment Reversed',
                                    text: 'Payment has been successfully reversed',
                                    timer: 2000
                                }).then(() => {
                                    location.reload();
                                });
                            } else {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Reversal Failed',
                                    text: response.message || 'Failed to reverse payment'
                                });
                            }
                        },
                        error: function() {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: 'Network error. Please try again.'
                            });
                        }
                    });
                }
            });
        });

        // Export payments
        $('#exportPayments').on('click', function() {
            window.location.href = 'ajax/export_payments.php';
        });

        // Print list
        $('#printList').on('click', function() {
            window.print();
        });
    });
    </script>
</body>
</html>