<?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'];
    $email = $user_details['email'];
}

// Get contributor ID if passed
$contributor_id = $_GET['contributor_id'] ?? '';
$fund_id = $_GET['fund_id'] ?? '';

// Initialize response array for AJAX
$response = ['success' => false, 'message' => '', 'transaction_id' => null];

// Handle AJAX form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['ajax'])) {
    header('Content-Type: application/json');
    
    $contributor_id = $_POST['contributor_id'];
    $fund_id = $_POST['fund_id'];
    $amount = floatval($_POST['amount']);
    $payment_method = $_POST['payment_method'];
    $reference_number = $_POST['reference_number'] ?? '';
    $description = $_POST['description'] ?? '';
    $purpose = $_POST['purpose'] ?? '';
    
    // Validate withdrawal amount
    $balance_check_query = "SELECT c.current_balance, c.first_name, c.last_name, f.fund_name, f.current_balance as fund_balance
                           FROM contributors c 
                           JOIN funds f ON f.fund_id = ?
                           WHERE c.contributor_id = ?";
    $balance_stmt = $conn->prepare($balance_check_query);
    $balance_stmt->bind_param("ii", $fund_id, $contributor_id);
    $balance_stmt->execute();
    $balance_result = $balance_stmt->get_result()->fetch_assoc();
    
    if (!$balance_result) {
        $response['message'] = "Invalid contributor or fund selected.";
    } elseif ($amount <= 0) {
        $response['message'] = "Withdrawal amount must be greater than zero.";
    } elseif ($amount > $balance_result['current_balance']) {
        $response['message'] = "Insufficient balance. Available balance: KES " . number_format($balance_result['current_balance']);
    } elseif ($amount > $balance_result['fund_balance']) {
        $response['message'] = "Insufficient fund balance. Fund balance: KES " . number_format($balance_result['fund_balance']);
    } else {
        // Process withdrawal
        try {
            $conn->begin_transaction();
            
            // Generate transaction number
            $transaction_number = 'TXN' . date('Ymd') . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
            
            // Insert withdrawal transaction
            $insert_query = "INSERT INTO fund_transactions 
                           (transaction_number, fund_id, contributor_id, transaction_type, amount, 
                            transaction_date, payment_method, reference_number, description, purpose, 
                            status, processed_by, balance_after) 
                           VALUES (?, ?, ?, 'WITHDRAWAL', ?, CURDATE(), ?, ?, ?, ?, 'COMPLETED', ?, ?)";
            
            $new_balance = $balance_result['current_balance'] - $amount;
            $stmt = $conn->prepare($insert_query);
            $stmt->bind_param("siidssssis", 
                $transaction_number, $fund_id, $contributor_id, $amount,
                $payment_method, $reference_number, $description, $purpose,
                $user_id, $new_balance
            );
            
            if ($stmt->execute()) {
                $transaction_id = $conn->insert_id;
                
                // Note: Balance updates are handled by the database trigger automatically
                // No manual updates needed to avoid double-deduction
                
                $conn->commit();
                
                $response['success'] = true;
                $response['message'] = "Withdrawal processed successfully!";
                $response['transaction_id'] = $transaction_id;
                $response['transaction_number'] = $transaction_number;
                $response['amount'] = number_format($amount);
                $response['contributor_name'] = $balance_result['first_name'] . ' ' . $balance_result['last_name'];
            }
        } catch (Exception $e) {
            $conn->rollback();
            $response['message'] = "Error processing withdrawal: " . $e->getMessage();
        }
    }
    
    echo json_encode($response);
    exit();
}

// Get contributors list
$contributors_query = "SELECT c.contributor_id, c.first_name, c.last_name, c.contributor_number, c.current_balance
                      FROM contributors c 
                      WHERE c.is_active = 1 AND c.current_balance > 0
                      ORDER BY c.first_name, c.last_name";
$contributors = $conn->query($contributors_query);

// Get funds list
$funds_query = "SELECT f.fund_id, f.fund_name, f.current_balance 
               FROM funds f 
               WHERE f.is_active = 1 AND f.current_balance > 0
               ORDER BY f.fund_name";
