<?php
/**
 * Process Life Insurance Claim
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('process_claims');

$lifeService = new LifeInsuranceService($conn);
$claim_id = $_GET['id'] ?? null;
$message = '';
$messageType = '';

if ($claim_id) {
    // Get claim details
    $sql = "SELECT lc.*, lp.policy_number, lp.sum_assured, lp.total_bonuses_allocated,
                   m.member_number, m.first_name, m.last_name
            FROM life_claims lc
            INNER JOIN life_policies lp ON lc.policy_id = lp.policy_id
            LEFT JOIN members m ON lp.member_id = m.member_id
            WHERE lc.claim_id = ?";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $claim_id);
    $stmt->execute();
    $claim = $stmt->get_result()->fetch_assoc();
    
    if (!$claim) {
        header('Location: claims.php');
        exit();
    }
    
    // Process claim
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (isset($_POST['action']) && $_POST['action'] === 'calculate') {
            // Calculate claim amount
            $result = $lifeService->calculateClaimAmount($claim['policy_id'], $claim['claim_type']);
            
            if ($result['success']) {
                // Update claim with calculated amounts
                $updateSql = "UPDATE life_claims SET 
                             claim_amount = ?,
                             sum_assured_component = ?,
                             bonus_component = ?
                             WHERE claim_id = ?";
                $updateStmt = $conn->prepare($updateSql);
                $updateStmt->bind_param("dddi", 
                    $result['claim_amount'],
                    $result['sum_assured_component'],
                    $result['bonus_component'],
                    $claim_id
                );
                $updateStmt->execute();
                
                $message = 'Claim amount calculated: KES ' . number_format($result['claim_amount'], 2);
                $messageType = 'success';
                
                // Refresh claim data
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("i", $claim_id);
                $stmt->execute();
                $claim = $stmt->get_result()->fetch_assoc();
            }
            
        } elseif (isset($_POST['action']) && $_POST['action'] === 'approve') {
            // Approve claim
            $updateSql = "UPDATE life_claims SET 
                         claim_status = 'APPROVED',
                         approved_by = ?,
                         approved_date = CURDATE()
                         WHERE claim_id = ?";
            $updateStmt = $conn->prepare($updateSql);
            $user_id = $_SESSION['user_id'];
            $updateStmt->bind_param("ii", $user_id, $claim_id);
            $updateStmt->execute();
            
            $message = 'Claim approved successfully';
            $messageType = 'success';
            
            // Refresh claim data
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $claim_id);
            $stmt->execute();
            $claim = $stmt->get_result()->fetch_assoc();
            
        } elseif (isset($_POST['action']) && $_POST['action'] === 'process') {
            // Process claim payment
            $updateSql = "UPDATE life_claims SET 
                         claim_status = 'PAID',
                         paid_date = CURDATE(),
                         payment_reference = ?,
                         payment_method = ?
                         WHERE claim_id = ?";
            $updateStmt = $conn->prepare($updateSql);
            $payment_ref = $_POST['payment_reference'] ?? null;
            $payment_method = $_POST['payment_method'] ?? 'BANK_TRANSFER';
            $updateStmt->bind_param("ssi", $payment_ref, $payment_method, $claim_id);
            $updateStmt->execute();
            
            // Update policy status if death claim
            if ($claim['claim_type'] === 'DEATH') {
                $policyUpdateSql = "UPDATE life_policies SET policy_status = 'DEATH_CLAIM' WHERE policy_id = ?";
                $policyStmt = $conn->prepare($policyUpdateSql);
                $policyStmt->bind_param("i", $claim['policy_id']);
                $policyStmt->execute();
            }
            
            $message = 'Claim processed and paid successfully';
            $messageType = 'success';
            
            header('Location: claims.php');
            exit();
        }
    }
} else {
    header('Location: claims.php');
    exit();
}

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Process Life Insurance Claim')); ?>
    <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, #ef4444 0%, #dc2626 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Process Life Insurance Claim</h2>
                                <p>Calculate, approve, and process life insurance claims</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">Claim Details</h4>
                                </div>
                                <div class="page-card-body">
                                    <table class="table table-borderless">
                                        <tr>
                                            <td><strong>Policy Number:</strong></td>
                                            <td><?php echo htmlspecialchars($claim['policy_number']); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Claim Type:</strong></td>
                                            <td><span class="badge bg-<?php echo $claim['claim_type'] === 'DEATH' ? 'danger' : 'info'; ?>"><?php echo htmlspecialchars($claim['claim_type']); ?></span></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Sum Assured:</strong></td>
                                            <td>KES <?php echo number_format($claim['sum_assured'], 2); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Total Bonuses:</strong></td>
                                            <td>KES <?php echo number_format($claim['total_bonuses_allocated'] ?? 0, 2); ?></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Claim Amount:</strong></td>
                                            <td><strong>KES <?php echo number_format($claim['claim_amount'], 2); ?></strong></td>
                                        </tr>
                                        <tr>
                                            <td><strong>Status:</strong></td>
                                            <td>
                                                <span class="badge bg-<?php 
                                                    echo $claim['claim_status'] === 'PAID' ? 'success' : 
                                                         ($claim['claim_status'] === 'APPROVED' ? 'info' : 'warning'); 
                                                ?>">
                                                    <?php echo htmlspecialchars($claim['claim_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">Processing Actions</h4>
                                </div>
                                <div class="page-card-body">
                                    <?php if ($claim['claim_status'] === 'PENDING'): ?>
                                        <form method="POST" class="mb-3">
                                            <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 Claim Amount
                                            </button>
                                        </form>
                                        
                                        <?php if ($claim['claim_amount'] > 0): ?>
                                            <form method="POST" class="mb-3">
                                                <input type="hidden" name="action" value="approve">
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="ri-check-line me-2"></i>Approve Claim
                                                </button>
                                            </form>
                                        <?php endif; ?>
                                    <?php elseif ($claim['claim_status'] === 'APPROVED'): ?>
                                        <form method="POST">
                                            <input type="hidden" name="action" value="process">
                                            <div class="mb-3">
                                                <label class="form-label">Payment Method</label>
                                                <select name="payment_method" class="form-select" required>
                                                    <option value="MPESA">M-Pesa</option>
                                                    <option value="BANK_TRANSFER" selected>Bank Transfer</option>
                                                    <option value="CHEQUE">Cheque</option>
                                                </select>
                                            </div>
                                            <div class="mb-3">
                                                <label class="form-label">Payment Reference</label>
                                                <input type="text" name="payment_reference" class="form-control" placeholder="Payment reference number">
                                            </div>
                                            <button type="submit" class="btn btn-success w-100">
                                                <i class="ri-check-double-line me-2"></i>Process Payment
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <div class="alert alert-info">
                                            This claim has already been processed.
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
