<?php
/**
 * Process Withdrawal
 * Kenyan Pension & Life Insurance Management System
 * 
 * CRITICAL: This file processes POST requests BEFORE any output
 * Structure: Session → Auth → Database → Process → Then HTML
 */

// ===================================================================
// STEP 0: START OUTPUT BUFFERING (catches any unwanted output)
// ===================================================================
ob_start();

// ===================================================================
// STEP 1: MINIMAL INCLUDES FOR PROCESSING ONLY
// ===================================================================

// Start session
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Include authentication functions
require_once 'includes/auth.php';

// Check authentication FIRST
requireLogin();
requirePermission('process_withdrawal'); // FIXED: Singular form

// Include database connection ONLY (not full layouts/main.php)
if (!isset($conn)) {
    require_once 'layouts/dbconn.php';
}

// ===================================================================
// STEP 2: GET REQUEST DATA AND VALIDATE
// ===================================================================

$request_id = $_GET['id'] ?? null;
$message = '';
$messageType = '';
$withdrawal = null;

if (!$request_id) {
    ob_end_clean(); // Clear output buffer before redirect
    header('Location: withdrawals.php');
    exit();
}

// Get withdrawal request details
$sql = "SELECT wr.*, m.member_number, m.first_name, m.last_name, m.date_of_birth,
               ps.scheme_name, ps.scheme_type, ps.retirement_age,
               ps.early_exit_max_cash_percentage,
               ma.accrued_benefits, ma.available_balance
        FROM withdrawal_requests wr
        INNER JOIN members m ON wr.member_id = m.member_id
        INNER JOIN pension_schemes ps ON wr.scheme_id = ps.scheme_id
        INNER JOIN member_accounts ma ON wr.account_id = ma.account_id
        WHERE wr.request_id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $request_id);
$stmt->execute();
$withdrawal = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$withdrawal) {
    ob_end_clean(); // Clear output buffer before redirect
    header('Location: withdrawals.php');
    exit();
}

// Calculate member age
$member_age = date_diff(date_create($withdrawal['date_of_birth']), date_create('today'))->y;

