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

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

// Require login and appropriate permissions
requireLogin();
requirePermission('view_members');

// Initialize services
$memberService = new MemberService($conn);

// Handle actions
$action = $_GET['action'] ?? 'list';
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($action === 'create') {
        $result = $memberService->createMember($_POST);
        if ($result['success']) {
            $message = $result['message'];
            $messageType = 'success';
            $action = 'list'; // Switch to list view after creation
        } else {
            $message = $result['message'];
            $messageType = 'danger';
        }
    } elseif ($action === 'update') {
        $member_id = $_POST['member_id'] ?? 0;
        $result = $memberService->updateMember($member_id, $_POST);
        if ($result['success']) {
            $message = $result['message'];
            $messageType = 'success';
            $action = 'list';
        } else {
            $message = $result['message'];
            $messageType = 'danger';
        }
    }
}

// Get filters
$filters = [
    'scheme_id' => $_GET['scheme_id'] ?? '',
    'employer_id' => $_GET['employer_id'] ?? '',
    'employment_status' => $_GET['employment_status'] ?? '',
    'search' => $_GET['search'] ?? ''
];

$page = $_GET['page'] ?? 1;
$perPage = 20;

// Get members list
$membersData = $memberService->getMembers($filters, $page, $perPage);
$members = $membersData['members'];
$pagination = $membersData['pagination'];

// Get schemes for filter
$schemesSql = "SELECT scheme_id, scheme_name FROM pension_schemes WHERE is_active = 1 ORDER BY scheme_name";
$schemes = $conn->query($schemesSql)->fetch_all(MYSQLI_ASSOC);

// Get employers for filter
$employersSql = "SELECT employer_id, employer_name FROM employers WHERE is_active = 1 ORDER BY employer_name";
$employers = $conn->query($employersSql)->fetch_all(MYSQLI_ASSOC);

// Include dashboard header
$pageTitle = 'Members Management';
include 'layouts/topbar.php';
?>

