<?php
/**
 * Request Withdrawal
 * Member self-service withdrawal request
 * Kenyan Pension & Life Insurance Management System
 */

require_once 'layouts/main.php';
require_once 'includes/auth.php';

requireLogin();
if (!isMember()) {
    header('Location: access_denied.php');
    exit();
}

$member_id = $_SESSION['member_id'] ?? $_SESSION['user_id'];
$message = '';
$messageType = '';

// Get member account
$account = $conn->query("SELECT * FROM member_accounts WHERE member_id = $member_id")->fetch_assoc();
$member = $conn->query("SELECT m.*, ps.scheme_name, ps.retirement_age FROM members m LEFT JOIN pension_schemes ps ON m.scheme_id = ps.scheme_id WHERE m.member_id = $member_id")->fetch_assoc();

if (!$account || !$member) {
    header('Location: member_portal.php');
    exit();
}

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $withdrawal_type = $_POST['withdrawal_type'];
    $requested_amount = $_POST['requested_amount'];
    
    // Validate withdrawal type eligibility
    $sql = "CALL sp_validate_withdrawal_eligibility(?, ?, CURDATE(), @is_eligible, @eligible_amount, @rejection_reason)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("is", $member_id, $withdrawal_type);
    $stmt->execute();
    $stmt->close();
    
    $result = $conn->query("SELECT @is_eligible as is_eligible, @eligible_amount as eligible_amount, @rejection_reason as rejection_reason");
    $eligibility = $result->fetch_assoc();
    
    if ($eligibility['is_eligible']) {
        // Create withdrawal request
        $insertSql = "INSERT INTO withdrawal_requests (member_id, account_id, scheme_id, withdrawal_type, requested_amount, requested_date, status)
                     VALUES (?, ?, ?, ?, ?, CURDATE(), 'PENDING')";
        $insertStmt = $conn->prepare($insertSql);
        $insertStmt->bind_param("iiisd", $member_id, $account['account_id'], $member['scheme_id'], $withdrawal_type, $requested_amount);
        
        if ($insertStmt->execute()) {
            $message = 'Withdrawal request submitted successfully. Awaiting approval.';
            $messageType = 'success';
        } else {
            $message = 'Failed to submit withdrawal request';
            $messageType = 'danger';
        }
    } else {
        $message = 'Not eligible: ' . $eligibility['rejection_reason'];
        $messageType = 'warning';
    }
}

$pageTitle = 'Request Withdrawal';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Request 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">
                    <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>Request Withdrawal</h2>
                                <p>Submit a pension withdrawal request</p>
                            </div>
                        </div>
                    </div>

                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Account Summary</h4>
                                </div>
                                <div class="page-card-body">
                                    <table class="table table-borderless">
                                        <tr>
                                            <td><strong>Available Balance:</strong></td>
                                            <td class="text-end"><strong style="color: #10b981; font-size: 1.25rem;">KES <?php echo number_format($account['available_balance'], 2); ?></strong></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Accrued Benefits:</strong></td>
                                            <td class="text-end">KES <?php echo number_format($account['accrued_benefits'], 2); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Member Age:</strong></td>
                                            <td class="text-end"><?php echo $member_age; ?> years</td>
                                        </tr>
                                        <tr>
                                            <td><strong>Retirement Age:</strong></td>
                                            <td class="text-end"><?php echo $member['retirement_age']; ?> years</td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-6">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Withdrawal Request</h4>
                                </div>
                                <div class="page-card-body">
                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Withdrawal Type <span class="text-danger">*</span></label>
                                            <select name="withdrawal_type" id="withdrawal_type" class="form-select" required>
                                                <option value="">Select Type</option>
                                                <?php if ($member_age >= $member['retirement_age']): ?>
                                                    <option value="RETIREMENT">Retirement</option>
                                                <?php else: ?>
                                                    <option value="EARLY_EXIT">Early Exit</option>
                                                <?php endif; ?>
                                                <?php if ($member['is_permanently_disabled']): ?>
                                                    <option value="DISABILITY">Disability</option>
                                                <?php endif; ?>
                                                <?php if ($member['is_emigrated']): ?>
                                                    <option value="EMIGRATION">Emigration</option>
                                                <?php endif; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Requested Amount (KES) <span class="text-danger">*</span></label>
                                            <input type="number" name="requested_amount" class="form-control" 
                                                   step="0.01" max="<?php echo $account['available_balance']; ?>" 
                                                   min="0" required>
                                            <small class="text-muted">Maximum: KES <?php echo number_format($account['available_balance'], 2); ?></small>
                                        </div>
                                        
                                        <div class="alert alert-info">
                                            <i class="ri-information-line me-2"></i>
                                            Your withdrawal request will be reviewed and processed by the scheme administrator.
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-send-plane-line me-2"></i>Submit Request
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