// ===================================================================
// STEP 3: PROCESS ALL POST REQUESTS (BEFORE ANY HTML OUTPUT)
// ===================================================================

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    try {
        switch ($action) {
            case 'validate':
                // ===== VALIDATE ELIGIBILITY =====
                $validateSql = "CALL sp_validate_withdrawal_eligibility(?, ?, CURDATE(), @is_eligible, @eligible_amount, @rejection_reason)";
                $validateStmt = $conn->prepare($validateSql);
                $validateStmt->bind_param("is", $withdrawal['member_id'], $withdrawal['withdrawal_type']);
                $validateStmt->execute();
                $validateStmt->close();
                
                // Get output parameters
                $result = $conn->query("SELECT @is_eligible as is_eligible, @eligible_amount as eligible_amount, @rejection_reason as rejection_reason");
                $eligibility = $result->fetch_assoc();
                
                // Update withdrawal request with eligibility results
                $updateSql = "UPDATE withdrawal_requests SET 
                             is_eligible = ?, 
                             eligible_amount = ?,
                             rejection_reason = ?
                             WHERE request_id = ?";
                $updateStmt = $conn->prepare($updateSql);
                $updateStmt->bind_param("idsi", 
                    $eligibility['is_eligible'], 
                    $eligibility['eligible_amount'],
                    $eligibility['rejection_reason'],
                    $request_id
                );
                $updateStmt->execute();
                $updateStmt->close();
                
                // Set message
                if ($eligibility['is_eligible']) {
                    $message = 'Eligibility validated successfully. Eligible amount: KES ' . number_format($eligibility['eligible_amount'], 2);
                    $messageType = 'success';
                } else {
                    $message = 'Member not eligible: ' . ($eligibility['rejection_reason'] ?? 'Unknown reason');
                    $messageType = 'danger';
                }
                
                // Refresh withdrawal data
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("i", $request_id);
                $stmt->execute();
                $withdrawal = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                
                // Recalculate member age
                $member_age = date_diff(date_create($withdrawal['date_of_birth']), date_create('today'))->y;
                break;
                
            case 'calculate':
                // ===== CALCULATE WITHDRAWAL AMOUNT =====
                $calculated_amount = $withdrawal['eligible_amount'] ?? 0;
                
                if ($calculated_amount <= 0) {
                    $message = 'Cannot calculate: No eligible amount found. Please validate eligibility first.';
                    $messageType = 'warning';
                } else {
                    // Update withdrawal request with calculated amount
                    $updateSql = "UPDATE withdrawal_requests SET 
                                 calculated_amount = ?
                                 WHERE request_id = ?";
                    $updateStmt = $conn->prepare($updateSql);
                    $updateStmt->bind_param("di", $calculated_amount, $request_id);
                    $updateStmt->execute();
                    $updateStmt->close();
                    
                    $message = 'Withdrawal amount calculated: KES ' . number_format($calculated_amount, 2);
                    $messageType = 'success';
                    
                    // Refresh withdrawal data
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("i", $request_id);
                    $stmt->execute();
                    $withdrawal = $stmt->get_result()->fetch_assoc();
                    $stmt->close();
                    
                    $member_age = date_diff(date_create($withdrawal['date_of_birth']), date_create('today'))->y;
                }
                break;
                
            case 'approve':
                // ===== APPROVE WITHDRAWAL =====
                if (!$withdrawal['calculated_amount']) {
                    $message = 'Cannot approve: Please calculate the withdrawal amount first.';
                    $messageType = 'warning';
                } else {
                    $updateSql = "UPDATE withdrawal_requests SET 
                                 status = 'APPROVED',
                                 approved_by = ?,
                                 approved_at = CURRENT_TIMESTAMP
                                 WHERE request_id = ?";
                    $updateStmt = $conn->prepare($updateSql);
                    $user_id = $_SESSION['user_id'];
                    $updateStmt->bind_param("ii", $user_id, $request_id);
                    $updateStmt->execute();
                    $updateStmt->close();
                    
                    // Log the approval
                    $audit_sql = "INSERT INTO audit_logs (event_type, event_category, member_id, event_description, amount, performed_by) 
                                  VALUES ('WITHDRAWAL_APPROVED', 'WITHDRAWAL', ?, ?, ?, ?)";
                    $audit_stmt = $conn->prepare($audit_sql);
                    $desc = "Withdrawal request #{$request_id} approved";
                    $username = $_SESSION['username'];
                    $audit_stmt->bind_param("isds", $withdrawal['member_id'], $desc, $withdrawal['calculated_amount'], $username);
                    $audit_stmt->execute();
                    $audit_stmt->close();
                    
                    $message = 'Withdrawal approved successfully. Amount: KES ' . number_format($withdrawal['calculated_amount'], 2);
                    $messageType = 'success';
                    
                    // Refresh withdrawal data
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("i", $request_id);
                    $stmt->execute();
                    $withdrawal = $stmt->get_result()->fetch_assoc();
                    $stmt->close();
                    
                    $member_age = date_diff(date_create($withdrawal['date_of_birth']), date_create('today'))->y;
                }
                break;
                
            case 'process':
                // ===== PROCESS AND COMPLETE WITHDRAWAL =====
                $payment_ref = trim($_POST['payment_reference'] ?? '');
                
                if (empty($payment_ref)) {
                    $message = 'Payment reference is required to process withdrawal.';
                    $messageType = 'danger';
                } else {
                    // Update withdrawal to PROCESSED status
                    $updateSql = "UPDATE withdrawal_requests SET 
                                 status = 'PROCESSED',
                                 processed_at = CURRENT_TIMESTAMP,
                                 payment_reference = ?
                                 WHERE request_id = ?";
                    $updateStmt = $conn->prepare($updateSql);
                    $updateStmt->bind_param("si", $payment_ref, $request_id);
                    $updateStmt->execute();
                    $updateStmt->close();
                    
                    // Update member account balance
                    $updateBalanceSql = "UPDATE member_accounts SET
                                        total_withdrawn = total_withdrawn + ?,
                                        available_balance = available_balance - ?
                                        WHERE account_id = ?";
                    $balanceStmt = $conn->prepare($updateBalanceSql);
                    $balanceStmt->bind_param("ddi", 
                        $withdrawal['calculated_amount'], 
                        $withdrawal['calculated_amount'],
                        $withdrawal['account_id']
                    );
                    $balanceStmt->execute();
                    $balanceStmt->close();
                    
                    // Log the processing
                    $audit_sql = "INSERT INTO audit_logs (event_type, event_category, member_id, event_description, amount, performed_by) 
                                  VALUES ('WITHDRAWAL_PROCESSED', 'WITHDRAWAL', ?, ?, ?, ?)";
                    $audit_stmt = $conn->prepare($audit_sql);
                    $desc = "Withdrawal request #{$request_id} processed. Payment ref: {$payment_ref}";
                    $username = $_SESSION['username'];
                    $audit_stmt->bind_param("isds", $withdrawal['member_id'], $desc, $withdrawal['calculated_amount'], $username);
                    $audit_stmt->execute();
                    $audit_stmt->close();
                    
                    // Store success message in session and redirect
                    $_SESSION['success_message'] = 'Withdrawal processed successfully. Payment reference: ' . $payment_ref;
                    
                    ob_end_clean(); // Clear output buffer before redirect
                    header('Location: withdrawals.php');
                    exit();
                }
                break;
                
            case 'reject':
                // ===== REJECT WITHDRAWAL =====
                $rejection_reason = trim($_POST['rejection_reason'] ?? '');
                
                if (empty($rejection_reason)) {
                    $message = 'Rejection reason is required.';
                    $messageType = 'danger';
                } else {
                    $updateSql = "UPDATE withdrawal_requests SET 
                                 status = 'REJECTED',
                                 rejection_reason = ?,
                                 approved_by = ?,
                                 approved_at = CURRENT_TIMESTAMP
                                 WHERE request_id = ?";
                    $updateStmt = $conn->prepare($updateSql);
                    $user_id = $_SESSION['user_id'];
                    $updateStmt->bind_param("sii", $rejection_reason, $user_id, $request_id);
                    $updateStmt->execute();
                    $updateStmt->close();
                    
                    $message = 'Withdrawal request rejected.';
                    $messageType = 'warning';
                    
                    // Refresh withdrawal data
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("i", $request_id);
                    $stmt->execute();
                    $withdrawal = $stmt->get_result()->fetch_assoc();
                    $stmt->close();
                    
                    $member_age = date_diff(date_create($withdrawal['date_of_birth']), date_create('today'))->y;
                }
                break;
                
            default:
                $message = 'Invalid action specified.';
                $messageType = 'danger';
        }
        
    } catch (Exception $e) {
        $message = 'Error processing request: ' . $e->getMessage();
        $messageType = 'danger';
        error_log("Withdrawal processing error: " . $e->getMessage());
    }
}

