<?php
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

$member_no = $_GET['member_no'] ?? '';
if (!$member_no) {
    header('Location: all_members.php');
    exit();
}

// Get member details with corporate information and category
$sql = "SELECT mi.*, pa.*, ca.anniv, c.corporate, c.scheme, c.currency,
               GROUP_CONCAT(DISTINCT mb.category) as categories
        FROM member_info mi 
        LEFT JOIN principal_applicant pa ON mi.family_no = pa.family_no
        LEFT JOIN corporate c ON mi.corp_id = c.corp_id
        LEFT JOIN corp_anniversary ca ON mi.corp_id = ca.corp_id AND ca.anniv = (
               SELECT MAX(anniv) FROM corp_anniversary WHERE corp_id = mi.corp_id
        )
        LEFT JOIN member_benefits mb ON mi.member_no = mb.member_no
        WHERE mi.member_no = ?
        GROUP BY mi.member_no";

$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $member_no);
$stmt->execute();
$member = $stmt->get_result()->fetch_assoc();

if (!$member) {
    $_SESSION['error_message'] = "Member not found";
    header('Location: all_members.php');
    exit();
}

// Check if this is the principal member
$isPrincipal = ($member['relation_to_principal'] == 1);

// Get member benefits
$sql_benefits = "SELECT 
    mb.*,
    b.benefit as benefit_name
FROM member_benefits mb
LEFT JOIN benefit b ON mb.benefit = b.code
WHERE mb.member_no = ?
ORDER BY mb.anniv DESC, b.code ASC";

$stmt_benefits = $conn->prepare($sql_benefits);
$stmt_benefits->bind_param('s', $member_no);
$stmt_benefits->execute();
$benefits = $stmt_benefits->get_result()->fetch_all(MYSQLI_ASSOC);

// Get member cancellation status
$sql_cancellation = "SELECT cancelled, date_can, reason 
                    FROM member_cancellation 
                    WHERE member_no = ? 
                    ORDER BY date_can DESC
                    LIMIT 1";
$stmt_cancellation = $conn->prepare($sql_cancellation);
$stmt_cancellation->bind_param('s', $member_no);
$stmt_cancellation->execute();
$cancellation_result = $stmt_cancellation->get_result();
$cancellation = $cancellation_result->fetch_assoc();
$is_active = true;
if ($cancellation && $cancellation['cancelled'] == 1) {
    $is_active = false;
}

// Get member anniversaries
$sql_anniversaries = "SELECT * FROM member_anniversary 
                     WHERE member_no = ? 
                     ORDER BY anniv DESC";
$stmt_anniversaries = $conn->prepare($sql_anniversaries);
$stmt_anniversaries->bind_param('s', $member_no);
$stmt_anniversaries->execute();
$anniversaries = $stmt_anniversaries->get_result()->fetch_all(MYSQLI_ASSOC);

// Get principal info if this is a dependent
$principal_info = null;
if (!$isPrincipal) {
    $sql_principal = "SELECT mi.member_no, mi.surname, mi.first_name, pa.mobile_no, pa.email
                     FROM member_info mi
                     JOIN principal_applicant pa ON mi.member_no = pa.member_no
                     WHERE mi.family_no = ? AND mi.relation_to_principal = 1";
    $stmt_principal = $conn->prepare($sql_principal);
    $stmt_principal->bind_param('s', $member['family_no']);
    $stmt_principal->execute();
    $principal_info = $stmt_principal->get_result()->fetch_assoc();
}

// Get all family members
$sql_family = "SELECT 
    mi.member_no, 
    mi.family_no,
    mi.surname, 
    mi.first_name, 
    mi.other_names,
    mi.relation_to_principal,
    mi.dob,
    mi.gender,
    mi.id_no,
    mi.cancelled as is_cancelled,
    CASE WHEN mi.cancelled = 1 THEN 0 ELSE 1 END as is_active
FROM member_info mi  
WHERE mi.family_no = ? AND mi.member_no != ?
ORDER BY mi.relation_to_principal ASC, mi.dob ASC";
        
$stmt_family = $conn->prepare($sql_family);
$stmt_family->bind_param('ss', $member['family_no'], $member_no);
$stmt_family->execute();
$family_members = $stmt_family->get_result()->fetch_all(MYSQLI_ASSOC);