$funds = $conn->query($funds_query);

// If contributor is preselected, get their details
$selected_contributor = null;
if ($contributor_id) {
    $contributor_query = "SELECT c.*, 
                         (SELECT COUNT(*) FROM fund_transactions ft WHERE ft.contributor_id = c.contributor_id) as total_transactions
                         FROM contributors c WHERE c.contributor_id = ?";
    $stmt = $conn->prepare($contributor_query);
    $stmt->bind_param("i", $contributor_id);
    $stmt->execute();
    $selected_contributor = $stmt->get_result()->fetch_assoc();
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Process Withdrawal - 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">
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <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, #dc2626 0%, #ef4444 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;
        }
        
        .contributor-info {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1.5rem;
            margin-bottom: 2rem;
            border: 1px solid #e2e8f0;
        }
        
        .balance-display {
            background: #dcfce7;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            border: 1px solid #bbf7d0;
        }
        
        .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: #dc2626;
            box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1);
        }
        
        .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-danger {
            background: #dc2626;
            color: white;
        }
        
        .btn-danger:hover {
            background: #b91c1c;
        }
        
        .btn-danger:disabled {
            background: #9ca3af;
            cursor: not-allowed;
        }
        
        .btn-secondary {
            background: #6b7280;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #4b5563;
        }
        
        .warning-box {
            background: #fef3c7;
            border: 1px solid #fcd34d;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
            color: #92400e;
        }
        
        .required-field {
            color: #dc2626;
        }
        
        .is-invalid {
            border-color: #dc2626 !important;
            box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1) !important;
        }
        
        .invalid-feedback {
            display: block;
            color: #dc2626;
            font-size: 0.75rem;
            margin-top: 0.25rem;
        }
        
        /* Custom SweetAlert2 styling */
        .swal2-popup {
            border-radius: 12px !important;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04) !important;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif !important;
        }
        
        .swal2-title {
            font-size: 1.5rem !important;
            font-weight: 600 !important;
        }
        
        .swal2-confirm {
            background: #dc2626 !important;
            border-radius: 8px !important;
            font-weight: 600 !important;
            padding: 0.75rem 1.5rem !important;
        }
        
        .swal2-cancel {
            background: #6b7280 !important;
            border-radius: 8px !important;
            font-weight: 600 !important;
            padding: 0.75rem 1.5rem !important;
        }
        
        .swal2-html-container {
            font-size: 0.925rem !important;
        }
        
        .loading-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9999;
            justify-content: center;
            align-items: center;
        }
        
        .loading-content {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            text-align: center;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
        }
        
        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #dc2626;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .transaction-details {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            margin: 1rem 0;
            border: 1px solid #e2e8f0;
        }
        
        .detail-row {
            display: flex;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .detail-row:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            font-weight: 500;
            color: #64748b;
        }
        
        .detail-value {
            font-weight: 600;
            color: #1e293b;
        }
        
        .amount-highlight {
            font-size: 1.25rem;
            color: #dc2626;
            font-weight: 700;
        }
        
        @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'; ?>
        
        <!-- Loading Overlay -->
        <div class="loading-overlay" id="loadingOverlay">
            <div class="loading-content">
                <div class="spinner"></div>
                <h5>Processing Withdrawal...</h5>
                <p class="text-muted">Please wait while we process your request</p>
            </div>
        </div>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">Process Withdrawal</h1>
                        <p class="page-subtitle">Process fund withdrawals for contributors</p>
                    </div>

                    <!-- Warning Box -->
                    <div class="warning-box">
                        <i class="ph-warning me-2"></i>
                        <strong>Important:</strong> Please verify all withdrawal details carefully. This action will immediately deduct funds from both the contributor's balance and the fund balance.
                    </div>

                    <!-- Withdrawal Form -->
                    <div class="form-card">
                        <h3 class="mb-4">Withdrawal Details</h3>
                        
                        <form id="withdrawalForm">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Contributor <span class="required-field">*</span></label>
                                        <select class="form-select" name="contributor_id" id="contributorSelect" required>
                                            <option value="">Select Contributor</option>
                                            <?php $contributors->data_seek(0); ?>
                                            <?php while ($contributor = $contributors->fetch_assoc()): ?>
                                                <option value="<?php echo $contributor['contributor_id']; ?>" 
                                                        data-balance="<?php echo $contributor['current_balance']; ?>"
                                                        data-name="<?php echo htmlspecialchars($contributor['first_name'] . ' ' . $contributor['last_name']); ?>"
                                                        <?php echo ($contributor_id == $contributor['contributor_id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($contributor['first_name'] . ' ' . $contributor['last_name']); ?> 
                                                    (<?php echo $contributor['contributor_number']; ?>) - 
                                                    Balance: KES <?php echo number_format($contributor['current_balance']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Fund <span class="required-field">*</span></label>
                                        <select class="form-select" name="fund_id" id="fundSelect" required>
                                            <option value="">Select Fund</option>
                                            <?php while ($fund = $funds->fetch_assoc()): ?>
                                                <option value="<?php echo $fund['fund_id']; ?>" 
                                                        data-balance="<?php echo $fund['current_balance']; ?>"
                                                        data-name="<?php echo htmlspecialchars($fund['fund_name']); ?>"
                                                        <?php echo ($fund_id == $fund['fund_id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($fund['fund_name']); ?> - 
                                                    Balance: KES <?php echo number_format($fund['current_balance']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Contributor Info Display -->
                            <div id="contributorInfo" class="contributor-info" style="display: none;">
                                <h5>Contributor Information</h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="balance-display">
                                            <strong>Available Balance: KES <span id="availableBalance">0</span></strong>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div id="contributorDetails"></div>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Withdrawal Amount (KES) <span class="required-field">*</span></label>
                                        <input type="number" class="form-control" name="amount" id="withdrawalAmount" 
                                               step="0.01" min="1" required placeholder="Enter amount to withdraw">
                                        <div class="form-text">Maximum withdrawal: KES <span id="maxWithdrawal">0</span></div>
                                        <div class="invalid-feedback" id="amountError"></div>
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Payment Method <span class="required-field">*</span></label>
                                        <select class="form-select" name="payment_method" id="paymentMethod" required>
                                            <option value="">Select Payment Method</option>
                                            <option value="CASH">Cash</option>
                                            <option value="BANK_TRANSFER">Bank Transfer</option>
                                            <option value="MPESA">M-Pesa</option>
                                            <option value="CHEQUE">Cheque</option>
                                            <option value="MOBILE_MONEY">Mobile Money</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Reference Number</label>
                                        <input type="text" class="form-control" name="reference_number" 
                                               placeholder="Payment reference (optional)">
                                    </div>
                                </div>
                                
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label">Purpose</label>
                                        <input type="text" class="form-control" name="purpose" 
                                               placeholder="Purpose of withdrawal (optional)">
                                    </div>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Description/Notes</label>
                                <textarea class="form-control" name="description" rows="3" 
                                          placeholder="Additional notes about this withdrawal (optional)"></textarea>
                            </div>

                            <div class="d-flex gap-3">
                                <button type="submit" class="btn btn-danger" id="submitBtn" disabled>
                                    <i class="ph-arrow-down-left me-2"></i>Process Withdrawal
                                </button>
                                <a href="list_contributors.php" class="btn btn-secondary">
                                    <i class="ph-arrow-left me-2"></i>Cancel
                                </a>
                            </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>
        $(document).ready(function() {
            let contributorBalance = 0;
            let fundBalance = 0;
            
            // Handle contributor selection
            $('#contributorSelect').on('change', function() {
                const selectedOption = $(this).find(':selected');
                contributorBalance = parseFloat(selectedOption.data('balance')) || 0;
                const contributorName = selectedOption.data('name') || '';
                
                if ($(this).val()) {
                    $('#contributorInfo').show();
                    $('#availableBalance').text(formatNumber(contributorBalance));
                    $('#maxWithdrawal').text(formatNumber(contributorBalance));
                    $('#withdrawalAmount').attr('max', contributorBalance);
                    
                    $('#contributorDetails').html(`
                        <p><strong>Name:</strong> ${contributorName}</p>
                        <p><strong>Available for Withdrawal:</strong> KES ${formatNumber(contributorBalance)}</p>
                    `);
                } else {
                    $('#contributorInfo').hide();
                    $('#withdrawalAmount').removeAttr('max');
                    contributorBalance = 0;
                }
                
                validateForm();
            });

            // Handle fund selection
            $('#fundSelect').on('change', function() {
                const selectedOption = $(this).find(':selected');
                fundBalance = parseFloat(selectedOption.data('balance')) || 0;
                validateForm();
            });

            // Validate withdrawal amount
            $('#withdrawalAmount').on('input', function() {
                validateAmount();
                validateForm();
            });

            // Validate payment method
            $('#paymentMethod').on('change', function() {
                validateForm();
            });

            function validateAmount() {
                const amount = parseFloat($('#withdrawalAmount').val()) || 0;
                const amountField = $('#withdrawalAmount');
                const errorDiv = $('#amountError');
                
                if (amount <= 0) {
                    amountField.addClass('is-invalid');
                    errorDiv.text('Amount must be greater than zero');
                    return false;
                } else if (amount > contributorBalance) {
                    amountField.addClass('is-invalid');
                    errorDiv.text(`Amount cannot exceed available balance (KES ${formatNumber(contributorBalance)})`);
                    return false;
                } else if (amount > fundBalance) {
                    amountField.addClass('is-invalid');
                    errorDiv.text(`Amount cannot exceed fund balance (KES ${formatNumber(fundBalance)})`);
                    return false;
                } else {
                    amountField.removeClass('is-invalid');
                    errorDiv.text('');
                    return true;
                }
            }

            function validateForm() {
                const contributor = $('#contributorSelect').val();
                const fund = $('#fundSelect').val();
                const amount = parseFloat($('#withdrawalAmount').val()) || 0;
                const paymentMethod = $('#paymentMethod').val();
                const isAmountValid = validateAmount();
                
                const isValid = contributor && fund && amount > 0 && paymentMethod && isAmountValid;
                $('#submitBtn').prop('disabled', !isValid);
            }

            // Form submission with SweetAlert2
            $('#withdrawalForm').on('submit', function(e) {
                e.preventDefault();
                
                const amount = parseFloat($('#withdrawalAmount').val()) || 0;
                const contributorName = $('#contributorSelect').find(':selected').data('name');
                const fundName = $('#fundSelect').find(':selected').data('name');
                const paymentMethod = $('#paymentMethod').find(':selected').text();
                const purpose = $('input[name="purpose"]').val() || 'Not specified';
                
                // Final validation
                if (!validateAmount()) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Invalid Amount',
                        text: 'Please enter a valid withdrawal amount.',
                        confirmButtonColor: '#dc2626'
                    });
                    return;
                }
                
                // Confirmation dialog with detailed information
                Swal.fire({
                    title: 'Confirm Withdrawal',
                    html: `
                        <div class="transaction-details">
                            <div class="detail-row">
                                <span class="detail-label">Contributor:</span>
                                <span class="detail-value">${contributorName}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Fund:</span>
                                <span class="detail-value">${fundName}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Amount:</span>
                                <span class="detail-value amount-highlight">KES ${formatNumber(amount)}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Payment Method:</span>
                                <span class="detail-value">${paymentMethod}</span>
                            </div>
                            <div class="detail-row">
                                <span class="detail-label">Purpose:</span>
                                <span class="detail-value">${purpose}</span>
                            </div>
                        </div>
                        <div style="margin-top: 1rem; padding: 0.75rem; background: #fef2f2; border-radius: 6px; color: #dc2626; font-weight: 600;">
                            ⚠️ This action cannot be undone!
                        </div>
                    `,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#dc2626',
                    cancelButtonColor: '#6b7280',
                    confirmButtonText: '<i class="ph-arrow-down-left me-2"></i>Yes, Process Withdrawal',
                    cancelButtonText: '<i class="ph-x me-2"></i>Cancel',
                    reverseButtons: true,
                    customClass: {
                        popup: 'swal2-popup-large'
                    }
                }).then((result) => {
                    if (result.isConfirmed) {
                        processWithdrawal();
                    }
                });
            });

            function processWithdrawal() {
                // Show loading overlay
                $('#loadingOverlay').css('display', 'flex');
                
                // Prepare form data
                const formData = new FormData($('#withdrawalForm')[0]);
                formData.append('ajax', '1');
                
                // Submit via AJAX
                $.ajax({
                    url: 'process_withdrawal.php',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    dataType: 'json',
                    timeout: 30000,
                    success: function(response) {
                        $('#loadingOverlay').hide();
                        
                        if (response.success) {
                            // Success alert with transaction details
                            Swal.fire({
                                icon: 'success',
                                title: 'Withdrawal Successful!',
                                html: `
                                    <div class="transaction-details">
                                        <div class="detail-row">
                                            <span class="detail-label">Transaction Number:</span>
                                            <span class="detail-value" style="font-family: monospace;">${response.transaction_number}</span>
                                        </div>
                                        <div class="detail-row">
                                            <span class="detail-label">Contributor:</span>
                                            <span class="detail-value">${response.contributor_name}</span>
                                        </div>
                                        <div class="detail-row">
                                            <span class="detail-label">Amount Withdrawn:</span>
                                            <span class="detail-value amount-highlight">KES ${response.amount}</span>
                                        </div>
                                    </div>
                                    <p style="margin-top: 1rem; color: #059669;">The withdrawal has been processed and balances have been updated.</p>
                                `,
                                confirmButtonColor: '#059669',
                                confirmButtonText: '<i class="ph-eye me-2"></i>View Transaction Details',
                                showCancelButton: true,
                                cancelButtonText: '<i class="ph-plus me-2"></i>Process Another Withdrawal',
                                cancelButtonColor: '#dc2626'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    window.location.href = `view_transaction.php?id=${response.transaction_id}`;
                                } else if (result.dismiss === Swal.DismissReason.cancel) {
                                    // Reset form for another withdrawal
                                    resetForm();
                                }
                            });
                        } else {
                            // Error alert
                            Swal.fire({
                                icon: 'error',
                                title: 'Withdrawal Failed',
                                text: response.message,
                                confirmButtonColor: '#dc2626',
                                confirmButtonText: 'Try Again'
                            });
                        }
                    },
                    error: function(xhr, status, error) {
                        $('#loadingOverlay').hide();
                        
                        let errorMessage = 'An unexpected error occurred. Please try again.';
                        
                        if (status === 'timeout') {
                            errorMessage = 'Request timeout. Please check your connection and try again.';
                        } else if (xhr.status === 500) {
                            errorMessage = 'Server error occurred. Please contact system administrator.';
                        }
                        
                        Swal.fire({
                            icon: 'error',
                            title: 'System Error',
                            text: errorMessage,
                            confirmButtonColor: '#dc2626',
                            footer: `<small>Error Code: ${xhr.status} - ${status}</small>`
                        });
                    }
                });
            }

            function resetForm() {
                $('#withdrawalForm')[0].reset();
                $('#contributorInfo').hide();
                $('#withdrawalAmount').removeClass('is-invalid');
                $('#amountError').text('');
                $('#submitBtn').prop('disabled', true);
                contributorBalance = 0;
                fundBalance = 0;
                
                // Show success toast
                Swal.fire({
                    toast: true,
                    position: 'top-end',
                    icon: 'info',
                    title: 'Form reset for new withdrawal',
                    showConfirmButton: false,
                    timer: 3000,
                    timerProgressBar: true
                });
            }

            // Initialize if contributor is preselected
            if ($('#contributorSelect').val()) {
                $('#contributorSelect').trigger('change');
            }
            
            if ($('#fundSelect').val()) {
                $('#fundSelect').trigger('change');
            }

            function formatNumber(num) {
                return new Intl.NumberFormat().format(num);
            }

            // Show welcome toast if first time or from URL parameter
            <?php if (isset($_GET['welcome'])): ?>
            Swal.fire({
                toast: true,
                position: 'top-end',
                icon: 'info',
                title: 'Welcome to Withdrawal Processing',
                text: 'Select a contributor and fund to begin',
                showConfirmButton: false,
                timer: 4000,
                timerProgressBar: true
            });
            <?php endif; ?>

            // Add keyboard shortcuts
            $(document).on('keydown', function(e) {
                // Ctrl/Cmd + Enter to submit form
                if ((e.ctrlKey || e.metaKey) && e.keyCode === 13) {
                    if (!$('#submitBtn').prop('disabled')) {
                        $('#withdrawalForm').submit();
                    }
                }
                
                // Escape to cancel/reset
                if (e.keyCode === 27) {
                    if ($('#withdrawalForm')[0].checkValidity()) {
                        Swal.fire({
                            title: 'Reset Form?',
                            text: 'Are you sure you want to clear all entered data?',
                            icon: 'question',
                            showCancelButton: true,
                            confirmButtonColor: '#dc2626',
                            cancelButtonColor: '#6b7280',
                            confirmButtonText: 'Yes, Reset',
                            cancelButtonText: 'Cancel'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                resetForm();
                            }
                        });
                    }
                }
            });

            // Auto-save form data to prevent loss
            let autoSaveTimer;
            $('#withdrawalForm input, #withdrawalForm select, #withdrawalForm textarea').on('input change', function() {
                clearTimeout(autoSaveTimer);
                autoSaveTimer = setTimeout(function() {
                    const formData = {
                        contributor_id: $('#contributorSelect').val(),
                        fund_id: $('#fundSelect').val(),
                        amount: $('#withdrawalAmount').val(),
                        payment_method: $('#paymentMethod').val(),
                        reference_number: $('input[name="reference_number"]').val(),
                        purpose: $('input[name="purpose"]').val(),
                        description: $('textarea[name="description"]').val()
                    };
                    
                    sessionStorage.setItem('withdrawal_form_draft', JSON.stringify(formData));
                }, 1000);
            });

            // Restore form data on page load
            const savedData = sessionStorage.getItem('withdrawal_form_draft');
            if (savedData) {
                try {
                    const formData = JSON.parse(savedData);
                    
                    if (formData.contributor_id) $('#contributorSelect').val(formData.contributor_id).trigger('change');
                    if (formData.fund_id) $('#fundSelect').val(formData.fund_id).trigger('change');
                    if (formData.amount) $('#withdrawalAmount').val(formData.amount);
                    if (formData.payment_method) $('#paymentMethod').val(formData.payment_method);
                    if (formData.reference_number) $('input[name="reference_number"]').val(formData.reference_number);
                    if (formData.purpose) $('input[name="purpose"]').val(formData.purpose);
                    if (formData.description) $('textarea[name="description"]').val(formData.description);
                    
                    validateForm();
                    
                    // Show restore notification
                    if (Object.values(formData).some(val => val)) {
                        Swal.fire({
                            toast: true,
                            position: 'top-end',
                            icon: 'info',
                            title: 'Draft restored',
                            text: 'Your previous form data has been restored',
                            showConfirmButton: false,
                            timer: 3000,
                            timerProgressBar: true
                        });
                    }
                } catch (e) {
                    console.log('Could not restore form data');
                }
            }

            // Clear saved data when form is successfully submitted..
            window.clearFormDraft = function() {
                sessionStorage.removeItem('withdrawal_form_draft');
            };

            // Add tooltips for better UX
            $('[data-bs-toggle="tooltip"]').tooltip();
            
            // Add title attributes for tooltips
            $('#contributorSelect').attr('title', 'Select the contributor who will receive the withdrawal');
            $('#fundSelect').attr('title', 'Select the fund from which money will be withdrawn');
            $('#withdrawalAmount').attr('title', 'Enter the amount to withdraw (must not exceed available balance)');
            $('#paymentMethod').attr('title', 'Choose how the payment will be made to the contributor');
        });

        // Initialize tooltips after DOM is ready
        $(function () {
            $('[title]').tooltip();
        });
    </script>

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

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