// ===================================================================
// STEP 4: NOW START HTML OUTPUT (All processing is complete)
// ===================================================================

// Clear output buffer and start fresh
ob_end_clean();

// Now it's safe to include layout files
$pageTitle = 'Process Withdrawal';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Process Withdrawal')); ?>
    <link rel="stylesheet" href="assets/css/pension-dashboard.css">
    <?php include 'layouts/head-css.php'; ?>
</head>

<body data-sidebar="dark">
    <div id="layout-wrapper">
        <?php include 'layouts/sidebar.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="welcome-header" style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Process Withdrawal Request</h2>
                                <p>Validate, calculate, and process pension withdrawal requests</p>
                            </div>
                        </div>
                    </div>

                    <!-- Alert Messages -->
                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                        <i class="ri-information-line me-2"></i>
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Main Content -->
                    <div class="row">
                        <!-- Left Column: Withdrawal Details -->
                        <div class="col-lg-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">
                                        <i class="ri-file-info-line me-2"></i>Withdrawal Request Details
                                    </h4>
                                </div>
                                <div class="page-card-body">
                                    <table class="table table-borderless mb-0">
                                        <tbody>
                                            <tr>
                                                <td width="40%" class="text-muted"><strong>Request ID:</strong></td>
                                                <td><span class="badge bg-secondary">#<?php echo $request_id; ?></span></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Member:</strong></td>
                                                <td><?php echo htmlspecialchars($withdrawal['member_number'] . ' - ' . $withdrawal['first_name'] . ' ' . $withdrawal['last_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Scheme:</strong></td>
                                                <td><?php echo htmlspecialchars($withdrawal['scheme_name']); ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Scheme Type:</strong></td>
                                                <td><span class="badge bg-secondary"><?php echo htmlspecialchars($withdrawal['scheme_type']); ?></span></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Withdrawal Type:</strong></td>
                                                <td><span class="badge bg-info"><?php echo htmlspecialchars($withdrawal['withdrawal_type']); ?></span></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Requested Date:</strong></td>
                                                <td><?php echo date('d M Y', strtotime($withdrawal['requested_date'])); ?></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Requested Amount:</strong></td>
                                                <td><strong>KES <?php echo number_format($withdrawal['requested_amount'], 2); ?></strong></td>
                                            </tr>
                                            <tr>
                                                <td colspan="2"><hr></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Member Age:</strong></td>
                                                <td><?php echo $member_age; ?> years</td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Retirement Age:</strong></td>
                                                <td><?php echo $withdrawal['retirement_age']; ?> years</td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Date of Birth:</strong></td>
                                                <td><?php echo date('d M Y', strtotime($withdrawal['date_of_birth'])); ?></td>
                                            </tr>
                                            <tr>
                                                <td colspan="2"><hr></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Accrued Benefits:</strong></td>
                                                <td><span class="text-primary fw-bold">KES <?php echo number_format($withdrawal['accrued_benefits'], 2); ?></span></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Available Balance:</strong></td>
                                                <td><span class="text-primary fw-bold">KES <?php echo number_format($withdrawal['available_balance'], 2); ?></span></td>
                                            </tr>
                                            <?php if ($withdrawal['eligible_amount']): ?>
                                            <tr>
                                                <td class="text-muted"><strong>Eligible Amount:</strong></td>
                                                <td><span class="text-success fw-bold">KES <?php echo number_format($withdrawal['eligible_amount'], 2); ?></span></td>
                                            </tr>
                                            <?php endif; ?>
                                            <?php if ($withdrawal['calculated_amount']): ?>
                                            <tr>
                                                <td class="text-muted"><strong>Calculated Amount:</strong></td>
                                                <td><span class="text-success fw-bold fs-5">KES <?php echo number_format($withdrawal['calculated_amount'], 2); ?></span></td>
                                            </tr>
                                            <?php endif; ?>
                                            <tr>
                                                <td colspan="2"><hr></td>
                                            </tr>
                                            <tr>
                                                <td class="text-muted"><strong>Current Status:</strong></td>
                                                <td>
                                                    <span class="badge bg-<?php 
                                                        echo $withdrawal['status'] === 'PROCESSED' ? 'success' : 
                                                             ($withdrawal['status'] === 'APPROVED' ? 'info' : 
                                                             ($withdrawal['status'] === 'REJECTED' ? 'danger' : 'warning')); 
                                                    ?>">
                                                        <?php echo htmlspecialchars($withdrawal['status']); ?>
                                                    </span>
                                                </td>
                                            </tr>
                                            <?php if ($withdrawal['rejection_reason']): ?>
                                            <tr>
                                                <td class="text-muted"><strong>Rejection Reason:</strong></td>
                                                <td><span class="text-danger"><?php echo htmlspecialchars($withdrawal['rejection_reason']); ?></span></td>
                                            </tr>
                                            <?php endif; ?>
                                            <?php if ($withdrawal['payment_reference']): ?>
                                            <tr>
                                                <td class="text-muted"><strong>Payment Reference:</strong></td>
                                                <td><code><?php echo htmlspecialchars($withdrawal['payment_reference']); ?></code></td>
                                            </tr>
                                            <?php endif; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Right Column: Processing Actions -->
                        <div class="col-lg-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">
                                        <i class="ri-settings-3-line me-2"></i>Processing Actions
                                    </h4>
                                </div>
                                <div class="page-card-body">
                                    
                                    <?php if ($withdrawal['status'] === 'PENDING'): ?>
                                        
                                        <!-- Step 1: Validate Eligibility -->
                                        <?php if (!$withdrawal['is_eligible']): ?>
                                        <div class="mb-3">
                                            <h5 class="text-primary mb-3">
                                                <span class="badge bg-primary me-2">1</span> Validate Eligibility
                                            </h5>
                                            <p class="text-muted">Check if the member is eligible for this withdrawal type.</p>
                                            <form method="POST">
                                                <input type="hidden" name="action" value="validate">
                                                <button type="submit" class="btn btn-warning w-100">
                                                    <i class="ri-checkbox-circle-line me-2"></i>Validate Eligibility
                                                </button>
                                            </form>
                                        </div>
                                        <hr>
                                        <?php endif; ?>
                                        
                                        <!-- Step 2: Calculate Amount -->
                                        <?php if ($withdrawal['is_eligible'] && !$withdrawal['calculated_amount']): ?>
                                        <div class="mb-3">
                                            <h5 class="text-primary mb-3">
                                                <span class="badge bg-primary me-2">2</span> Calculate Withdrawal Amount
                                            </h5>
                                            <p class="text-muted">Calculate the final withdrawal amount based on scheme rules.</p>
                                            <form method="POST">
                                                <input type="hidden" name="action" value="calculate">
                                                <button type="submit" class="btn btn-info w-100">
                                                    <i class="ri-calculator-line me-2"></i>Calculate Withdrawal Amount
                                                </button>
                                            </form>
                                        </div>
                                        <hr>
                                        <?php endif; ?>
                                        
                                        <!-- Step 3: Approve or Reject -->
                                        <?php if ($withdrawal['calculated_amount']): ?>
                                        <div class="mb-3">
                                            <h5 class="text-primary mb-3">
                                                <span class="badge bg-primary me-2">3</span> Approve or Reject
                                            </h5>
                                            
                                            <div class="alert alert-success mb-3">
                                                <strong>Ready for Approval</strong><br>
                                                Calculated Amount: <strong>KES <?php echo number_format($withdrawal['calculated_amount'], 2); ?></strong>
                                            </div>
                                            
                                            <form method="POST" class="mb-2">
                                                <input type="hidden" name="action" value="approve">
                                                <button type="submit" class="btn btn-primary w-100 mb-2">
                                                    <i class="ri-check-line me-2"></i>Approve Withdrawal
                                                </button>
                                            </form>
                                            
                                            <button type="button" class="btn btn-danger w-100" data-bs-toggle="modal" data-bs-target="#rejectModal">
                                                <i class="ri-close-line me-2"></i>Reject Withdrawal
                                            </button>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <!-- Show rejection if not eligible -->
                                        <?php if ($withdrawal['is_eligible'] === '0' && $withdrawal['rejection_reason']): ?>
                                        <div class="alert alert-danger">
                                            <h6 class="alert-heading">Not Eligible</h6>
                                            <p class="mb-0"><?php echo htmlspecialchars($withdrawal['rejection_reason']); ?></p>
                                        </div>
                                        <?php endif; ?>
                                        
                                    <?php elseif ($withdrawal['status'] === 'APPROVED'): ?>
                                        
                                        <!-- Step 4: Process Payment -->
                                        <div class="mb-3">
                                            <h5 class="text-success mb-3">
                                                <i class="ri-check-double-line me-2"></i>Approved - Ready for Processing
                                            </h5>
                                            
                                            <div class="alert alert-info mb-3">
                                                <strong>Approved Amount:</strong> KES <?php echo number_format($withdrawal['calculated_amount'], 2); ?>
                                            </div>
                                            
                                            <form method="POST">
                                                <input type="hidden" name="action" value="process">
                                                
                                                <div class="mb-3">
                                                    <label class="form-label"><strong>Payment Reference *</strong></label>
                                                    <input type="text" name="payment_reference" class="form-control" 
                                                           placeholder="e.g., MPESA-ABC123 or BANK-REF456" required>
                                                    <small class="text-muted">Enter M-Pesa transaction code or bank reference number</small>
                                                </div>
                                                
                                                <button type="submit" class="btn btn-success w-100">
                                                    <i class="ri-check-double-line me-2"></i>Process & Complete Withdrawal
                                                </button>
                                            </form>
                                        </div>
                                        
                                    <?php elseif ($withdrawal['status'] === 'PROCESSED'): ?>
                                        
                                        <div class="alert alert-success">
                                            <h5 class="alert-heading"><i class="ri-check-double-line me-2"></i>Completed</h5>
                                            <p>This withdrawal has been processed successfully.</p>
                                            <hr>
                                            <p class="mb-0">
                                                <strong>Amount:</strong> KES <?php echo number_format($withdrawal['calculated_amount'], 2); ?><br>
                                                <strong>Payment Reference:</strong> <?php echo htmlspecialchars($withdrawal['payment_reference'] ?? 'N/A'); ?><br>
                                                <strong>Processed:</strong> <?php echo $withdrawal['processed_at'] ? date('d M Y H:i', strtotime($withdrawal['processed_at'])) : 'N/A'; ?>
                                            </p>
                                        </div>
                                        
                                        <a href="withdrawals.php" class="btn btn-secondary w-100">
                                            <i class="ri-arrow-left-line me-2"></i>Back to Withdrawals
                                        </a>
                                        
                                    <?php elseif ($withdrawal['status'] === 'REJECTED'): ?>
                                        
                                        <div class="alert alert-danger">
                                            <h5 class="alert-heading"><i class="ri-close-circle-line me-2"></i>Rejected</h5>
                                            <p>This withdrawal request has been rejected.</p>
                                            <?php if ($withdrawal['rejection_reason']): ?>
                                            <hr>
                                            <p class="mb-0"><strong>Reason:</strong> <?php echo htmlspecialchars($withdrawal['rejection_reason']); ?></p>
                                            <?php endif; ?>
                                        </div>
                                        
                                        <a href="withdrawals.php" class="btn btn-secondary w-100">
                                            <i class="ri-arrow-left-line me-2"></i>Back to Withdrawals
                                        </a>
                                        
                                    <?php else: ?>
                                        
                                        <div class="alert alert-warning">
                                            <p class="mb-0">Unknown status: <?php echo htmlspecialchars($withdrawal['status']); ?></p>
                                        </div>
                                        
                                    <?php endif; ?>
                                    
                                </div>
                            </div>
                            
                            <!-- Quick Actions -->
                            <div class="page-card mt-3">
                                <div class="page-card-header">
                                    <h5 class="page-card-title">Quick Actions</h5>
                                </div>
                                <div class="page-card-body">
                                    <a href="withdrawals.php" class="btn btn-outline-secondary w-100 mb-2">
                                        <i class="ri-arrow-left-line me-2"></i>Back to Withdrawals List
                                    </a>
                                    <a href="member_details.php?id=<?php echo $withdrawal['member_id']; ?>" class="btn btn-outline-primary w-100 mb-2">
                                        <i class="ri-user-line me-2"></i>View Member Details
                                    </a>
                                    <a href="member_statement.php?id=<?php echo $withdrawal['member_id']; ?>" class="btn btn-outline-info w-100">
                                        <i class="ri-file-text-line me-2"></i>View Member Statement
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <!-- Rejection Modal -->
    <div class="modal fade" id="rejectModal" tabindex="-1" aria-labelledby="rejectModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="rejectModalLabel">Reject Withdrawal Request</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="reject">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Rejection Reason *</label>
                            <textarea name="rejection_reason" class="form-control" rows="4" 
                                      placeholder="Enter reason for rejecting this withdrawal request..." required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">
                            <i class="ri-close-line me-2"></i>Reject Request
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>