<?php
/**
 * Process Payout
 * Process and execute payouts (withdrawals, claims, etc.)
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('process_payouts');

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

if (!$payout_id) {
    header('Location: payouts.php');
    exit();
}

// Get payout details
$payout = $conn->query("SELECT p.*, 
                       CASE 
                           WHEN p.payout_type = 'WITHDRAWAL' THEN wr.member_id
                           WHEN p.payout_type = 'CLAIM' THEN lc.member_id
                           WHEN p.payout_type = 'SURRENDER' THEN sr.member_id
                           ELSE NULL
                       END as member_id,
                       CASE 
                           WHEN p.payout_type = 'WITHDRAWAL' THEN CONCAT(m1.member_number, ' - ', m1.first_name, ' ', m1.last_name)
                           WHEN p.payout_type = 'CLAIM' THEN CONCAT(m2.member_number, ' - ', m2.first_name, ' ', m2.last_name)
                           WHEN p.payout_type = 'SURRENDER' THEN CONCAT(m3.member_number, ' - ', m3.first_name, ' ', m3.last_name)
                           ELSE 'N/A'
                       END as member_name
                       FROM payouts p
                       LEFT JOIN withdrawal_requests wr ON p.reference_id = wr.request_id AND p.payout_type = 'WITHDRAWAL'
                       LEFT JOIN members m1 ON wr.member_id = m1.member_id
                       LEFT JOIN life_claims lc ON p.reference_id = lc.claim_id AND p.payout_type = 'CLAIM'
                       LEFT JOIN members m2 ON lc.member_id = m2.member_id
                       LEFT JOIN surrender_requests sr ON p.reference_id = sr.surrender_id AND p.payout_type = 'SURRENDER'
                       LEFT JOIN members m3 ON sr.member_id = m3.member_id
                       WHERE p.payout_id = $payout_id")->fetch_assoc();

if (!$payout) {
    header('Location: payouts.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];
    $processor_id = $_SESSION['user_id'];
    
    if ($action === 'process') {
        $payment_method = $_POST['payment_method'];
        $transaction_reference = $_POST['transaction_reference'] ?? null;
        $payment_date = $_POST['payment_date'] ?? date('Y-m-d');
        
        $updateSql = "UPDATE payouts SET 
                     status = 'PROCESSED',
                     payment_method = ?,
                     transaction_reference = ?,
                     payment_date = ?,
                     processed_by = ?,
                     processed_at = CURRENT_TIMESTAMP,
                     payment_notes = ?
                     WHERE payout_id = ?";
        $updateStmt = $conn->prepare($updateSql);
        $payment_notes = $_POST['payment_notes'] ?? null;
        $updateStmt->bind_param("sssisi", $payment_method, $transaction_reference, $payment_date, $processor_id, $payment_notes, $payout_id);
        
        if ($updateStmt->execute()) {
            // Update related request/claim status
            if ($payout['payout_type'] === 'WITHDRAWAL') {
                $conn->query("UPDATE withdrawal_requests SET status = 'PROCESSED' WHERE request_id = {$payout['reference_id']}");
            } elseif ($payout['payout_type'] === 'CLAIM') {
                $conn->query("UPDATE life_claims SET claim_status = 'PAID' WHERE claim_id = {$payout['reference_id']}");
            } elseif ($payout['payout_type'] === 'SURRENDER') {
                $conn->query("UPDATE surrender_requests SET status = 'PROCESSED' WHERE surrender_id = {$payout['reference_id']}");
            }
            
            $message = 'Payout processed successfully';
            $messageType = 'success';
        } else {
            $message = 'Failed to process payout';
            $messageType = 'danger';
        }
    }
    
    // Refresh payout data
    $payout = $conn->query("SELECT p.*, 
                           CASE 
                               WHEN p.payout_type = 'WITHDRAWAL' THEN wr.member_id
                               WHEN p.payout_type = 'CLAIM' THEN lc.member_id
                               WHEN p.payout_type = 'SURRENDER' THEN sr.member_id
                               ELSE NULL
                           END as member_id,
                           CASE 
                               WHEN p.payout_type = 'WITHDRAWAL' THEN CONCAT(m1.member_number, ' - ', m1.first_name, ' ', m1.last_name)
                               WHEN p.payout_type = 'CLAIM' THEN CONCAT(m2.member_number, ' - ', m2.first_name, ' ', m2.last_name)
                               WHEN p.payout_type = 'SURRENDER' THEN CONCAT(m3.member_number, ' - ', m3.first_name, ' ', m3.last_name)
                               ELSE 'N/A'
                           END as member_name
                           FROM payouts p
                           LEFT JOIN withdrawal_requests wr ON p.reference_id = wr.request_id AND p.payout_type = 'WITHDRAWAL'
                           LEFT JOIN members m1 ON wr.member_id = m1.member_id
                           LEFT JOIN life_claims lc ON p.reference_id = lc.claim_id AND p.payout_type = 'CLAIM'
                           LEFT JOIN members m2 ON lc.member_id = m2.member_id
                           LEFT JOIN surrender_requests sr ON p.reference_id = sr.surrender_id AND p.payout_type = 'SURRENDER'
                           LEFT JOIN members m3 ON sr.member_id = m3.member_id
                           WHERE p.payout_id = $payout_id")->fetch_assoc();
}

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Process Payout')); ?>
    <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>Process Payout</h2>
                                <p>Process and execute payout payment</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">Payout Details</h4>
                                </div>
                                <div class="page-card-body">
                                    <table class="table table-borderless">
                                        <tr>
                                            <td><strong>Payout Type:</strong></td>
                                            <td><span class="badge bg-info"><?php echo htmlspecialchars($payout['payout_type']); ?></span></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Member:</strong></td>
                                            <td><?php echo htmlspecialchars($payout['member_name'] ?? 'N/A'); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Amount:</strong></td>
                                            <td><strong style="color: #10b981; font-size: 1.25rem;">KES <?php echo number_format($payout['payout_amount'], 2); ?></strong></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Status:</strong></td>
                                            <td><span class="status-badge status-<?php echo strtolower($payout['status']); ?>"><?php echo htmlspecialchars($payout['status']); ?></span></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Created Date:</strong></td>
                                            <td><?php echo date('d M Y', strtotime($payout['created_at'])); ?></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 Payment</h4>
                                </div>
                                <div class="page-card-body">
                                    <?php if ($payout['status'] === 'PENDING'): ?>
                                        <form method="POST">
                                            <input type="hidden" name="action" value="process">
                                            <div class="mb-3">
                                                <label class="form-label">Payment Method <span class="text-danger">*</span></label>
                                                <select name="payment_method" class="form-select" required>
                                                    <option value="">Select Method</option>
                                                    <option value="MPESA">M-Pesa</option>
                                                    <option value="BANK_TRANSFER">Bank Transfer</option>
                                                    <option value="CHEQUE">Cheque</option>
                                                    <option value="CASH">Cash</option>
                                                </select>
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Transaction Reference</label>
                                                <input type="text" name="transaction_reference" class="form-control" 
                                                       placeholder="M-Pesa code, bank ref, etc.">
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Payment Date</label>
                                                <input type="date" name="payment_date" class="form-control" 
                                                       value="<?php echo date('Y-m-d'); ?>">
                                            </div>
                                            
                                            <div class="mb-3">
                                                <label class="form-label">Payment Notes</label>
                                                <textarea name="payment_notes" class="form-control" rows="3"></textarea>
                                            </div>
                                            
                                            <button type="submit" class="btn btn-success w-100">
                                                <i class="ri-check-line me-2"></i>Process Payout
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <div class="alert alert-info">
                                            <i class="ri-information-line me-2"></i>
                                            This payout has been <?php echo strtolower($payout['status']); ?>.
                                        </div>
                                        <?php if ($payout['payment_method']): ?>
                                            <p><strong>Payment Method:</strong> <?php echo htmlspecialchars($payout['payment_method']); ?></p>
                                            <?php if ($payout['transaction_reference']): ?>
                                                <p><strong>Transaction Reference:</strong> <?php echo htmlspecialchars($payout['transaction_reference']); ?></p>
                                            <?php endif; ?>
                                            <?php if ($payout['payment_date']): ?>
                                                <p><strong>Payment Date:</strong> <?php echo date('d M Y', strtotime($payout['payment_date'])); ?></p>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                    
                                    <a href="payouts.php" class="btn btn-secondary w-100 mt-3">
                                        <i class="ri-arrow-left-line me-2"></i>Back to Payouts
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
