<?php
/**
 * Trustee Assignments
 * Manage trustee assignments to schemes
 * Kenyan Pension & Life Insurance Management System
 */

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

requireLogin();
requirePermission('manage_trustee_assignments');

$scheme_id = $_GET['scheme_id'] ?? '';
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $scheme_id_post = $_POST['scheme_id'];
    $trustee_id = $_POST['trustee_id'];
    $role = $_POST['role'] ?? 'TRUSTEE';
    
    // Check if assignment exists
    $check = $conn->query("SELECT * FROM scheme_trustees 
                          WHERE scheme_id = $scheme_id_post AND trustee_id = $trustee_id")->fetch_assoc();
    
    if (!$check) {
        $sql = "INSERT INTO scheme_trustees (scheme_id, trustee_id, role, assigned_date, is_active)
                VALUES (?, ?, ?, CURDATE(), 1)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iis", $scheme_id_post, $trustee_id, $role);
        
        if ($stmt->execute()) {
            $message = 'Trustee assigned successfully';
            $messageType = 'success';
        } else {
            $message = 'Failed to assign trustee';
            $messageType = 'danger';
        }
    } else {
        $message = 'Trustee already assigned to this scheme';
        $messageType = 'warning';
    }
}

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

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

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

$sql = "SELECT st.*, ps.scheme_name, t.trustee_name, t.trustee_type
        FROM scheme_trustees st
        INNER JOIN pension_schemes ps ON st.scheme_id = ps.scheme_id
        INNER JOIN trustees t ON st.trustee_id = t.trustee_id
        WHERE $whereClause
        ORDER BY ps.scheme_name, st.assigned_date DESC";

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

$schemes = $conn->query("SELECT scheme_id, scheme_name FROM pension_schemes WHERE is_active = 1 ORDER BY scheme_name")->fetch_all(MYSQLI_ASSOC);
$trustees = $conn->query("SELECT trustee_id, trustee_name FROM trustees WHERE is_active = 1 ORDER BY trustee_name")->fetch_all(MYSQLI_ASSOC);

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Trustee Assignments')); ?>
    <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, #6366f1 0%, #4f46e5 100%); margin-bottom: 2rem;">
                        <div class="welcome-content">
                            <div class="welcome-text">
                                <h2>Trustee Assignments</h2>
                                <p>Manage trustee assignments to pension schemes</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-4">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Assign Trustee</h4>
                                </div>
                                <div class="page-card-body">
                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Scheme <span class="text-danger">*</span></label>
                                            <select name="scheme_id" class="form-select" required>
                                                <option value="">Select Scheme</option>
                                                <?php foreach ($schemes as $scheme): ?>
                                                    <option value="<?php echo $scheme['scheme_id']; ?>">
                                                        <?php echo htmlspecialchars($scheme['scheme_name']); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Trustee <span class="text-danger">*</span></label>
                                            <select name="trustee_id" class="form-select" required>
                                                <option value="">Select Trustee</option>
                                                <?php foreach ($trustees as $trustee): ?>
                                                    <option value="<?php echo $trustee['trustee_id']; ?>">
                                                        <?php echo htmlspecialchars($trustee['trustee_name']); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Role</label>
                                            <select name="role" class="form-select">
                                                <option value="TRUSTEE">Trustee</option>
                                                <option value="CHAIRPERSON">Chairperson</option>
                                                <option value="SECRETARY">Secretary</option>
                                            </select>
                                        </div>
                                        
                                        <button type="submit" class="btn btn-primary w-100">
                                            <i class="ri-user-add-line me-2"></i>Assign Trustee
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-8">
                            <div class="page-card">
                                <div class="page-card-header">
                                    <h4 class="page-card-title">Current Assignments</h4>
                                </div>
                                <div class="page-card-body">
                                    <form method="GET" class="mb-3">
                                        <select name="scheme_id" class="form-select" style="width: auto;">
                                            <option value="">All Schemes</option>
                                            <?php foreach ($schemes as $scheme): ?>
                                                <option value="<?php echo $scheme['scheme_id']; ?>" <?php echo $scheme_id == $scheme['scheme_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($scheme['scheme_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <button type="submit" class="btn btn-secondary">Filter</button>
                                    </form>
                                    
                                    <div class="table-responsive">
                                        <table class="data-table">
                                            <thead>
                                                <tr>
                                                    <th>Scheme</th>
                                                    <th>Trustee</th>
                                                    <th>Role</th>
                                                    <th>Assigned Date</th>
                                                    <th>Status</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($assignments)): ?>
                                                    <tr><td colspan="6" class="text-center">No assignments found</td></tr>
                                                <?php else: ?>
                                                    <?php foreach ($assignments as $assign): ?>
                                                        <tr>
                                                            <td><?php echo htmlspecialchars($assign['scheme_name']); ?></td>
                                                            <td><?php echo htmlspecialchars($assign['trustee_name']); ?></td>
                                                            <td><span class="badge bg-info"><?php echo htmlspecialchars($assign['role']); ?></span></td>
                                                            <td><?php echo date('d M Y', strtotime($assign['assigned_date'])); ?></td>
                                                            <td><span class="status-badge status-<?php echo $assign['is_active'] ? 'active' : 'pending'; ?>"><?php echo $assign['is_active'] ? 'Active' : 'Inactive'; ?></span></td>
                                                            <td>
                                                                <a href="trustee_assignment_details.php?id=<?php echo $assign['assignment_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>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
