<?php
// record_bulk_payment.php - Record Bulk Payment Receipt
include 'layouts/session.php';
include 'layouts/dbconn.php';

// Get active providers
$providers_sql = "SELECT provider_id, provider_name, provider_code, payment_terms, current_balance 
                  FROM external_service_providers 
                  WHERE is_active = 1 
                  ORDER BY provider_name";
$providers = $conn->query($providers_sql);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn->begin_transaction();
    
    try {
        // Generate payment number
        $payment_number = 'BP-' . date('Y') . '-' . str_pad(rand(1, 99999), 5, '0', STR_PAD_LEFT);
        
        // Check if number exists
        $check_sql = "SELECT bulk_payment_id FROM bulk_payments WHERE payment_number = ?";
        $stmt = $conn->prepare($check_sql);
        $stmt->bind_param('s', $payment_number);
        $stmt->execute();
        if ($stmt->get_result()->num_rows > 0) {
            $payment_number = 'BP-' . date('Y') . '-' . str_pad(rand(10000, 99999), 5, '0', STR_PAD_LEFT);
        }
        
        // Get form data
        $provider_id = intval($_POST['provider_id']);
        $payment_date = $_POST['payment_date'];
        $payment_period_start = $_POST['payment_period_start'];
        $payment_period_end = $_POST['payment_period_end'];
        $total_amount = floatval($_POST['total_amount']);
        $payment_method = $_POST['payment_method'];
        $transaction_reference = trim($_POST['transaction_reference']);
        $bank_name = trim($_POST['bank_name'] ?? '');
        $cheque_number = trim($_POST['cheque_number'] ?? '');
        $mpesa_code = trim($_POST['mpesa_code'] ?? '');
        $currency = $_POST['currency'] ?? 'KES';
        $notes = trim($_POST['notes'] ?? '');
        $received_by = $_SESSION['user_id'];
        
        // Insert bulk payment
        $insert_sql = "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, notes, received_by)
                       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($insert_sql);
        $stmt->bind_param('sisssdsssssssi',
            $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, $notes, $received_by
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Failed to record payment: " . $stmt->error);
        }
        
        $bulk_payment_id = $conn->insert_id;
        
        // Update provider balance
        $update_balance_sql = "UPDATE external_service_providers 
                               SET current_balance = current_balance + ?
                               WHERE provider_id = ?";
        $stmt = $conn->prepare($update_balance_sql);
        $stmt->bind_param('di', $total_amount, $provider_id);
        $stmt->execute();
        
        // Log activity
        $activity_sql = "INSERT INTO activity_logs (user_id, action, description, ip_address)
                         VALUES (?, 'RECORD_BULK_PAYMENT', ?, ?)";
        $stmt = $conn->prepare($activity_sql);
        $description = "Recorded bulk payment: {$payment_number} - KES " . number_format($total_amount, 2);
        $ip_address = $_SERVER['REMOTE_ADDR'];
        $stmt->bind_param('iss', $received_by, $description, $ip_address);
        $stmt->execute();
        
        $conn->commit();
        
        $_SESSION['success_message'] = "Bulk payment recorded successfully!";
        header("Location: view_bulk_payment.php?id=" . $bulk_payment_id);
        exit();
        
    } catch (Exception $e) {
        $conn->rollback();
        $error_message = $e->getMessage();
    }
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Record Bulk Payment')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            padding: 2rem;
            border-radius: 12px;
            color: white;
            margin-bottom: 2rem;
        }
        
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
        }
        
        .section-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1.5rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .info-box {
            background: #f0fdf4;
            border-left: 4px solid #10b981;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
        }
        
        .payment-method-selector {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .method-option {
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .method-option:hover {
            border-color: #10b981;
            background: #f8fafc;
        }
        
        .method-option.active {
            border-color: #10b981;
            background: #f0fdf4;
        }
        
        .method-option input[type="radio"] {
            display: none;
        }
        
        .method-option i {
            font-size: 2rem;
            color: #10b981;
            margin-bottom: 0.5rem;
        }
        
        .method-title {
            font-weight: 600;
            color: #1e293b;
        }
        
        .hidden {
            display: none;
        }
        
        .provider-info {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
        }
    </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 Header -->
                    <div class="page-header">
                        <div class="row align-items-center">
                            <div class="col">
                                <h3 class="mb-2"><i class="ri-bank-line me-2"></i>Record Bulk Payment</h3>
                                <p class="mb-0 opacity-75">Record payment received from external service provider</p>
                            </div>
                            <div class="col-auto">
                                <a href="list_bulk_payments.php" class="btn btn-light">
                                    <i class="ri-arrow-left-line me-1"></i>Back to List
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <?php if (isset($error_message)): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="ri-error-warning-line me-2"></i><?php echo htmlspecialchars($error_message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>
                    
                    <form method="POST" action="" id="paymentForm">
                        
                        <!-- Provider Selection -->
                        <div class="form-card">
                            <div class="section-title">
                                <i class="ri-building-line"></i>Service Provider
                            </div>
                            
                            <div class="row g-3">
                                <div class="col-md-12">
                                    <label class="form-label">Select Provider <span class="text-danger">*</span></label>
                                    <select class="form-select" name="provider_id" id="providerSelect" required>
                                        <option value="">Choose provider...</option>
                                        <?php while ($provider = $providers->fetch_assoc()): ?>
                                            <option value="<?php echo $provider['provider_id']; ?>"
                                                    data-name="<?php echo htmlspecialchars($provider['provider_name']); ?>"
                                                    data-code="<?php echo htmlspecialchars($provider['provider_code']); ?>"
                                                    data-terms="<?php echo htmlspecialchars($provider['payment_terms']); ?>"
                                                    data-balance="<?php echo $provider['current_balance']; ?>">
                                                <?php echo htmlspecialchars($provider['provider_name']); ?> 
                                                (<?php echo htmlspecialchars($provider['provider_code']); ?>)
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                </div>
                            </div>
                            
                            <div id="providerInfo" class="provider-info hidden">
                                <div class="row">
                                    <div class="col-md-6">
                                        <small class="text-muted">Payment Terms:</small>
                                        <div class="fw-bold" id="infoTerms">-</div>
                                    </div>
                                    <div class="col-md-6">
                                        <small class="text-muted">Current Outstanding:</small>
                                        <div class="fw-bold text-warning" id="infoBalance">-</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Payment Details -->
                        <div class="form-card">
                            <div class="section-title">
                                <i class="ri-money-dollar-circle-line"></i>Payment Details
                            </div>
                            
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">Payment Date <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control datepicker" name="payment_date" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Total Amount (KES) <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" name="total_amount" 
                                           id="totalAmount" step="0.01" min="0.01" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Currency</label>
                                    <select class="form-select" name="currency">
                                        <option value="KES" selected>KES - Kenyan Shilling</option>
                                        <option value="USD">USD - US Dollar</option>
                                        <option value="EUR">EUR - Euro</option>
                                        <option value="GBP">GBP - British Pound</option>
                                    </select>
                                </div>
                            </div>
                            
                            <div class="row g-3 mt-2">
                                <div class="col-md-6">
                                    <label class="form-label">Service Period Start <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control datepicker" name="payment_period_start" required>
                                    <small class="text-muted">Start date of services covered by this payment</small>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Service Period End <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control datepicker" name="payment_period_end" required>
                                    <small class="text-muted">End date of services covered by this payment</small>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Payment Method -->
                        <div class="form-card">
                            <div class="section-title">
                                <i class="ri-bank-card-line"></i>Payment Method
                            </div>
                            
                            <div class="payment-method-selector">
                                <label class="method-option" for="bankTransfer">
                                    <input type="radio" name="payment_method" id="bankTransfer" value="BANK_TRANSFER">
                                    <i class="ri-bank-line"></i>
                                    <div class="method-title">Bank Transfer</div>
                                </label>
                                
                                <label class="method-option" for="cheque">
                                    <input type="radio" name="payment_method" id="cheque" value="CHEQUE">
                                    <i class="ri-file-list-line"></i>
                                    <div class="method-title">Cheque</div>
                                </label>
                                
                                <label class="method-option" for="mobileMoney">
                                    <input type="radio" name="payment_method" id="mobileMoney" value="MOBILE_MONEY">
                                    <i class="ri-smartphone-line"></i>
                                    <div class="method-title">M-Pesa</div>
                                </label>
                                
                                <label class="method-option" for="cash">
                                    <input type="radio" name="payment_method" id="cash" value="CASH">
                                    <i class="ri-money-dollar-circle-line"></i>
                                    <div class="method-title">Cash</div>
                                </label>
                                
                                <label class="method-option" for="card">
                                    <input type="radio" name="payment_method" id="card" value="CARD">
                                    <i class="ri-bank-card-line"></i>
                                    <div class="method-title">Card</div>
                                </label>
                            </div>
                            
                            <!-- Bank Transfer Fields -->
                            <div id="bankTransferFields" class="hidden">
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Bank Name</label>
                                        <input type="text" class="form-control" name="bank_name" 
                                               placeholder="e.g., Equity Bank">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Transaction Reference</label>
                                        <input type="text" class="form-control" name="transaction_reference" 
                                               placeholder="Bank transaction reference number">
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Cheque Fields -->
                            <div id="chequeFields" class="hidden">
                                <div class="row g-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Bank Name</label>
                                        <input type="text" class="form-control" name="bank_name" 
                                               placeholder="Bank name on cheque">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Cheque Number</label>
                                        <input type="text" class="form-control" name="cheque_number" 
                                               placeholder="Cheque number">
                                    </div>
                                </div>
                            </div>
                            
                            <!-- M-Pesa Fields -->
                            <div id="mpesaFields" class="hidden">
                                <div class="row g-3">
                                    <div class="col-md-12">
                                        <label class="form-label">M-Pesa Transaction Code</label>
                                        <input type="text" class="form-control" name="mpesa_code" 
                                               placeholder="e.g., RGH7K8L9M0">
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Cash/Card - Just reference -->
                            <div id="otherFields" class="hidden">
                                <div class="row g-3">
                                    <div class="col-md-12">
                                        <label class="form-label">Transaction Reference (Optional)</label>
                                        <input type="text" class="form-control" name="transaction_reference" 
                                               placeholder="Any reference number or identifier">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Additional Information -->
                        <div class="form-card">
                            <div class="section-title">
                                <i class="ri-file-text-line"></i>Additional Information
                            </div>
                            
                            <div class="row g-3">
                                <div class="col-md-12">
                                    <label class="form-label">Notes</label>
                                    <textarea class="form-control" name="notes" rows="4" 
                                              placeholder="Any additional notes about this payment (e.g., remittance advice details, special terms, etc.)"></textarea>
                                </div>
                            </div>
                            
                            <div class="info-box mt-3">
                                <i class="ri-information-line me-2"></i>
                                <strong>Next Steps:</strong> After recording this payment, you can create individual allocations 
                                to doctors and/or facility for each service covered by this payment.
                            </div>
                        </div>
                        
                        <!-- Form Actions -->
                        <div class="form-card">
                            <div class="d-flex justify-content-between align-items-center">
                                <a href="list_bulk_payments.php" class="btn btn-secondary">
                                    <i class="ri-close-line me-1"></i>Cancel
                                </a>
                                <button type="submit" class="btn btn-success">
                                    <i class="ri-save-line me-1"></i>Record Payment
                                </button>
                            </div>
                        </div>
                        
                    </form>
                    
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Initialize Flatpickr
            flatpickr('.datepicker', {
                dateFormat: 'Y-m-d',
                allowInput: true,
                maxDate: 'today'
            });
            
            // Provider selection
            const providerSelect = document.getElementById('providerSelect');
            const providerInfo = document.getElementById('providerInfo');
            
            providerSelect.addEventListener('change', function() {
                const selected = this.options[this.selectedIndex];
                if (this.value) {
                    document.getElementById('infoTerms').textContent = selected.dataset.terms;
                    document.getElementById('infoBalance').textContent = 
                        'KES ' + parseFloat(selected.dataset.balance).toLocaleString('en-US', {
                            minimumFractionDigits: 2,
                            maximumFractionDigits: 2
                        });
                    providerInfo.classList.remove('hidden');
                } else {
                    providerInfo.classList.add('hidden');
                }
            });
            
            // Payment method selection
            const methodOptions = document.querySelectorAll('.method-option');
            const bankTransferFields = document.getElementById('bankTransferFields');
            const chequeFields = document.getElementById('chequeFields');
            const mpesaFields = document.getElementById('mpesaFields');
            const otherFields = document.getElementById('otherFields');
            
            methodOptions.forEach(option => {
                option.addEventListener('click', function() {
                    methodOptions.forEach(opt => opt.classList.remove('active'));
                    this.classList.add('active');
                    const radio = this.querySelector('input[type="radio"]');
                    radio.checked = true;
                    
                    // Hide all fields
                    bankTransferFields.classList.add('hidden');
                    chequeFields.classList.add('hidden');
                    mpesaFields.classList.add('hidden');
                    otherFields.classList.add('hidden');
                    
                    // Show relevant fields
                    const method = radio.value;
                    if (method === 'BANK_TRANSFER') {
                        bankTransferFields.classList.remove('hidden');
                    } else if (method === 'CHEQUE') {
                        chequeFields.classList.remove('hidden');
                    } else if (method === 'MOBILE_MONEY') {
                        mpesaFields.classList.remove('hidden');
                    } else {
                        otherFields.classList.remove('hidden');
                    }
                });
            });
            
            // Form validation
            document.getElementById('paymentForm').addEventListener('submit', function(e) {
                const providerId = providerSelect.value;
                const totalAmount = parseFloat(document.getElementById('totalAmount').value);
                const paymentMethod = document.querySelector('input[name="payment_method"]:checked');
                
                if (!providerId) {
                    e.preventDefault();
                    Swal.fire('Error', 'Please select a provider', 'error');
                    return false;
                }
                
                if (!totalAmount || totalAmount <= 0) {
                    e.preventDefault();
                    Swal.fire('Error', 'Please enter a valid amount', 'error');
                    return false;
                }
                
                if (!paymentMethod) {
                    e.preventDefault();
                    Swal.fire('Error', 'Please select a payment method', 'error');
                    return false;
                }
                
                // Show loading
                Swal.fire({
                    title: 'Processing...',
                    text: 'Recording bulk payment',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });
            });
        });
    </script>
</body>
</html>