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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Check if user has permission (Administrator or Fund Manager)
if (!in_array($role_name, ['Administrator', 'Fund Manager'])) {
    header('Location: dashboard.php');
    exit();
}

$success_message = '';
$error_message = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $fund_id = $_POST['fund_id'];
    $contributor_id = $_POST['contributor_id'];
    $amount = $_POST['amount'];
    $transaction_date = $_POST['transaction_date'];
    $payment_method = $_POST['payment_method'];
    $reference_number = $_POST['reference_number'];
    $description = $_POST['description'];
    $purpose = $_POST['purpose'];
    $expected_return_date = !empty($_POST['expected_return_date']) ? $_POST['expected_return_date'] : null;
    $interest_rate = !empty($_POST['interest_rate']) ? $_POST['interest_rate'] : 0.00;
    $receipt_number = $_POST['receipt_number'];
    $notes = $_POST['notes'];
    
    // Validate required fields
    if (empty($fund_id) || empty($contributor_id) || empty($amount) || empty($transaction_date)) {
        $error_message = "Please fill in all required fields.";
    } else {
        try {
            // Start transaction
            $conn->begin_transaction();
            
            // Get current fund balance
            $fund_balance_query = "SELECT current_balance FROM funds WHERE fund_id = ?";
            $stmt_balance = $conn->prepare($fund_balance_query);
            $stmt_balance->bind_param("i", $fund_id);
            $stmt_balance->execute();
            $fund_balance = $stmt_balance->get_result()->fetch_assoc()['current_balance'];
            
            $balance_after = $fund_balance + $amount;
            
            // Insert transaction record
            $insert_query = "INSERT INTO fund_transactions (
                fund_id, contributor_id, transaction_type, amount, transaction_date,
                payment_method, reference_number, description, purpose, 
                expected_return_date, interest_rate, status, processed_by,
                receipt_number, balance_after, notes
            ) VALUES (?, ?, 'CONTRIBUTION', ?, ?, ?, ?, ?, ?, ?, ?, 'COMPLETED', ?, ?, ?, ?)";
            
            $stmt_insert = $conn->prepare($insert_query);
            $stmt_insert->bind_param("iidssssssdisds", 
                $fund_id, $contributor_id, $amount, $transaction_date,
                $payment_method, $reference_number, $description, $purpose,
                $expected_return_date, $interest_rate, $user_id,
                $receipt_number, $balance_after, $notes
            );
            
            if ($stmt_insert->execute()) {
                $transaction_id = $stmt_insert->insert_id;
                
                // The trigger will automatically update fund and contributor balances
                
                // Log activity
                $activity_query = "INSERT INTO activity_log (user_id, action, module, record_id, record_type) 
                                  VALUES (?, 'CREATE', 'FUND_TRANSACTIONS', ?, 'CONTRIBUTION')";
                $stmt_activity = $conn->prepare($activity_query);
                $stmt_activity->bind_param("ii", $user_id, $transaction_id);
                $stmt_activity->execute();
                
                $conn->commit();
                $success_message = "Contribution recorded successfully! Transaction ID: " . $transaction_id;
                
                // Clear form data
                $_POST = array();
                
            } else {
                throw new Exception("Failed to insert transaction record");
            }
            
        } catch (Exception $e) {
            $conn->rollback();
            $error_message = "Error recording contribution: " . $e->getMessage();
        }
    }
}

// Get all active funds
$funds_query = "SELECT f.fund_id, f.fund_name, f.fund_code, fc.category_name, f.current_balance, f.status
                FROM funds f 
                LEFT JOIN fund_categories fc ON f.category_id = fc.category_id 
                WHERE f.is_active = 1 AND f.status = 'ACTIVE'
                ORDER BY f.fund_name";
$funds_result = $conn->query($funds_query);

// Get all active contributors
$contributors_query = "SELECT contributor_id, contributor_number, first_name, last_name, 
                      phone_primary, email, relationship, current_balance, trust_level
                      FROM contributors 
                      WHERE is_active = 1 
                      ORDER BY first_name, last_name";
