<?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 = "Bulk Payments";

// Fetch bulk payments - using exact schema
$query = "SELECT bp.*, 
          esp.provider_name, esp.provider_code,
          receiver.full_name as received_by_name,
          allocator.full_name as allocated_by_name
          FROM bulk_payments bp
          JOIN external_service_providers esp ON bp.provider_id = esp.provider_id
          LEFT JOIN users receiver ON bp.received_by = receiver.user_id
          LEFT JOIN users allocator ON bp.allocated_by = allocator.user_id
          ORDER BY bp.payment_date DESC, bp.created_at DESC";

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

// Get external providers for dropdown
$providers_query = "SELECT provider_id, provider_name, provider_code 
                    FROM external_service_providers 
                    WHERE is_active = 1 
                    ORDER BY provider_name";
$providers_result = mysqli_query($conn, $providers_query);

// Calculate summary
$summary_query = "SELECT 
                  COUNT(*) as total_bulk_payments,
                  SUM(total_amount) as total_received,
                  SUM(allocated_amount) as total_allocated,
                  SUM(unallocated_amount) as total_unallocated,
                  COUNT(CASE WHEN allocation_status = 'PENDING' THEN 1 END) as pending_allocation
                  FROM bulk_payments";
$summary_result = mysqli_query($conn, $summary_query);
$summary = mysqli_fetch_assoc($summary_result);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_bulk_payment'])) {
    $provider_id = mysqli_real_escape_string($conn, $_POST['provider_id']);
    $payment_date = mysqli_real_escape_string($conn, $_POST['payment_date']);
    $period_start = mysqli_real_escape_string($conn, $_POST['payment_period_start']);
    $period_end = mysqli_real_escape_string($conn, $_POST['payment_period_end']);
    $total_amount = floatval($_POST['total_amount']);
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $transaction_reference = mysqli_real_escape_string($conn, $_POST['transaction_reference']);
    $notes = mysqli_real_escape_string($conn, $_POST['notes']);
    
    // Optional fields
    $bank_name = isset($_POST['bank_name']) ? mysqli_real_escape_string($conn, $_POST['bank_name']) : NULL;
    $cheque_number = isset($_POST['cheque_number']) ? mysqli_real_escape_string($conn, $_POST['cheque_number']) : NULL;
    $mpesa_code = isset($_POST['mpesa_code']) ? mysqli_real_escape_string($conn, $_POST['mpesa_code']) : NULL;
    
    mysqli_begin_transaction($conn);
    
    try {
        // Generate payment number
        $prefix = "BP-" . date('Y') . "-";
        $random = rand(10000, 99999);
        $payment_number = $prefix . $random;
        
        $insert_query = "INSERT INTO bulk_payments (
                        payment_number, provider_id, payment_date, 
                        payment_period_start, payment_period_end, total_amount,
                        payment_method, transaction_reference, bank_name, 
                        cheque_number, mpesa_code, currency, exchange_rate,
                        allocation_status, reconciliation_status, notes, received_by
                        ) VALUES (
                        '$payment_number', '$provider_id', '$payment_date',
                        '$period_start', '$period_end', '$total_amount',
                        '$payment_method', " . ($transaction_reference ? "'$transaction_reference'" : "NULL") . ",
                        " . ($bank_name ? "'$bank_name'" : "NULL") . ",
                        " . ($cheque_number ? "'$cheque_number'" : "NULL") . ",
                        " . ($mpesa_code ? "'$mpesa_code'" : "NULL") . ",
                        'KES', 1.0000, 'PENDING', 'PENDING', 
                        " . ($notes ? "'$notes'" : "NULL") . ", {$_SESSION['user_id']}
                        )";
        
        if (!mysqli_query($conn, $insert_query)) {
            throw new Exception("Error creating bulk payment: " . mysqli_error($conn));
        }
        
        $bulk_payment_id = mysqli_insert_id($conn);
        
        mysqli_commit($conn);
        $_SESSION['success_message'] = "Bulk payment $payment_number created successfully!";
        header("Location: allocate_bulk_payment.php?id=$bulk_payment_id");
        exit();
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $error_message = $e->getMessage();
    }
}

?>