<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 Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0 font-size-18">Members Management</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Home</a></li>
                                        <li class="breadcrumb-item active">Members</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if ($message): ?>
                    <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($message); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                    <?php endif; ?>

                    <!-- Action Buttons -->
                    <div class="row mb-3">
                        <div class="col-12">
                            <a href="members.php?action=create" class="btn btn-primary">
                                <i class="ri-user-add-line me-2"></i>Add New Member
                            </a>
                            <button class="btn btn-success" onclick="exportMembers()">
                                <i class="ri-download-line me-2"></i>Export
                            </button>
                        </div>
                    </div>

                    <?php if ($action === 'create' || $action === 'edit'): ?>
                        <!-- Member Form -->
                        <div class="row">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h4 class="card-title"><?php echo $action === 'create' ? 'Add New Member' : 'Edit Member'; ?></h4>
                                    </div>
                                    <div class="card-body">
                                        <form method="POST" id="member-form">
                                            <?php if ($action === 'edit'): ?>
                                                <input type="hidden" name="member_id" value="<?php echo $_GET['id'] ?? ''; ?>">
                                            <?php endif; ?>
                                            
                                            <div class="row">
                                                <div class="col-md-6 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="col-md-6 mb-3">
                                                    <label class="form-label">Member Number <span class="text-danger">*</span></label>
                                                    <input type="text" name="member_number" class="form-control" required>
                                                </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">Middle Name</label>
                                                    <input type="text" name="middle_name" class="form-control">
                                                </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>
                                            
                                            <div class="row">
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Date of Birth <span class="text-danger">*</span></label>
                                                    <input type="date" name="date_of_birth" class="form-control" required>
                                                </div>
                                                
                                                <div class="col-md-4 mb-3">
                                                    <label class="form-label">Gender</label>
                                                    <select name="gender" class="form-select">
                                                        <option value="">Select</option>
                                                        <option value="MALE">Male</option>
                                                        <option value="FEMALE">Female</option>
                                                        <option value="OTHER">Other</option>
                                                    </select>
                                                </div>
                                                
                                                <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>
                                            
                                            <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">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">Employment Status</label>
                                                    <select name="employment_status" class="form-select">
                                                        <option value="ACTIVE">Active</option>
                                                        <option value="TERMINATED">Terminated</option>
                                                        <option value="RETIRED">Retired</option>
                                                        <option value="DISABLED">Disabled</option>
                                                        <option value="EMIGRATED">Emigrated</option>
                                                    </select>
                                                </div>
                                                
                                                <div class="col-md-6 mb-3">
                                                    <label class="form-label">Date of Employment</label>
                                                    <input type="date" name="date_of_employment" class="form-control">
                                                </div>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-12">
                                                    <button type="submit" class="btn btn-primary">
                                                        <i class="ri-save-line me-2"></i>Save Member
                                                    </button>
                                                    <a href="members.php" class="btn btn-secondary">Cancel</a>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <!-- Members List -->
                        <div class="row">
                            <div class="col-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h4 class="card-title">Members List</h4>
                                    </div>
                                    <div class="card-body">
                                        <!-- Filters -->
                                        <form method="GET" class="mb-3">
                                            <div class="row">
                                                <div class="col-md-3 mb-2">
                                                    <input type="text" name="search" class="form-control" 
                                                           placeholder="Search..." value="<?php echo htmlspecialchars($filters['search']); ?>">
                                                </div>
                                                <div class="col-md-2 mb-2">
                                                    <select name="scheme_id" class="form-select">
                                                        <option value="">All Schemes</option>
                                                        <?php foreach ($schemes as $scheme): ?>
                                                            <option value="<?php echo $scheme['scheme_id']; ?>" 
                                                                    <?php echo $filters['scheme_id'] == $scheme['scheme_id'] ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($scheme['scheme_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                                <div class="col-md-2 mb-2">
                                                    <select name="employment_status" class="form-select">
                                                        <option value="">All Status</option>
                                                        <option value="ACTIVE" <?php echo $filters['employment_status'] === 'ACTIVE' ? 'selected' : ''; ?>>Active</option>
                                                        <option value="TERMINATED" <?php echo $filters['employment_status'] === 'TERMINATED' ? 'selected' : ''; ?>>Terminated</option>
                                                        <option value="RETIRED" <?php echo $filters['employment_status'] === 'RETIRED' ? 'selected' : ''; ?>>Retired</option>
                                                    </select>
                                                </div>
                                                <div class="col-md-2 mb-2">
                                                    <button type="submit" class="btn btn-primary w-100">Filter</button>
                                                </div>
                                                <div class="col-md-2 mb-2">
                                                    <a href="members.php" class="btn btn-secondary w-100">Reset</a>
                                                </div>
                                            </div>
                                        </form>
                                        
                                        <!-- Members Table -->
                                        <div class="table-responsive">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Member #</th>
                                                        <th>Name</th>
                                                        <th>Scheme</th>
                                                        <th>Status</th>
                                                        <th>Accrued Benefits</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php if (empty($members)): ?>
                                                        <tr>
                                                            <td colspan="6" class="text-center">No members found</td>
                                                        </tr>
                                                    <?php else: ?>
                                                        <?php foreach ($members as $member): ?>
                                                            <tr>
                                                                <td><?php echo htmlspecialchars($member['member_number']); ?></td>
                                                                <td><?php echo htmlspecialchars($member['first_name'] . ' ' . $member['last_name']); ?></td>
                                                                <td><?php echo htmlspecialchars($member['scheme_name'] ?? 'N/A'); ?></td>
                                                                <td>
                                                                    <span class="badge bg-<?php 
                                                                        echo $member['employment_status'] === 'ACTIVE' ? 'success' : 
                                                                             ($member['employment_status'] === 'RETIRED' ? 'info' : 'secondary'); 
                                                                    ?>">
                                                                        <?php echo htmlspecialchars($member['employment_status']); ?>
                                                                    </span>
                                                                </td>
                                                                <td>KES <?php echo number_format($member['accrued_benefits'] ?? 0, 2); ?></td>
                                                                <td>
                                                                    <a href="member_details.php?id=<?php echo $member['member_id']; ?>" 
                                                                       class="btn btn-sm btn-info">
                                                                        <i class="ri-eye-line"></i>
                                                                    </a>
                                                                    <a href="members.php?action=edit&id=<?php echo $member['member_id']; ?>" 
                                                                       class="btn btn-sm btn-primary">
                                                                        <i class="ri-edit-line"></i>
                                                                    </a>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    <?php endif; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                        
                                        <!-- Pagination -->
                                        <?php if ($pagination['total_pages'] > 1): ?>
                                        <nav>
                                            <ul class="pagination justify-content-center">
                                                <?php for ($i = 1; $i <= $pagination['total_pages']; $i++): ?>
                                                    <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                                                        <a class="page-link" href="?page=<?php echo $i; ?>&<?php echo http_build_query($filters); ?>">
                                                            <?php echo $i; ?>
                                                        </a>
                                                    </li>
                                                <?php endfor; ?>
                                            </ul>
                                        </nav>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