$contributors_result = $conn->query($contributors_query);
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Record Contribution - Fund Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.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/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        .page-header {
            background: linear-gradient(135deg, #059669 0%, #10b981 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .form-section {
            margin-bottom: 2rem;
        }
        
        .section-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #059669;
            box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
        }
        
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .required {
            color: #dc2626;
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background: #059669;
            color: white;
        }
        
        .btn-primary:hover {
            background: #047857;
        }
        
        .btn-secondary {
            background: #6b7280;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #4b5563;
        }
        
        .alert {
            border-radius: 8px;
            border: none;
            padding: 1rem 1.25rem;
            margin-bottom: 1.5rem;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
            border-left: 4px solid #059669;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
            border-left: 4px solid #dc2626;
        }
        
        .contributor-info {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 0.5rem;
            display: none;
        }
        
        .fund-info {
            background: #f0fdf4;
            border: 1px solid #bbf7d0;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 0.5rem;
            display: none;
        }
        
        .info-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 0.5rem;
        }
        
        .info-label {
            font-weight: 500;
            color: #6b7280;
        }
        
        .info-value {
            font-weight: 600;
            color: #1e293b;
        }
        
        .select2-container--default .select2-selection--single {
            height: 48px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 46px;
            padding-left: 12px;
        }
        
        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 46px;
        }
        
        .trust-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        
        .trust-high { background: #dcfce7; color: #166534; }
        .trust-medium { background: #fef3c7; color: #92400e; }
        .trust-low { background: #fee2e2; color: #991b1b; }
        
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .form-card {
                padding: 1.5rem;
            }
            
            .page-header {
                padding: 1.5rem;
            }
        }
    </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">
                        <h1 class="page-title">Record Contribution</h1>
                        <p class="page-subtitle">Add new contribution to fund from contributor</p>
                    </div>

                    <!-- Alert Messages -->
                    <?php if ($success_message): ?>
                        <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                Swal.fire({
                                    icon: 'success',
                                    title: 'Success!',
                                    text: '<?php echo addslashes($success_message); ?>',
                                    confirmButtonColor: '#059669',
                                    timer: 5000,
                                    timerProgressBar: true
                                });
                            });
                        </script>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                        <script>
                            document.addEventListener('DOMContentLoaded', function() {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Error!',
                                    text: '<?php echo addslashes($error_message); ?>',
                                    confirmButtonColor: '#dc2626'
                                });
                            });
                        </script>
                    <?php endif; ?>

                    <!-- Contribution Form -->
                    <div class="form-card">
                        <form method="POST" id="contributionForm">
                            <!-- Basic Information Section -->
                            <div class="form-section">
                                <h3 class="section-title">Basic Information</h3>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Fund <span class="required">*</span></label>
                                        <select class="form-select" name="fund_id" id="fund_id" required>
                                            <option value="">Select Fund</option>
                                            <?php while ($fund = $funds_result->fetch_assoc()): ?>
                                                <option value="<?php echo $fund['fund_id']; ?>" 
                                                        data-balance="<?php echo $fund['current_balance']; ?>"
                                                        data-category="<?php echo $fund['category_name']; ?>"
                                                        data-code="<?php echo $fund['fund_code']; ?>">
                                                    <?php echo $fund['fund_name'] . ' (' . $fund['fund_code'] . ')'; ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                        <div class="fund-info" id="fund-info">
                                            <div class="info-item">
                                                <span class="info-label">Category:</span>
                                                <span class="info-value" id="fund-category">-</span>
                                            </div>
                                            <div class="info-item">
                                                <span class="info-label">Current Balance:</span>
                                                <span class="info-value" id="fund-balance">KES 0</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Contributor <span class="required">*</span></label>
                                        <select class="form-select" name="contributor_id" id="contributor_id" required>
                                            <option value="">Select Contributor</option>
                                            <?php while ($contributor = $contributors_result->fetch_assoc()): ?>
                                                <option value="<?php echo $contributor['contributor_id']; ?>"
                                                        data-phone="<?php echo $contributor['phone_primary']; ?>"
                                                        data-email="<?php echo $contributor['email']; ?>"
                                                        data-relationship="<?php echo $contributor['relationship']; ?>"
                                                        data-balance="<?php echo $contributor['current_balance']; ?>"
                                                        data-trust="<?php echo $contributor['trust_level']; ?>"
                                                        data-number="<?php echo $contributor['contributor_number']; ?>">
                                                    <?php echo $contributor['first_name'] . ' ' . $contributor['last_name'] . ' (' . $contributor['contributor_number'] . ')'; ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                        <div class="contributor-info" id="contributor-info">
                                            <div class="info-item">
                                                <span class="info-label">Phone:</span>
                                                <span class="info-value" id="contributor-phone">-</span>
                                            </div>
                                            <div class="info-item">
                                                <span class="info-label">Relationship:</span>
                                                <span class="info-value" id="contributor-relationship">-</span>
                                            </div>
                                            <div class="info-item">
                                                <span class="info-label">Current Balance:</span>
                                                <span class="info-value" id="contributor-balance">KES 0</span>
                                            </div>
                                            <div class="info-item">
                                                <span class="info-label">Trust Level:</span>
                                                <span class="info-value" id="contributor-trust">-</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Transaction Details Section -->
                            <div class="form-section">
                                <h3 class="section-title">Transaction Details</h3>
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Amount (KES) <span class="required">*</span></label>
                                        <input type="number" class="form-control" name="amount" step="0.01" min="1" 
                                               value="<?php echo $_POST['amount'] ?? ''; ?>" required 
                                               placeholder="Enter amount">
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Transaction Date <span class="required">*</span></label>
                                        <input type="date" class="form-control" name="transaction_date" 
                                               value="<?php echo $_POST['transaction_date'] ?? date('Y-m-d'); ?>" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label class="form-label">Payment Method <span class="required">*</span></label>
                                        <select class="form-select" name="payment_method" required>
                                            <option value="">Select Method</option>
                                            <option value="CASH" <?php echo ($_POST['payment_method'] ?? '') == 'CASH' ? 'selected' : ''; ?>>Cash</option>
                                            <option value="BANK_TRANSFER" <?php echo ($_POST['payment_method'] ?? '') == 'BANK_TRANSFER' ? 'selected' : ''; ?>>Bank Transfer</option>
                                            <option value="MPESA" <?php echo ($_POST['payment_method'] ?? '') == 'MPESA' ? 'selected' : ''; ?>>M-Pesa</option>
                                            <option value="CHEQUE" <?php echo ($_POST['payment_method'] ?? '') == 'CHEQUE' ? 'selected' : ''; ?>>Cheque</option>
                                            <option value="MOBILE_MONEY" <?php echo ($_POST['payment_method'] ?? '') == 'MOBILE_MONEY' ? 'selected' : ''; ?>>Mobile Money</option>
                                            <option value="OTHER" <?php echo ($_POST['payment_method'] ?? '') == 'OTHER' ? 'selected' : ''; ?>>Other</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Reference Number</label>
                                        <input type="text" class="form-control" name="reference_number" 
                                               value="<?php echo $_POST['reference_number'] ?? ''; ?>" 
                                               placeholder="Transaction reference number">
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Receipt Number</label>
                                        <input type="text" class="form-control" name="receipt_number" 
                                               value="<?php echo $_POST['receipt_number'] ?? ''; ?>" 
                                               placeholder="Receipt number">
                                    </div>
                                </div>
                            </div>

                            <!-- Additional Information Section -->
                            <div class="form-section">
                                <h3 class="section-title">Additional Information</h3>
                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label">Purpose</label>
                                        <input type="text" class="form-control" name="purpose" 
                                               value="<?php echo $_POST['purpose'] ?? ''; ?>" 
                                               placeholder="Purpose of contribution">
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Expected Return Date</label>
                                        <input type="date" class="form-control" name="expected_return_date" 
                                               value="<?php echo $_POST['expected_return_date'] ?? ''; ?>">
                                        <small class="text-muted">For loans or temporary contributions</small>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Interest Rate (%)</label>
                                        <input type="number" class="form-control" name="interest_rate" 
                                               step="0.01" min="0" max="100"
                                               value="<?php echo $_POST['interest_rate'] ?? '0.00'; ?>">
                                        <small class="text-muted">If applicable</small>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label">Description</label>
                                        <textarea class="form-control" name="description" rows="3" 
                                                  placeholder="Brief description of the contribution"><?php echo $_POST['description'] ?? ''; ?></textarea>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12 mb-3">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="notes" rows="2" 
                                                  placeholder="Additional notes or comments"><?php echo $_POST['notes'] ?? ''; ?></textarea>
                                    </div>
                                </div>
                            </div>

                            <!-- Form Actions -->
                            <div class="d-flex gap-3 justify-content-end">
                                <a href="list_transactions.php" class="btn btn-secondary">
                                    <i class="ph-x me-1"></i> Cancel
                                </a>
                                <button type="submit" class="btn btn-primary" id="submitBtn">
                                    <i class="ph-check me-1"></i> Record Contribution
                                </button>
                                <!-- Fallback button for debugging -->
                                <button type="button" class="btn btn-warning d-none" id="fallbackBtn" onclick="submitFormFallback()">
                                    <i class="ph-upload me-1"></i> Submit (Fallback)
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        // Prevent conflicts with app.js
        (function($) {
            'use strict';
            
            $(document).ready(function() {
                console.log('jQuery loaded and ready');
                
                // Check if required libraries are loaded
                if (typeof Swal === 'undefined') {
                    console.error('SweetAlert2 not loaded');
                    // Show fallback button
                    $('#fallbackBtn').removeClass('d-none');
                    return;
                }
                
                // Initialize Select2
                try {
                    $('#fund_id, #contributor_id').select2({
                        width: '100%',
                        placeholder: function() {
                            return $(this).data('placeholder');
                        }
                    });
                    console.log('Select2 initialized');
                } catch (e) {
                    console.error('Select2 initialization failed:', e);
                }
                
                // Show fund information when fund is selected
                $('#fund_id').on('change', function() {
                    const selectedOption = $(this).find('option:selected');
                    if (selectedOption.val()) {
                        const balance = selectedOption.data('balance');
                        const category = selectedOption.data('category');
                        const code = selectedOption.data('code');
                        
                        $('#fund-category').text(category || '-');
                        $('#fund-balance').text('KES ' + (balance ? Number(balance).toLocaleString() : '0'));
                        $('#fund-info').show();
                    } else {
                        $('#fund-info').hide();
                    }
                });
                
                // Show contributor information when contributor is selected
                $('#contributor_id').on('change', function() {
                    const selectedOption = $(this).find('option:selected');
                    if (selectedOption.val()) {
                        const phone = selectedOption.data('phone');
                        const email = selectedOption.data('email');
                        const relationship = selectedOption.data('relationship');
                        const balance = selectedOption.data('balance');
                        const trust = selectedOption.data('trust');
                        
                        $('#contributor-phone').text(phone || '-');
                        $('#contributor-relationship').text(relationship || '-');
                        $('#contributor-balance').text('KES ' + (balance ? Number(balance).toLocaleString() : '0'));
                        
                        // Set trust level with badge
                        const trustBadge = `<span class="trust-badge trust-${trust.toLowerCase()}">${trust}</span>`;
                        $('#contributor-trust').html(trustBadge);
                        
                        $('#contributor-info').show();
                    } else {
                        $('#contributor-info').hide();
                    }
                });
                
                // Form validation and submission
                $('#contributionForm').on('submit', function(e) {
                    e.preventDefault(); // Prevent default submission
                    console.log('Form submit event triggered');
                    
                    const form = this;
                    const amount = parseFloat($('input[name="amount"]').val());
                    const fundId = $('#fund_id').val();
                    const contributorId = $('#contributor_id').val();
                    const paymentMethod = $('select[name="payment_method"]').val();
                    
                    console.log('Form data:', {amount, fundId, contributorId, paymentMethod});
                    
                    // Validation checks
                    if (!fundId) {
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                icon: 'warning',
                                title: 'Missing Information',
                                text: 'Please select a fund',
                                confirmButtonColor: '#059669'
                            });
                        } else {
                            alert('Please select a fund');
                        }
                        return false;
                    }
                    
                    if (!contributorId) {
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                icon: 'warning',
                                title: 'Missing Information',
                                text: 'Please select a contributor',
                                confirmButtonColor: '#059669'
                            });
                        } else {
                            alert('Please select a contributor');
                        }
                        return false;
                    }
                    
                    if (!amount || amount <= 0) {
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                icon: 'warning',
                                title: 'Invalid Amount',
                                text: 'Please enter a valid amount greater than 0',
                                confirmButtonColor: '#059669'
                            });
                        } else {
                            alert('Please enter a valid amount greater than 0');
                        }
                        return false;
                    }
                    
                    if (!paymentMethod) {
                        if (typeof Swal !== 'undefined') {
                            Swal.fire({
                                icon: 'warning',
                                title: 'Missing Information',
                                text: 'Please select a payment method',
                                confirmButtonColor: '#059669'
                            });
                        } else {
                            alert('Please select a payment method');
                        }
                        return false;
                    }
                    
                    // Confirmation dialog
                    if (typeof Swal !== 'undefined') {
                        Swal.fire({
                            title: 'Confirm Contribution',
                            html: `
                                <div class="text-start">
                                    <p><strong>Fund:</strong> ${$('#fund_id option:selected').text()}</p>
                                    <p><strong>Contributor:</strong> ${$('#contributor_id option:selected').text()}</p>
                                    <p><strong>Amount:</strong> KES ${amount.toLocaleString()}</p>
                                    <p><strong>Payment Method:</strong> ${paymentMethod.replace('_', ' ')}</p>
                                </div>
                            `,
                            icon: 'question',
                            showCancelButton: true,
                            confirmButtonColor: '#059669',
                            cancelButtonColor: '#6b7280',
                            confirmButtonText: 'Yes, Record Contribution',
                            cancelButtonText: 'Cancel',
                            reverseButtons: true
                        }).then((result) => {
                            if (result.isConfirmed) {
                                console.log('User confirmed submission');
                                // Show loading
                                Swal.fire({
                                    title: 'Processing...',
                                    text: 'Recording contribution, please wait',
                                    allowOutsideClick: false,
                                    allowEscapeKey: false,
                                    showConfirmButton: false,
                                    didOpen: () => {
                                        Swal.showLoading();
                                    }
                                });
                                
                                // Submit the form naturally
                                console.log('Submitting form...');
                                form.submit();
                            }
                        });
                    } else {
                        // Fallback confirmation
                        if (confirm('Are you sure you want to record this contribution?')) {
                            console.log('User confirmed submission (fallback)');
                            form.submit();
                        }
                    }
                    
                    return false;
                });
                
                // Alternative button click handler for debugging
                $('#submitBtn').on('click', function(e) {
                    console.log('Submit button clicked');
                    // Let the form submit event handle the logic
                });
                
                // Format number inputs
                $('input[name="amount"], input[name="interest_rate"]').on('input', function() {
                    let value = $(this).val();
                    if (value && !isNaN(value)) {
                        // Allow typing, but could add formatting on blur if needed
                    }
                });
                
                // Auto-generate receipt number if empty
                $('input[name="amount"], select[name="payment_method"]').on('change', function() {
                    const receiptField = $('input[name="receipt_number"]');
                    if (!receiptField.val()) {
                        const date = new Date();
                        const dateStr = date.getFullYear().toString() + 
                                       (date.getMonth() + 1).toString().padStart(2, '0') + 
                                       date.getDate().toString().padStart(2, '0');
                        const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
                        receiptField.val('RCT' + dateStr + randomNum);
                    }
                });
                
                // Enhanced number formatting
                $('input[name="amount"]').on('blur', function() {
                    let value = parseFloat($(this).val());
                    if (!isNaN(value)) {
                        $(this).val(value.toFixed(2));
                    }
                });
                
                // Payment method dependent fields
                $('select[name="payment_method"]').on('change', function() {
                    const method = $(this).val();
                    const refField = $('input[name="reference_number"]');
                    
                    // Set placeholder based on payment method
                    switch(method) {
                        case 'MPESA':
                            refField.attr('placeholder', 'M-Pesa transaction code (e.g., NLJ7RT61SV)');
                            break;
                        case 'BANK_TRANSFER':
                            refField.attr('placeholder', 'Bank reference number');
                            break;
                        case 'CHEQUE':
                            refField.attr('placeholder', 'Cheque number');
                            break;
                        case 'MOBILE_MONEY':
                            refField.attr('placeholder', 'Mobile money transaction ID');
                            break;
                        default:
                            refField.attr('placeholder', 'Transaction reference number');
                            break;
                    }
                });
                
                console.log('All event handlers attached');
            });
            
        })(jQuery);
        
        // Fallback function if SweetAlert fails
        function submitFormFallback() {
            const form = document.getElementById('contributionForm');
            const amount = document.querySelector('input[name="amount"]').value;
            const fundId = document.querySelector('#fund_id').value;
            const contributorId = document.querySelector('#contributor_id').value;
            
            if (!fundId || !contributorId || !amount) {
                alert('Please fill in all required fields');
                return false;
            }
            
            if (confirm('Are you sure you want to record this contribution?')) {
                form.submit();
            }
        }
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>