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

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

requireLogin();
requirePermission('view_beneficiaries');

$action = $_GET['action'] ?? 'list';
$member_id = $_GET['member_id'] ?? null;
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'create') {
        $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",
            $_POST['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';
            $action = 'list';
        } else {
            $message = 'Failed to add beneficiary';
            $messageType = 'danger';
        }
    }
}

// Get beneficiaries
$where = ["1=1"];
$params = [];
$types = '';

if ($member_id) {
    $where[] = "b.member_id = ?";
    $params[] = $member_id;
    $types .= 'i';
}

$whereClause = implode(' AND ', $where);

$sql = "SELECT b.*, m.member_number, m.first_name as member_first_name, m.last_name as member_last_name
        FROM beneficiaries b
        INNER JOIN members m ON b.member_id = m.member_id
        WHERE $whereClause
        ORDER BY b.created_at DESC";

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$beneficiaries = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get members for filter
$members = $conn->query("SELECT member_id, member_number, first_name, last_name FROM members WHERE is_active = 1 ORDER BY member_number")->fetch_all(MYSQLI_ASSOC);

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Beneficiaries Management')); ?>
    <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, #2563eb 0%, #1e40af 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Beneficiaries Management</h2>
                                <p>Manage member beneficiaries and nominees</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 mb-3">
                        <div class="col-12">
                            <a href="beneficiaries.php?action=create" class="btn btn-primary">
                                <i class="ri-user-add-line me-2"></i>Add Beneficiary
                            </a>
                        </div>
                    </div>

                    <?php if ($action === 'create'): ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Add New Beneficiary</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <form method="POST">
                                            <div class="row">
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Member <span class="text-danger">*</span></label>
                                                    <select name="member_id" class="form-select" required>
                                                        <option value="">Select Member</option>
                                                        <?php foreach ($members as $m): ?>
                                                            <option value="<?php echo $m['member_id']; ?>" <?php echo $member_id == $m['member_id'] ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($m['member_number'] . ' - ' . $m['first_name'] . ' ' . $m['last_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <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>
                                            <div class="row">
                                                <div class="col-md-4 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-4 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 class="col-md-4 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="100" required>
                                                </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">Save Beneficiary</button>
                                            <a href="beneficiaries.php" class="btn btn-secondary">Cancel</a>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <div class="row">
                            <div class="col-12">
                                <div class="page-card">
                                    <div class="page-card-header">
                                        <h4 class="page-card-title">Beneficiaries List</h4>
                                    </div>
                                    <div class="page-card-body">
                                        <form method="GET" class="mb-3">
                                            <div class="row">
                                                <div class="col-md-4 mb-2">
                                                    <select name="member_id" class="form-select">
                                                        <option value="">All Members</option>
                                                        <?php foreach ($members as $m): ?>
                                                            <option value="<?php echo $m['member_id']; ?>" <?php echo $member_id == $m['member_id'] ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($m['member_number'] . ' - ' . $m['first_name'] . ' ' . $m['last_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-2 mb-2">
                                                    <button type="submit" class="btn btn-primary w-100">Filter</button>
                                                </div>
                                            </div>
                                        </form>
                                        
                                        <div class="table-responsive">
                                            <table class="data-table">
                                                <thead>
                                                    <tr>
                                                        <th>Member</th>
                                                        <th>Beneficiary Name</th>
                                                        <th>Relationship</th>
                                                        <th>Allocation %</th>
                                                        <th>National ID</th>
                                                        <th>Phone</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php if (empty($beneficiaries)): ?>
                                                        <tr><td colspan="7" class="text-center">No beneficiaries found</td></tr>
                                                    <?php else: ?>
                                                        <?php foreach ($beneficiaries as $ben): ?>
                                                            <tr>
                                                                <td><?php echo htmlspecialchars($ben['member_number'] . ' - ' . $ben['member_first_name'] . ' ' . $ben['member_last_name']); ?></td>
                                                                <td><?php echo htmlspecialchars($ben['first_name'] . ' ' . $ben['last_name']); ?></td>
                                                                <td><?php echo htmlspecialchars($ben['relationship']); ?></td>
                                                                <td><?php echo number_format($ben['allocation_percentage'], 2); ?>%</td>
                                                                <td><?php echo htmlspecialchars($ben['national_id'] ?? 'N/A'); ?></td>
                                                                <td><?php echo htmlspecialchars($ben['phone_number'] ?? 'N/A'); ?></td>
                                                                <td>
                                                                    <a href="beneficiary_details.php?id=<?php echo $ben['beneficiary_id']; ?>" class="btn btn-sm btn-info">
                                                                        <i class="ri-eye-line"></i>
                                                                    </a>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
