<?php
/**
 * Add Beneficiary
 * Member self-service add beneficiary
 * 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 = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Check total allocation percentage
    $existingTotal = $conn->query("SELECT COALESCE(SUM(allocation_percentage), 0) as total FROM beneficiaries WHERE member_id = $member_id")->fetch_assoc()['total'];
    $newAllocation = $_POST['allocation_percentage'];
    
    if (($existingTotal + $newAllocation) > 100) {
        $message = 'Total allocation percentage cannot exceed 100%. Current total: ' . number_format($existingTotal, 2) . '%';
        $messageType = 'warning';
    } else {
        $sql = "INSERT INTO beneficiaries (member_id, first_name, last_name, relationship, allocation_percentage, 
                                         national_id, date_of_birth, phone_number, email, address)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("isssdsssss",
            $member_id,
            $_POST['first_name'],
            $_POST['last_name'],
            $_POST['relationship'],
            $_POST['allocation_percentage'],
            $_POST['national_id'] ?? null,
            $_POST['date_of_birth'] ?? null,
            $_POST['phone_number'] ?? null,
            $_POST['email'] ?? null,
            $_POST['address'] ?? null
        );
        if ($stmt->execute()) {
            $message = 'Beneficiary added successfully';
            $messageType = 'success';
            header('Location: my_beneficiaries.php');
            exit();
        } else {
            $message = 'Failed to add beneficiary';
            $messageType = 'danger';
        }
    }
}

// Get current total allocation
$currentTotal = $conn->query("SELECT COALESCE(SUM(allocation_percentage), 0) as total FROM beneficiaries WHERE member_id = $member_id")->fetch_assoc()['total'];
$remainingAllocation = 100 - $currentTotal;

$pageTitle = 'Add Beneficiary';
include 'layouts/topbar.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Beneficiary')); ?>
    <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, #2563eb 0%, #1e40af 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Add Beneficiary</h2>
                                <p>Register a new beneficiary for your pension benefits</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-8">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Beneficiary Information</h4>
                                </div>
                                <div class="page-card-body">
                                    <div class="alert alert-info mb-4">
                                        <strong>Current Allocation:</strong> <?php echo number_format($currentTotal, 2); ?>% | 
                                        <strong>Remaining:</strong> <?php echo number_format($remainingAllocation, 2); ?>%
                                    </div>
                                    
                                    <form method="POST">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">First Name <span class="text-danger">*</span></label>
                                                <input type="text" name="first_name" class="form-control" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Last Name <span class="text-danger">*</span></label>
                                                <input type="text" name="last_name" class="form-control" required>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Relationship <span class="text-danger">*</span></label>
                                                <select name="relationship" class="form-select" required>
                                                    <option value="">Select Relationship</option>
                                                    <option value="SPOUSE">Spouse</option>
                                                    <option value="CHILD">Child</option>
                                                    <option value="PARENT">Parent</option>
                                                    <option value="SIBLING">Sibling</option>
                                                    <option value="OTHER">Other</option>
                                                </select>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Allocation Percentage (%) <span class="text-danger">*</span></label>
                                                <input type="number" name="allocation_percentage" class="form-control" 
                                                       step="0.01" min="0" max="<?php echo $remainingAllocation; ?>" required>
                                                <small class="text-muted">Maximum: <?php echo number_format($remainingAllocation, 2); ?>%</small>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">National ID</label>
                                                <input type="text" name="national_id" class="form-control">
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Date of Birth</label>
                                                <input type="date" name="date_of_birth" class="form-control">
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Phone Number</label>
                                                <input type="text" name="phone_number" class="form-control">
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Email</label>
                                                <input type="email" name="email" class="form-control">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Address</label>
                                                <textarea name="address" class="form-control" rows="2"></textarea>
                                            </div>
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-save-line me-2"></i>Save Beneficiary
                                        </button>
                                        <a href="my_beneficiaries.php" class="btn btn-secondary">Cancel</a>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