<?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, #0ea5e9 0%, #0284c7 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);
        }
        
        .allocation-progress {
            height: 8px;
            border-radius: 4px;
            background: #e5e7eb;
            overflow: hidden;
        }
        
        .allocation-progress-bar {
            height: 100%;
            background: linear-gradient(135deg, #059669 0%, #047857 100%);
            transition: width 0.3s;
        }
    </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">Bulk 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-file-list-3-line me-2"></i>Bulk Payment Processing</h4>
                                <p class="mb-0">Manage bulk payments from external providers</p>
                            </div>
                            <button type="button" class="btn btn-light" data-bs-toggle="modal" data-bs-target="#createBulkPaymentModal">
                                <i class="ri-add-line me-1"></i> New Bulk Payment
                            </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, #0ea5e9 0%, #0284c7 100%); color: white;">
                                    <i class="ri-file-list-3-line"></i>
                                </div>
                                <div class="stat-value"><?php echo number_format($summary['total_bulk_payments'] ?? 0); ?></div>
                                <div class="stat-label">Total Bulk Payments</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-money-dollar-circle-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['total_received'] ?? 0, 2); ?></div>
                                <div class="stat-label">Total Received</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-checkbox-circle-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['total_allocated'] ?? 0, 2); ?></div>
                                <div class="stat-label">Total Allocated</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-time-line"></i>
                                </div>
                                <div class="stat-value">KES <?php echo number_format($summary['total_unallocated'] ?? 0, 2); ?></div>
                                <div class="stat-label">Unallocated</div>
                                <small class="text-warning"><?php echo $summary['pending_allocation'] ?? 0; ?> pending</small>
                            </div>
                        </div>
                    </div>

                    <!-- Bulk 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-list-check me-2"></i>Bulk Payment Records</h5>
                            <button class="btn btn-outline-success btn-sm" id="exportBulkPayments">
                                <i class="ri-file-excel-line me-1"></i> Export
                            </button>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-hover" id="bulkPaymentsTable">
                                <thead class="table-light">
                                    <tr>
                                        <th>Payment #</th>
                                        <th>Date</th>
                                        <th>Provider</th>
                                        <th>Period</th>
                                        <th>Amount</th>
                                        <th>Allocated</th>
                                        <th>Unallocated</th>
                                        <th>Method</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (mysqli_num_rows($result) > 0): ?>
                                        <?php while ($payment = mysqli_fetch_assoc($result)): 
                                            $allocation_percentage = ($payment['total_amount'] > 0) 
                                                ? ($payment['allocated_amount'] / $payment['total_amount']) * 100 
                                                : 0;
                                        ?>
                                        <tr>
                                            <td>
                                                <strong class="text-primary"><?php echo htmlspecialchars($payment['payment_number']); ?></strong>
                                            </td>
                                            <td><?php echo date('d M Y', strtotime($payment['payment_date'])); ?></td>
                                            <td>
                                                <div class="fw-medium"><?php echo htmlspecialchars($payment['provider_name']); ?></div>
                                                <small class="text-muted"><?php echo htmlspecialchars($payment['provider_code']); ?></small>
                                            </td>
                                            <td>
                                                <small>
                                                    <?php echo date('d M', strtotime($payment['payment_period_start'])); ?> - 
                                                    <?php echo date('d M Y', strtotime($payment['payment_period_end'])); ?>
                                                </small>
                                            </td>
                                            <td>
                                                <strong>KES <?php echo number_format($payment['total_amount'], 2); ?></strong>
                                            </td>
                                            <td>
                                                <div>KES <?php echo number_format($payment['allocated_amount'], 2); ?></div>
                                                <div class="allocation-progress mt-1">
                                                    <div class="allocation-progress-bar" style="width: <?php echo $allocation_percentage; ?>%"></div>
                                                </div>
                                                <small class="text-muted"><?php echo number_format($allocation_percentage, 1); ?>%</small>
                                            </td>
                                            <td>
                                                <?php if ($payment['unallocated_amount'] > 0): ?>
                                                    <strong class="text-warning">KES <?php echo number_format($payment['unallocated_amount'], 2); ?></strong>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <span class="badge bg-info"><?php echo str_replace('_', ' ', $payment['payment_method']); ?></span>
                                            </td>
                                            <td>
                                                <?php
                                                $allocationColors = [
                                                    'PENDING' => 'warning',
                                                    'PARTIAL' => 'info',
                                                    'COMPLETED' => 'success',
                                                    'RECONCILED' => 'primary'
                                                ];
                                                $color = $allocationColors[$payment['allocation_status']] ?? 'secondary';
                                                echo '<span class="badge bg-' . $color . '">' . $payment['allocation_status'] . '</span>';
                                                ?>
                                            </td>
                                            <td>
                                                <div class="btn-group btn-group-sm">
                                                    <a href="view_bulk_payment.php?id=<?php echo $payment['bulk_payment_id']; ?>" 
                                                       class="btn btn-outline-primary" title="View">
                                                        <i class="ri-eye-line"></i>
                                                    </a>
                                                    <?php if ($payment['allocation_status'] != 'COMPLETED'): ?>
                                                    <a href="allocate_bulk_payment.php?id=<?php echo $payment['bulk_payment_id']; ?>" 
                                                       class="btn btn-outline-success" title="Allocate">
                                                        <i class="ri-distribution-line"></i>
                                                    </a>
                                                    <?php endif; ?>
                                                    <button type="button" class="btn btn-outline-info view-allocations" 
                                                            data-payment-id="<?php echo $payment['bulk_payment_id']; ?>" 
                                                            title="View Allocations">
                                                        <i class="ri-list-check"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <tr>
                                            <td colspan="10" class="text-center py-5">
                                                <div class="text-muted">
                                                    <i class="ri-file-list-3-line" style="font-size: 3rem;"></i>
                                                    <p class="mt-3 mb-0">No bulk payments recorded yet</p>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    
                </div>
            </div>
        </div>

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

    <!-- Create Bulk Payment Modal -->
    <div class="modal fade" id="createBulkPaymentModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Create Bulk Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">External Provider <span class="text-danger">*</span></label>
                                <select class="form-select select2" name="provider_id" required>
                                    <option value="">Select Provider</option>
                                    <?php 
                                    mysqli_data_seek($providers_result, 0);
                                    while ($provider = mysqli_fetch_assoc($providers_result)): 
                                    ?>
                                    <option value="<?php echo $provider['provider_id']; ?>">
                                        <?php echo htmlspecialchars($provider['provider_name']); ?>
                                    </option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Payment Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="payment_date" 
                                       value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Period Start <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="payment_period_start" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Period End <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="payment_period_end" required>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Total Amount (KES) <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="total_amount" 
                                       min="0" step="0.01" required>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Payment Method <span class="text-danger">*</span></label>
                                <select class="form-select" name="payment_method" id="bulk_payment_method" required>
                                    <option value="BANK_TRANSFER">Bank Transfer</option>
                                    <option value="CHEQUE">Cheque</option>
                                    <option value="MOBILE_MONEY">Mobile Money</option>
                                    <option value="CASH">Cash</option>
                                    <option value="CARD">Card</option>
                                </select>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-12">
                                <label class="form-label">Transaction Reference</label>
                                <input type="text" class="form-control" name="transaction_reference">
                            </div>
                        </div>

                        <div class="row mb-3" id="bank_fields">
                            <div class="col-md-12">
                                <label class="form-label">Bank Name</label>
                                <input type="text" class="form-control" name="bank_name">
                            </div>
                        </div>

                        <div class="row mb-3" id="cheque_fields" style="display: none;">
                            <div class="col-md-12">
                                <label class="form-label">Cheque Number</label>
                                <input type="text" class="form-control" name="cheque_number">
                            </div>
                        </div>

                        <div class="row mb-3" id="mpesa_fields" style="display: none;">
                            <div class="col-md-12">
                                <label class="form-label">M-Pesa Transaction Code</label>
                                <input type="text" class="form-control" name="mpesa_code">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" name="notes" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="create_bulk_payment" class="btn btn-primary">
                            <i class="ri-check-line me-1"></i> Create Bulk Payment
                        </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').select2({
            theme: 'bootstrap-5',
            dropdownParent: $('#createBulkPaymentModal')
        });

        // Initialize DataTable
        $('#bulkPaymentsTable').DataTable({
            order: [[1, 'desc']],
            pageLength: 25
        });

        // Handle payment method change
        $('#bulk_payment_method').on('change', function() {
            $('#bank_fields, #cheque_fields, #mpesa_fields').hide();
            
            if ($(this).val() === 'BANK_TRANSFER') {
                $('#bank_fields').show();
            } else if ($(this).val() === 'CHEQUE') {
                $('#cheque_fields').show();
            } else if ($(this).val() === 'MOBILE_MONEY') {
                $('#mpesa_fields').show();
            }
        });

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

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