// Get available categories for this corporate
$sql_categories = "SELECT DISTINCT category FROM corp_groups WHERE corp_id = ? ORDER BY category";
$stmt_categories = $conn->prepare($sql_categories);
$stmt_categories->bind_param('s', $member['corp_id']);
$stmt_categories->execute();
$categories_result = $stmt_categories->get_result();
$available_categories = [];
while ($cat = $categories_result->fetch_assoc()) {
    $available_categories[] = $cat['category'];
}

// Get corporate plan benefits
$sql_corp_benefits = "SELECT 
    cg.category, 
    cg.benefit, 
    cg.limit, 
    b.benefit as benefit_name
FROM corp_groups cg
JOIN benefit b ON cg.benefit = b.code
WHERE cg.corp_id = ?
ORDER BY cg.category, b.benefit";
$stmt_corp_benefits = $conn->prepare($sql_corp_benefits);
$stmt_corp_benefits->bind_param('s', $member['corp_id']);
$stmt_corp_benefits->execute();
$corporate_benefits = $stmt_corp_benefits->get_result()->fetch_all(MYSQLI_ASSOC);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $conn->begin_transaction();

        // Update member_info table
        $sql = "UPDATE member_info SET 
                first_name = ?,
                surname = ?,
                other_names = ?,
                dob = ?,
                gender = ?,
                id_no = ?,
                nhif_card_no = ?
                WHERE member_no = ?";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ssssssss', 
            $_POST['first_name'],
            $_POST['surname'],
            $_POST['other_names'],
            $_POST['dob'],
            $_POST['gender'],
            $_POST['id_no'],
            $_POST['nhif_no'],
            $member_no
        );
        $stmt->execute();

        // Update principal_applicant table if this is the principal
        if ($isPrincipal) {
            $sql = "UPDATE principal_applicant SET 
                    mobile_no = ?,
                    email = ?,
                    postal_add = ?,
                    pin_no = ?
                    WHERE member_no = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param('sssss',
                $_POST['mobile_no'],
                $_POST['email'],
                $_POST['postal_add'],
                $_POST['pin_no'],
                $member_no
            );
            $stmt->execute();
            
            // Update category in member_benefits if changed
            if (isset($_POST['category']) && !empty($_POST['category'])) {
                $new_category = $_POST['category'];
                $old_category = $member['categories'];
                
                if ($new_category != $old_category) {
                    // First update the principal's category
                    $sql = "UPDATE member_benefits SET 
                            category = ?
                            WHERE member_no = ?";
                    
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param('ss', $new_category, $member_no);
                    $stmt->execute();
                    
                    // Now update all dependents' categories
                    $sql = "UPDATE member_benefits mb
                            JOIN member_info mi ON mb.member_no = mi.member_no
                            SET mb.category = ?
                            WHERE mi.family_no = ? 
                            AND mi.relation_to_principal > 1";
                    
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param('ss', $new_category, $member['family_no']);
                    $stmt->execute();
                    
                    // Log the category change
                    $sql = "INSERT INTO api_category_change 
                            (member_no, category, user_id, date_entered, sync)
                            VALUES (?, ?, ?, CURDATE(), 0)";
                    
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param('sss', $member_no, $new_category, $_SESSION['user_id']);
                    $stmt->execute();
                }
            }
        }

        $conn->commit();
        $_SESSION['success_message'] = "Member updated successfully";
        header("Location: view_member.php?member_no=" . $member_no);
        exit();
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error_message'] = "Error updating member: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Member')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Sweet Alert css-->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <style>
        .member-edit-card {
            border-radius: 10px;
            box-shadow: 0 0.5rem 1.5rem rgba(0, 0, 0, 0.1);
            border: none;
        }
        
        .card-header {
            background-color: #f8f9fa;
            border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        }
        
        .card-header .back-btn {
            transition: all 0.3s ease-in-out;
        }
        
        .card-header .back-btn:hover {
            transform: translateX(-3px);
        }
        
        .member-info-section {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            border-left: 4px solid #3762ea;
        }
        
        .member-info-section .text-muted {
            font-size: 0.85rem;
        }
        
        .member-info-section input[readonly] {
            background-color: #f5f7fa;
            border-color: #e9edf3;
            font-weight: 500;
        }
        
        .form-label {
            font-weight: 500;
            margin-bottom: 8px;
            color: #495057;
        }
        
        .form-control, .form-select {
            padding: 10px 15px;
            border-radius: 6px;
            border: 1px solid #e2e8f0;
            transition: all 0.2s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #3762ea;
            box-shadow: 0 0 0 0.2rem rgba(55, 98, 234, 0.25);
        }
        
        .badge-principal {
            background-color: #3762ea;
            color: #fff;
            padding: 6px 12px;
            border-radius: 30px;
            font-size: 0.8rem;
            font-weight: 500;
            display: inline-flex;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .badge-principal i {
            margin-right: 5px;
            font-size: 0.9rem;
        }
        
        .badge-dependent {
            background-color: #6c757d;
            color: #fff;
        }
        
        .category-select {
            border-left: 3px solid #ffc107;
        }
        
        .category-info {
            color: #6c757d;
            font-size: 0.8rem;
            margin-top: 5px;
        }
        
        .btn-section {
            margin-top: 30px;
            padding-top: 20px;
            border-top: 1px solid #e9ecef;
        }
        
        .btn-primary {
            padding: 10px 25px;
            font-weight: 500;
            letter-spacing: 0.5px;
            background-color: #3762ea;
            border-color: #3762ea;
            transition: all 0.3s;
        }
        
        .btn-primary:hover {
            background-color: #2a50d2;
            border-color: #2a50d2;
            transform: translateY(-2px);
            box-shadow: 0 5px 12px rgba(55, 98, 234, 0.3);
        }
        
        .btn-secondary {
            padding: 10px 25px;
            font-weight: 500;
            letter-spacing: 0.5px;
            transition: all 0.3s;
        }
        
        .btn-secondary:hover {
            transform: translateY(-2px);
        }
        
        .personal-info-container {
            margin-top: 25px;
        }
        
        .section-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #374151;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .address-textarea {
            height: 80px;
            resize: none;
        }
        
        .info-section {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
        }
        
        .info-section i {
            font-size: 1.2rem;
            margin-right: 0.5rem;
            opacity: 0.7;
        }
        
        .info-title {
            font-size: 1rem;
            font-weight: 600;
            color: #495057;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }
        
        .info-divider {
            height: 1px;
            background-color: rgba(0, 0, 0, 0.05);
            margin: 15px 0;
        }
        
        .info-item {
            margin-bottom: 12px;
        }
        
        .info-label {
            color: #6c757d;
            font-size: 0.85rem;
            font-weight: 500;
            margin-bottom: 4px;
        }
        
        .info-value {
            color: #343a40;
            font-weight: 500;
            font-size: 0.95rem;
        }
        
        .data-table {
            border-collapse: separate;
            border-spacing: 0;
            width: 100%;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            overflow: hidden;
            margin-bottom: 20px;
        }
        
        .data-table th {
            background-color: #f8f9fa;
            font-weight: 600;
            padding: 12px 15px;
            color: #495057;
            border-bottom: 1px solid #e9ecef;
            font-size: 0.9rem;
        }
        
        .data-table td {
            padding: 10px 15px;
            vertical-align: middle;
            border-bottom: 1px solid #e9ecef;
            font-size: 0.9rem;
        }
        
        .data-table tr:last-child td {
            border-bottom: none;
        }
        
        .data-table tbody tr:hover {
            background-color: rgba(0, 0, 0, 0.01);
        }
        
        .tab-content {
            padding: 20px 0;
        }
        
        .nav-tabs {
            border-radius: 8px;
            border: none;
            background-color: #f8f9fa;
            overflow: hidden;
            padding: 2px;
            margin-bottom: 20px;
        }
        
        .nav-tabs .nav-link {
            border: none;
            color: #6c757d;
            font-weight: 500;
            padding: 12px 20px;
            border-radius: 6px;
            margin: 3px;
            transition: all 0.2s;
        }
        
        .nav-tabs .nav-link:hover {
            color: #495057;
            background: rgba(0, 0, 0, 0.03);
        }
        
        .nav-tabs .nav-link.active {
            color: #3762ea;
            background-color: #fff;
            font-weight: 600;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.08);
        }
        
        .badge {
            font-weight: 500;
            font-size: 0.8rem;
            padding: 5px 10px;
        }
        
        .benefit-tag {
            display: inline-block;
            padding: 4px 10px;
            background-color: #f8f9fa;
            border-radius: 50px;
            font-size: 0.75rem;
            font-weight: 500;
            margin-top: 5px;
        }
        
        @media (max-width: 767.98px) {
            .col-form-label {
                margin-bottom: 0.25rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Members', 'title' => 'Edit Member')); ?>

                    <div class="row justify-content-center">
                        <div class="col-xl-10">
                            <div class="card member-edit-card">
                                <div class="card-header d-flex align-items-center py-3">
                                    <h4 class="card-title mb-0 flex-grow-1">
                                        <i class="ri-user-settings-line me-2 text-primary"></i>
                                        Edit Member Information
                                    </h4>
                                    <div class="flex-shrink-0">
                                        <a href="view_member.php?member_no=<?php echo $member_no; ?>" class="btn btn-soft-primary btn-sm back-btn">
                                            <i class="ri-arrow-left-line align-middle me-1"></i> Back to Member Details
                                        </a>
                                    </div>
                                </div>
                                
                                <div class="card-body p-4">
                                    <!-- Member Summary Bar -->
                                    <div class="member-info-section">
                                        <div class="row align-items-center">
                                            <div class="col-md-12 mb-3 d-flex align-items-center">
                                                <?php if ($isPrincipal): ?>
                                                <div class="badge-principal me-2">
                                                    <i class="ri-user-star-line"></i> Principal Member
                                                </div>
                                                <?php else: ?>
                                                <div class="badge-principal badge-dependent me-2">
                                                    <i class="ri-user-follow-line"></i> Dependent
                                                </div>
                                                <?php endif; ?>
                                                
                                                <span class="badge bg-<?php echo $is_active ? 'success' : 'danger'; ?> ms-2">
                                                    <?php echo $is_active ? 'Active' : 'Suspended'; ?>
                                                </span>
                                            </div>
                                            
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label text-muted">Member No</label>
                                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($member['member_no']); ?>" readonly>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label text-muted">Family No</label>
                                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($member['family_no']); ?>" readonly>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label text-muted">Corporate</label>
                                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($member['corporate']); ?>" readonly>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label class="form-label text-muted">Scheme</label>
                                                    <input type="text" class="form-control" value="<?php echo htmlspecialchars($member['scheme']); ?>" readonly>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Tabs Navigation -->
                                    <ul class="nav nav-tabs nav-justified" role="tablist">
                                        <li class="nav-item">
                                            <a class="nav-link active" data-bs-toggle="tab" href="#tab-edit" role="tab">
                                                <i class="ri-edit-box-line me-1 align-middle"></i> Edit Member
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#tab-benefits" role="tab">
                                                <i class="ri-shield-star-line me-1 align-middle"></i> Benefits
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#tab-family" role="tab">
                                                <i class="ri-team-line me-1 align-middle"></i> Family Members
                                            </a>
                                        </li>
                                        <li class="nav-item">
                                            <a class="nav-link" data-bs-toggle="tab" href="#tab-anniversary" role="tab">
                                                <i class="ri-calendar-line me-1 align-middle"></i> Anniversaries
                                            </a>
                                        </li>
                                    </ul>
                                    
                                    <!-- Tab Content -->
                                    <div class="tab-content">
                                        <!-- Edit Member Tab -->
                                        <div class="tab-pane active" id="tab-edit" role="tabpanel">
                                            <form action="" method="POST" id="editMemberForm">
                                                <!-- Personal Information Section -->
                                                <div class="personal-info-container">
                                                    <h5 class="section-title">
                                                        <i class="ri-profile-line me-2 text-primary"></i>
                                                        Personal Information
                                                    </h5>
                                                    
                                                    <div class="row g-3">
                                                        <div class="col-md-4">
                                                            <label class="form-label">First Name</label>
                                                            <input type="text" class="form-control" name="first_name" 
                                                                   value="<?php echo htmlspecialchars($member['first_name']); ?>" required>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label class="form-label">Surname</label>
                                                            <input type="text" class="form-control" name="surname" 
                                                                   value="<?php echo htmlspecialchars($member['surname']); ?>" required>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label class="form-label">Other Names</label>
                                                            <input type="text" class="form-control" name="other_names" 
                                                                   value="<?php echo htmlspecialchars($member['other_names']); ?>">
                                                        </div>
                                                    </div>

                                                    <div class="row g-3 mt-2">
                                                        <div class="col-md-4">
                                                            <label class="form-label">Date of Birth</label>
                                                            <div class="input-group">
                                                                <span class="input-group-text"><i class="ri-calendar-line"></i></span>
                                                                <input type="date" class="form-control" name="dob" 
                                                                       value="<?php echo $member['dob']; ?>" required>
                                                            </div>
                                                            <?php 
                                                            // Calculate age
                                                            $birthDate = new DateTime($member['dob']);
                                                            $currentDate = new DateTime();
                                                            $age = $currentDate->diff($birthDate)->y;
                                                            ?>
                                                            <small class="text-muted">Age: <?php echo $age; ?> years</small>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label class="form-label">Gender</label>
                                                            <select class="form-select" name="gender" required>
                                                                <option value="1" <?php echo $member['gender'] == 1 ? 'selected' : ''; ?>>Male</option>
                                                                <option value="2" <?php echo $member['gender'] == 2 ? 'selected' : ''; ?>>Female</option>
                                                            </select>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label class="form-label">ID Number</label>
                                                            <div class="input-group">
                                                                <span class="input-group-text"><i class="ri-article-line"></i></span>
                                                                <input type="text" class="form-control" name="id_no" 
                                                                       value="<?php echo htmlspecialchars($member['id_no']); ?>">
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <div class="row g-3 mt-2">
                                                        <div class="col-md-4">
                                                            <label class="form-label">NHIF Card No</label>
                                                            <div class="input-group">
                                                                <span class="input-group-text"><i class="ri-health-book-line"></i></span>
                                                                <input type="text" class="form-control" name="nhif_no" 
                                                                       value="<?php echo htmlspecialchars($member['nhif_card_no']); ?>">
                                                            </div>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label class="form-label">Member Type</label>
                                                            <input type="text" class="form-control" 
                                                                   value="<?php echo $isPrincipal ? 'Principal' : 'Dependent'; ?>" readonly>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <?php if ($isPrincipal && !empty($available_categories)): ?>
                                                            <label class="form-label">Category</label>
                                                            <select class="form-select category-select" name="category">
                                                                <?php foreach ($available_categories as $category): ?>
                                                                <option value="<?php echo $category; ?>" 
                                                                        <?php echo ($member['categories'] == $category) ? 'selected' : ''; ?>>
                                                                    <?php echo $category; ?>
                                                                </option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                            <div class="category-info">
                                                                <i class="ri-information-line me-1"></i>
                                                                Changing category will update all family members
                                                            </div>
                                                            <?php else: ?>
                                                            <label class="form-label">Category</label>
                                                            <input type="text" class="form-control" 
                                                                   value="<?php echo htmlspecialchars($member['categories']); ?>" readonly>
                                                            <?php endif; ?>
                                                        </div>
                                                    </div>
                                                </div>

                                                <?php if ($isPrincipal): ?>
                                                <!-- Contact Information Section (Only for principal) -->
                                                <div class="personal-info-container">
                                                    <h5 class="section-title">
                                                        <i class="ri-contacts-line me-2 text-primary"></i>
                                                        Contact Information
                                                    </h5>
                                                    
                                                    <div class="row g-3">
                                                        <div class="col-md-4">
                                                            <label class="form-label">Mobile Number</label>
                                                            <div class="input-group">
                                                                <span class="input-group-text"><i class="ri-smartphone-line"></i></span>
                                                                <input type="text" class="form-control" name="mobile_no" 
                                                                       value="<?php echo htmlspecialchars($member['mobile_no']); ?>">
                                                            </div>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label class="form-label">Email Address</label>
                                                            <div class="input-group">
                                                                <span class="input-group-text"><i class="ri-mail-line"></i></span>
                                                                <input type="email" class="form-control" name="email" 
                                                                       value="<?php echo htmlspecialchars($member['email']); ?>">
                                                            </div>
                                                        </div>
                                                        <div class="col-md-4">
                                                            <label class="form-label">KRA PIN</label>
                                                            <div class="input-group">
                                                                <span class="input-group-text"><i class="ri-bank-card-line"></i></span>
                                                                <input type="text" class="form-control" name="pin_no" 
                                                                       value="<?php echo htmlspecialchars($member['pin_no']); ?>">
                                                            </div>
                                                        </div>
                                                    </div>
                                                
                                                    <div class="row g-3 mt-2">
                                                        <div class="col-md-6">
                                                            <label class="form-label">Postal Address</label>
                                                            <div class="input-group">
                                                                <span class="input-group-text"><i class="ri-mail-send-line"></i></span>
                                                                <textarea class="form-control address-textarea" name="postal_add" rows="2"><?php echo htmlspecialchars($member['postal_add']); ?></textarea>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                <?php endif; ?>

                                                <div class="row btn-section">
                                                    <div class="col-12 text-end">
                                                        <a href="view_member.php?member_no=<?php echo $member_no; ?>" class="btn btn-secondary me-2">
                                                            <i class="ri-close-line me-1"></i> Cancel
                                                        </a>
                                                        <button type="submit" class="btn btn-primary">
                                                            <i class="ri-save-3-line me-1"></i> Update Member
                                                        </button>
                                                    </div>
                                                </div>
                                            </form>
                                        </div>
                                        
                                        <!-- Benefits Tab -->
                                        <div class="tab-pane" id="tab-benefits" role="tabpanel">
                                            <div class="info-section">
                                                <div class="info-title">
                                                    <i class="ri-shield-star-line text-primary"></i> 
                                                    Current Benefits
                                                </div>
                                                <p class="text-muted mb-3">
                                                    These are the current benefits assigned to the member. Changes to benefits must be done by an administrator.
                                                </p>
                                                
                                                <div class="table-responsive">
                                                    <table class="table data-table">
                                                        <thead>
                                                            <tr>
                                                                <th>Benefit</th>
                                                                <th>Category</th>
                                                                <th>Anniversary</th>
                                                                <th class="text-end">Limit</th>
                                                                <th>Sharing</th>
                                                                <th>Status</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php 
                                                            if (empty($benefits)) {
                                                                echo '<tr><td colspan="6" class="text-center">No benefits assigned to this member</td></tr>';
                                                            } else {
                                                                foreach ($benefits as $benefit): 
                                                            ?>
                                                                <tr>
                                                                    <td><?php echo $benefit['benefit_name']; ?></td>
                                                                    <td>
                                                                        <span class="benefit-tag">
                                                                            <?php echo $benefit['category']; ?>
                                                                        </span>
                                                                    </td>
                                                                    <td><?php echo $benefit['anniv']; ?></td>
                                                                    <td class="text-end">
                                                                        <?php echo number_format($benefit['limit'], 2); ?>
                                                                    </td>
                                                                    <td>
                                                                        <span class="badge bg-<?php echo $benefit['sharing'] ? 'success' : 'secondary'; ?>">
                                                                            <?php echo $benefit['sharing'] ? 'Yes' : 'No'; ?>
                                                                        </span>
                                                                    </td>
                                                                    <td>
                                                                        <span class="badge bg-<?php echo $benefit['suspended'] ? 'danger' : 'success'; ?>">
                                                                            <?php echo $benefit['suspended'] ? 'Suspended' : 'Active'; ?>
                                                                        </span>
                                                                    </td>
                                                                </tr>
                                                            <?php endforeach; } ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                            
                                            <div class="info-section">
                                                <div class="info-title">
                                                    <i class="ri-building-line text-primary"></i> 
                                                    Corporate Plan Benefits
                                                </div>
                                                <p class="text-muted mb-3">
                                                    These are the benefits available in the corporate plan for category <?php echo htmlspecialchars($member['categories']); ?>.
                                                </p>
                                                
                                                <div class="table-responsive">
                                                    <table class="table data-table">
                                                        <thead>
                                                            <tr>
                                                                <th>Benefit</th>
                                                                <th>Category</th>
                                                                <th class="text-end">Limit</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php 
                                                            $filtered_benefits = array_filter($corporate_benefits, function($b) use ($member) {
                                                                return $b['category'] == $member['categories'];
                                                            });
                                                            
                                                            if (empty($filtered_benefits)) {
                                                                echo '<tr><td colspan="3" class="text-center">No corporate benefits found for this category</td></tr>';
                                                            } else {
                                                                foreach ($filtered_benefits as $cb): 
                                                            ?>
                                                                <tr>
                                                                    <td><?php echo $cb['benefit_name']; ?></td>
                                                                    <td>
                                                                        <span class="benefit-tag">
                                                                            <?php echo $cb['category']; ?>
                                                                        </span>
                                                                    </td>
                                                                    <td class="text-end">
                                                                        <?php echo number_format($cb['limit'], 2); ?>
                                                                    </td>
                                                                </tr>
                                                            <?php endforeach; } ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Family Members Tab -->
                                        <div class="tab-pane" id="tab-family" role="tabpanel">
                                            <div class="info-section">
                                                <div class="info-title">
                                                    <i class="ri-team-line text-primary"></i> 
                                                    Family Members
                                                </div>
                                                <p class="text-muted mb-3">
                                                    These are all the members associated with the family number: <?php echo htmlspecialchars($member['family_no']); ?>
                                                </p>
                                                
                                                <div class="table-responsive">
                                                    <table class="table data-table">
                                                        <thead>
                                                            <tr>
                                                                <th>Member No</th>
                                                                <th>Name</th>
                                                                <th>Relationship</th>
                                                                <th>Date of Birth</th>
                                                                <th>Gender</th>
                                                                <th>ID Number</th>
                                                                <th>Status</th>
                                                                <th>Action</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php 
                                                            if (empty($family_members)) {
                                                                echo '<tr><td colspan="8" class="text-center">No other family members found</td></tr>';
                                                            } else {
                                                                foreach ($family_members as $family_member): 
                                                                    $relation = '';
                                                                    switch($family_member['relation_to_principal']) {
                                                                        case 1: $relation = 'Principal'; break;
                                                                        case 2: $relation = 'Spouse'; break;
                                                                        case 3: $relation = 'Child'; break;
                                                                        case 4: $relation = 'Parent'; break;
                                                                    }
                                                            ?>
                                                                <tr>
                                                                    <td><?php echo $family_member['member_no']; ?></td>
                                                                    <td>
                                                                        <?php echo $family_member['surname'] . ' ' . 
                                                                                  $family_member['first_name'] . ' ' . 
                                                                                  $family_member['other_names']; ?>
                                                                    </td>
                                                                    <td><?php echo $relation; ?></td>
                                                                    <td><?php echo date('d M Y', strtotime($family_member['dob'])); ?></td>
                                                                    <td><?php echo $family_member['gender'] == 1 ? 'Male' : 'Female'; ?></td>
                                                                    <td><?php echo $family_member['id_no']; ?></td>
                                                                    <td>
                                                                        <span class="badge bg-<?php echo $family_member['is_cancelled'] ? 'danger' : 'success'; ?>">
                                                                            <?php echo $family_member['is_cancelled'] ? 'Inactive' : 'Active'; ?>
                                                                        </span>
                                                                    </td>
                                                                    <td>
                                                                        <a href="view_member.php?member_no=<?php echo $family_member['member_no']; ?>" class="btn btn-sm btn-primary">
                                                                            <i class="ri-eye-line"></i>
                                                                        </a>
                                                                        <a href="edit_member.php?member_no=<?php echo $family_member['member_no']; ?>" class="btn btn-sm btn-info">
                                                                            <i class="ri-edit-line"></i>
                                                                        </a>
                                                                    </td>
                                                                </tr>
                                                            <?php endforeach; } ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Anniversary Tab -->
                                        <div class="tab-pane" id="tab-anniversary" role="tabpanel">
                                            <div class="info-section">
                                                <div class="info-title">
                                                    <i class="ri-calendar-line text-primary"></i> 
                                                    Member Anniversaries
                                                </div>
                                                <p class="text-muted mb-3">
                                                    Anniversary periods for this member's policy coverage
                                                </p>
                                                
                                                <div class="table-responsive">
                                                    <table class="table data-table">
                                                        <thead>
                                                            <tr>
                                                                <th>Anniversary</th>
                                                                <th>Start Date</th>
                                                                <th>End Date</th>
                                                                <th>Renewal Date</th>
                                                                <th>Renewal Status</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php 
                                                            if (empty($anniversaries)) {
                                                                echo '<tr><td colspan="5" class="text-center">No anniversary records found</td></tr>';
                                                            } else {
                                                                foreach ($anniversaries as $anniversary): 
                                                                    $badge_class = 'bg-info';
                                                                    $status = 'Pending';
                                                                    
                                                                    if ($anniversary['renewal_notified']) {
                                                                        $badge_class = 'bg-warning';
                                                                        $status = 'Notified';
                                                                    }
                                                                    
                                                                    if (isset($anniversary['is_renewed']) && $anniversary['is_renewed'] == '1') {
                                                                        $badge_class = 'bg-success';
                                                                        $status = 'Renewed';
                                                                    }
                                                            ?>
                                                                <tr>
                                                                    <td><?php echo $anniversary['anniv']; ?></td>
                                                                    <td><?php echo date('d M Y', strtotime($anniversary['start_date'])); ?></td>
                                                                    <td><?php echo date('d M Y', strtotime($anniversary['end_date'])); ?></td>
                                                                    <td><?php echo date('d M Y', strtotime($anniversary['renewal_date'])); ?></td>
                                                                    <td>
                                                                        <span class="badge <?php echo $badge_class; ?>">
                                                                            <?php echo $status; ?>
                                                                        </span>
                                                                    </td>
                                                                </tr>
                                                            <?php endforeach; } ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                            
                                            <div class="info-section">
                                                <div class="info-title">
                                                    <i class="ri-building-4-line text-primary"></i> 
                                                    Corporate Anniversary
                                                </div>
                                                <p class="text-muted mb-3">
                                                    Corporate policy anniversary details
                                                </p>
                                                
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="info-item">
                                                            <div class="info-label">Current Anniversary</div>
                                                            <div class="info-value"><?php echo $member['anniv'] ?? 'Not available'; ?></div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="info-item">
                                                            <div class="info-label">Corporate</div>
                                                            <div class="info-value"><?php echo htmlspecialchars($member['corporate']); ?></div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        // Client-side validation
        document.getElementById('editMemberForm').addEventListener('submit', function(e) {
            const idNo = document.querySelector('input[name="id_no"]').value;
            const dob = new Date(document.querySelector('input[name="dob"]').value);
            const today = new Date();
            const age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
            
            let errors = [];
            
            // Validate ID number
            //if (idNo && idNo.length < 6) {
            //    errors.push("ID number must be at least 6 characters long");
            //}
            
            // Validate principal age
            const isPrincipal = <?php echo $isPrincipal ? 'true' : 'false'; ?>;
            if (isPrincipal && age < 18) {
                errors.push("Principal member must be at least 18 years old");
            }
            
            // Display errors if any
            if (errors.length > 0) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    html: errors.join('<br>'),
                    confirmButtonColor: '#3762ea'
                });
            } else {
                // Confirm category change if applicable
                const categorySelect = document.querySelector('select[name="category"]');
                if (categorySelect) {
                    const oldCategory = "<?php echo $member['categories']; ?>";
                    
                    if (categorySelect.value !== oldCategory) {
                        e.preventDefault();
                        Swal.fire({
                            title: 'Change Category?',
                            text: `Are you sure you want to change the category from "${oldCategory}" to "${categorySelect.value}"? This will update all family members.`,
                            icon: 'warning',
                            showCancelButton: true,
                            confirmButtonColor: '#3762ea',
                            cancelButtonColor: '#6c757d',
                            confirmButtonText: 'Yes, change it!'
                        }).then((result) => {
                            if (result.isConfirmed) {
                                document.getElementById('editMemberForm').submit();
                            }
                        });
                    }
                }
            }
        });
        
        // Activate tabs via URL hash
        document.addEventListener('DOMContentLoaded', function() {
            const hash = window.location.hash;
            if (hash) {
                document.querySelector(`a[href="${hash}"]`)?.click();
            }
            
            // Add input focus animation
            document.querySelectorAll('.form-control, .form-select').forEach(input => {
                input.addEventListener('focus', function() {
                    this.parentElement.classList.add('focused');
                });
                
                input.addEventListener('blur', function() {
                    this.parentElement.classList.remove('focused');
                });
            });
        });
    </script>
</body>
</html>