<?php
/**
 * Process Retirement
 * Process and approve retirement withdrawals
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('process_retirement');

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

if (!$request_id) {
    header('Location: retirement_requests.php');
    exit();
}

// Get withdrawal request
$request = $conn->query("SELECT wr.*, m.member_number, m.first_name, m.last_name, m.date_of_birth, 
                         ps.scheme_name, ps.retirement_commutation_percentage, ps.retirement_balance_action,
                         ma.accrued_benefits, ma.available_balance
                         FROM withdrawal_requests wr
                         INNER JOIN members m ON wr.member_id = m.member_id
                         LEFT JOIN pension_schemes ps ON wr.scheme_id = ps.scheme_id
                         LEFT JOIN member_accounts ma ON wr.member_id = ma.member_id
                         WHERE wr.request_id = $request_id")->fetch_assoc();

if (!$request) {
    header('Location: retirement_requests.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];
    $approver_id = $_SESSION['user_id'];
    
    if ($action === 'approve') {
        // Calculate withdrawal amount using stored procedure
        $calcSql = "CALL sp_calculate_withdrawal_amount(?, ?, CURDATE(), @calculated_amount, @rejection_reason)";
        $calcStmt = $conn->prepare($calcSql);
        $calcStmt->bind_param("is", $request_id, $request['withdrawal_type']);
        $calcStmt->execute();
        $calcStmt->close();
        
        $result = $conn->query("SELECT @calculated_amount as calculated_amount, @rejection_reason as rejection_reason");
        $calcResult = $result->fetch_assoc();
        
        if ($calcResult['calculated_amount'] > 0) {
            // Update request
            $updateSql = "UPDATE withdrawal_requests SET 
                         status = 'APPROVED',
                         calculated_amount = ?,
                         approved_by = ?,
                         approved_date = CURDATE(),
                         approval_notes = ?
                         WHERE request_id = ?";
            $updateStmt = $conn->prepare($updateSql);
            $approval_notes = $_POST['approval_notes'] ?? null;
            $updateStmt->bind_param("diss", $calcResult['calculated_amount'], $approver_id, $approval_notes, $request_id);
            
            if ($updateStmt->execute()) {
                $message = 'Retirement request approved successfully';
                $messageType = 'success';
            } else {
                $message = 'Failed to approve request';
                $messageType = 'danger';
            }
        } else {
            $message = 'Calculation failed: ' . ($calcResult['rejection_reason'] ?? 'Unknown error');
            $messageType = 'danger';
        }
    } elseif ($action === 'reject') {
        $rejectSql = "UPDATE withdrawal_requests SET 
                     status = 'REJECTED',
                     rejection_reason = ?,
                     rejected_by = ?,
                     rejected_date = CURDATE()
                     WHERE request_id = ?";
        $rejectStmt = $conn->prepare($rejectSql);
        $rejection_reason = $_POST['rejection_reason'] ?? 'No reason provided';
        $rejectStmt->bind_param("sii", $rejection_reason, $approver_id, $request_id);
        
        if ($rejectStmt->execute()) {
            $message = 'Retirement request rejected';
            $messageType = 'success';
        } else {
            $message = 'Failed to reject request';
            $messageType = 'danger';
        }
    }
    
    // Refresh request data
    $request = $conn->query("SELECT wr.*, m.member_number, m.first_name, m.last_name, m.date_of_birth, 
                             ps.scheme_name, ps.retirement_commutation_percentage, ps.retirement_balance_action,
                             ma.accrued_benefits, ma.available_balance
                             FROM withdrawal_requests wr
                             INNER JOIN members m ON wr.member_id = m.member_id
                             LEFT JOIN pension_schemes ps ON wr.scheme_id = ps.scheme_id
                             LEFT JOIN member_accounts ma ON wr.member_id = ma.member_id
                             WHERE wr.request_id = $request_id")->fetch_assoc();
}

$pageTitle = 'Process Retirement';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Process Retirement')); ?>
    <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, #10b981 0%, #059669 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Process Retirement Request</h2>
                                <p>Review and process retirement withdrawal</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">Request Details</h4>
                                </div>
                                <div class="page-card-body">
                                    <table class="table table-borderless">
                                        <tr>
                                            <td><strong>Member:</strong></td>
                                            <td><?php echo htmlspecialchars($request['member_number'] . ' - ' . $request['first_name'] . ' ' . $request['last_name']); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Scheme:</strong></td>
                                            <td><?php echo htmlspecialchars($request['scheme_name'] ?? 'N/A'); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Request Date:</strong></td>
                                            <td><?php echo date('d M Y', strtotime($request['requested_date'])); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Requested Amount:</strong></td>
                                            <td><strong>KES <?php echo number_format($request['requested_amount'], 2); ?></strong></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Accrued Benefits:</strong></td>
                                            <td>KES <?php echo number_format($request['accrued_benefits'] ?? 0, 2); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Available Balance:</strong></td>
                                            <td>KES <?php echo number_format($request['available_balance'] ?? 0, 2); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Status:</strong></td>
                                            <td><span class="status-badge status-<?php echo strtolower($request['status']); ?>"><?php echo htmlspecialchars($request['status']); ?></span></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">Process Request</h4>
                                </div>
                                <div class="page-card-body">
                                    <?php if ($request['status'] === 'PENDING'): ?>
                                        <form method="POST" id="approveForm">
                                            <input type="hidden" name="action" value="approve">
                                            <div class="mb-3">
                                                <label class="form-label">Approval Notes</label>
                                                <textarea name="approval_notes" class="form-control" rows="3"></textarea>
                                            </div>
                                            <button type="submit" class="btn btn-success w-100 mb-2">
                                                <i class="ri-check-line me-2"></i>Approve Request
                                            </button>
                                        </form>
                                        
                                        <form method="POST" id="rejectForm">
                                            <input type="hidden" name="action" value="reject">
                                            <div class="mb-3">
                                                <label class="form-label">Rejection Reason</label>
                                                <textarea name="rejection_reason" class="form-control" rows="3" required></textarea>
                                            </div>
                                            <button type="submit" class="btn btn-danger w-100">
                                                <i class="ri-close-line me-2"></i>Reject Request
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <div class="alert alert-info">
                                            <i class="ri-information-line me-2"></i>
                                            This request has been <?php echo strtolower($request['status']); ?>.
                                        </div>
                                        <?php if ($request['calculated_amount']): ?>
                                            <p><strong>Calculated Amount:</strong> KES <?php echo number_format($request['calculated_amount'], 2); ?></p>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                    
                                    <a href="retirement_requests.php" class="btn btn-secondary w-100 mt-3">
                                        <i class="ri-arrow-left-line me-2"></i>Back to Requests
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
