<?php
session_start();
include 'layouts/dbconn.php';

// Force JSON response and prevent any output before JSON
header('Content-Type: application/json; charset=utf-8');
ob_start();

// Check if this is an AJAX request
$isAjax = !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && 
          strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    ob_clean();
    if ($isAjax) {
        echo json_encode(['success' => false, 'error' => 'Not authenticated']);
    } else {
        header('Location: login.php');
    }
    exit;
}

// Clear any previous output
ob_clean();

try {
    // Start transaction
    $conn->autocommit(FALSE);

    $user_id = $_SESSION['user_id'];
    $member_type = $_POST['member_type'] ?? 'corporate';
    
    // Get the current date
    $current_date = date('Y-m-d');
    
    // Initialize variables for member data with safe defaults
    $corp_id = '';
    $agent_id = '';
    $category = '';
    $member_no = '';
    $family_no = '';
    
    // Handle corporate vs individual member
    if ($member_type === 'corporate') {
        $corp_id = $_POST['corp_id'] ?? '';
        $category = trim($_POST['category'] ?? ''); // Make sure to trim whitespace
        $member_no = $_POST['principal_member_no'] ?? '';
        $family_no = $_POST['principal_family_no'] ?? '';
        
        if (empty($corp_id) || empty($category)) {
            throw new Exception('Corporate ID and Category are required for corporate members');
        }
        
        // Validate that category is not just whitespace
        if (strlen($category) === 0) {
            throw new Exception('Category cannot be empty for corporate members');
        }
        
    } else {
        $agent_id = $_POST['agent_id'] ?? '';
        $member_no = $_POST['individual_member_no'] ?? '';
        $family_no = $_POST['individual_family_no'] ?? '';
        $corp_id = 'INDIVIDUAL';
        $category = 'INDIVIDUAL'; // Set a proper default for individual members
        
        if (empty($agent_id)) {
            throw new Exception('Agent is required for individual members');
        }
    }
    
    if (empty($member_no) || empty($family_no)) {
        throw new Exception('Member number and family number are required');
    }
    
    // Debug logging - remove in production
    error_log("DEBUG: member_type = $member_type, category = '$category', corp_id = $corp_id");
    
    // Validate required principal member fields
    $required_fields = [
        'principal_surname', 'principal_first_name', 'principal_family_size',
        'principal_relation_to_family', 'principal_dob', 'principal_gender', 'principal_pin_no'
    ];
    
    foreach ($required_fields as $field) {
        if (empty(trim($_POST[$field] ?? ''))) {
            $field_name = str_replace('principal_', '', $field);
            $field_name = str_replace('_', ' ', $field_name);
            throw new Exception("Required field missing: " . ucfirst($field_name));
        }
    }
    
    // Calculate age from date of birth
    $dob = $_POST['principal_dob'];
    $age = date_diff(date_create($dob), date_create('today'))->y;
    
    // Initialize all variables for principal_applicant binding
    $principal_surname = trim($_POST['principal_surname'] ?? '');
    $principal_first_name = trim($_POST['principal_first_name'] ?? '');
    $principal_other_names = trim($_POST['principal_other_names'] ?? '');
    $principal_tel_no = trim($_POST['principal_tel_no'] ?? '');
    $principal_mobile_no = trim($_POST['principal_mobile_no'] ?? '');
    $principal_postal_add = trim($_POST['principal_postal_add'] ?? '');
    $principal_town = !empty($_POST['principal_town']) ? (int)$_POST['principal_town'] : null;
    $principal_email = trim($_POST['principal_email'] ?? '');
    $principal_phy_loc = trim($_POST['principal_phy_loc'] ?? '');
    $principal_family_size = trim($_POST['principal_family_size'] ?? '');
    $principal_relation_to_family = (int)($_POST['principal_relation_to_family'] ?? 1);
    $individual_flag = ($member_type === 'individual') ? 1 : 0;
    $principal_marital_status = !empty($_POST['principal_marital_status']) ? (int)$_POST['principal_marital_status'] : null;
    $principal_date_employed = !empty($_POST['principal_date_employed']) ? $_POST['principal_date_employed'] : null;
    $principal_previous_insurer = trim($_POST['principal_previous_insurer'] ?? '');
    $principal_period_insured = trim($_POST['principal_period_insured'] ?? '');
    $principal_beneficiary = trim($_POST['principal_beneficiary'] ?? '');
    $principal_beneficiary_id = trim($_POST['principal_beneficiary_id'] ?? '');
    $principal_beneficiary_relation = trim($_POST['principal_beneficiary_relation'] ?? '');
    $principal_parish = trim($_POST['principal_parish'] ?? '');
    $principal_policy_no = trim($_POST['principal_policy_no'] ?? '');
    $principal_pin_no = trim($_POST['principal_pin_no'] ?? '');
    $principal_branch = trim($_POST['principal_branch'] ?? '');
    $principal_bank_branch = trim($_POST['principal_bank_branch'] ?? '');
    $principal_account_no = trim($_POST['principal_account_no'] ?? '');
    $principal_plan_code = trim($_POST['principal_plan_code'] ?? '');
    $principal_employer_code = trim($_POST['principal_employer_code'] ?? '');
    
    // Check if principal_applicant table has category column, if not, exclude it
    $check_column_sql = "SHOW COLUMNS FROM principal_applicant LIKE 'category'";
    $column_result = $conn->query($check_column_sql);
    $has_category_column = $column_result && $column_result->num_rows > 0;
    
    if ($has_category_column) {
        // Insert into principal_applicant table with category
        $sql_principal = "INSERT INTO principal_applicant (
            family_no, member_no, surname, first_name, other_names, agent_id, corp_id,
            tel_no, mobile_no, postal_add, town, email, phy_loc, family_size,
            relation_to_family, individual, date_form_received, user_id, date_entered,
            marital_status, date_employed, previous_insurer, period_insured,
            beneficiary, beneficiary_id, beneficiary_relation, parish, policy_no,
            pin_no, branch, bank_branch, account_no, plan_code, employer_code, category
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt_principal = $conn->prepare($sql_principal);
        if (!$stmt_principal) {
            throw new Exception('Failed to prepare principal statement: ' . $conn->error);
        }
        
        // Bind parameters for principal_applicant (35 parameters including category)
        $stmt_principal->bind_param(
            'ssssssssssisssissssssssssssssssssss',
            $family_no,                    // 1
            $member_no,                    // 2
            $principal_surname,            // 3
            $principal_first_name,         // 4
            $principal_other_names,        // 5
            $agent_id,                     // 6
            $corp_id,                      // 7
            $principal_tel_no,             // 8
            $principal_mobile_no,          // 9
            $principal_postal_add,         // 10
            $principal_town,               // 11 (integer)
            $principal_email,              // 12
            $principal_phy_loc,            // 13
            $principal_family_size,        // 14
            $principal_relation_to_family, // 15 (integer)
            $individual_flag,              // 16 (integer)
            $current_date,                 // 17
            $user_id,                      // 18
            $current_date,                 // 19
            $principal_marital_status,     // 20 (integer)
            $principal_date_employed,      // 21
            $principal_previous_insurer,   // 22
            $principal_period_insured,     // 23
            $principal_beneficiary,        // 24
            $principal_beneficiary_id,     // 25
            $principal_beneficiary_relation, // 26
            $principal_parish,             // 27
            $principal_policy_no,          // 28
            $principal_pin_no,             // 29
            $principal_branch,             // 30
            $principal_bank_branch,        // 31
            $principal_account_no,         // 32
            $principal_plan_code,          // 33
            $principal_employer_code,      // 34
            $category                      // 35
        );
    } else {
        // Insert into principal_applicant table without category
        $sql_principal = "INSERT INTO principal_applicant (
            family_no, member_no, surname, first_name, other_names, agent_id, corp_id,
            tel_no, mobile_no, postal_add, town, email, phy_loc, family_size,
            relation_to_family, individual, date_form_received, user_id, date_entered,
            marital_status, date_employed, previous_insurer, period_insured,
            beneficiary, beneficiary_id, beneficiary_relation, parish, policy_no,
            pin_no, branch, bank_branch, account_no, plan_code, employer_code
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt_principal = $conn->prepare($sql_principal);
        if (!$stmt_principal) {
            throw new Exception('Failed to prepare principal statement: ' . $conn->error);
        }
        
        // Bind parameters for principal_applicant (34 parameters without category)
        $stmt_principal->bind_param(
            'sssssssssisssissssssssssssssssss',
            $family_no,                    // 1
            $member_no,                    // 2
            $principal_surname,            // 3
            $principal_first_name,         // 4
            $principal_other_names,        // 5
            $agent_id,                     // 6
            $corp_id,                      // 7
            $principal_tel_no,             // 8
            $principal_mobile_no,          // 9
            $principal_postal_add,         // 10
            $principal_town,               // 11 (integer)
            $principal_email,              // 12
            $principal_phy_loc,            // 13
            $principal_family_size,        // 14
            $principal_relation_to_family, // 15 (integer)
            $individual_flag,              // 16 (integer)
            $current_date,                 // 17
            $user_id,                      // 18
            $current_date,                 // 19
            $principal_marital_status,     // 20 (integer)
            $principal_date_employed,      // 21
            $principal_previous_insurer,   // 22
            $principal_period_insured,     // 23
            $principal_beneficiary,        // 24
            $principal_beneficiary_id,     // 25
            $principal_beneficiary_relation, // 26
            $principal_parish,             // 27
            $principal_policy_no,          // 28
            $principal_pin_no,             // 29
            $principal_branch,             // 30
            $principal_bank_branch,        // 31
            $principal_account_no,         // 32
            $principal_plan_code,          // 33
            $principal_employer_code       // 34
        );
    }
    
    if (!$stmt_principal->execute()) {
        throw new Exception('Failed to save principal applicant: ' . $stmt_principal->error);
    }
    
    // Insert into member_info table for principal member
    $sql_member = "INSERT INTO member_info (
        family_no, member_no, surname, first_name, other_names, dob, id_no,
        relation_to_principal, user_id, date_entered, family_title, cancelled,
        employment_no, gender, passport_no, nhif_card_no, marital_status,
        date_employed, status, corp_id, family_size, mem_pin, age
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt_member = $conn->prepare($sql_member);
    if (!$stmt_member) {
        throw new Exception('Failed to prepare member statement: ' . $conn->error);
    }
    
    // Prepare member_info variables
    $status = 1; // Active
    $cancelled = 0;
    $principal_id_no = trim($_POST['principal_id_no'] ?? '');
    $principal_employment_no = trim($_POST['principal_employment_no'] ?? '');
    $principal_gender = (int)($_POST['principal_gender'] ?? 1);
    $principal_passport_no = trim($_POST['principal_passport_no'] ?? '');
    $principal_nhif_card_no = trim($_POST['principal_nhif_card_no'] ?? '');
    $principal_family_title = (int)($_POST['principal_family_title'] ?? 1);
    
    // Bind parameters for member_info
    $stmt_member->bind_param(
        'ssssssisssiissssisssssi',
        $family_no,
        $member_no,
        $principal_surname,
        $principal_first_name,
        $principal_other_names,
        $dob,
        $principal_id_no,
        $principal_relation_to_family,
        $user_id,
        $current_date,
        $principal_family_title,
        $cancelled,
        $principal_employment_no,
        $principal_gender,
        $principal_passport_no,
        $principal_nhif_card_no,
        $principal_marital_status,
        $principal_date_employed,
        $status,
        $corp_id,
        $principal_family_size,
        $principal_pin_no,
        $age
    );
    
    if (!$stmt_member->execute()) {
        throw new Exception('Failed to save member info: ' . $stmt_member->error);
    }
    
    // Handle dependent members if any
    if (isset($_POST['dependent_member_no']) && is_array($_POST['dependent_member_no'])) {
        $dependent_count = count($_POST['dependent_member_no']);
        
        for ($i = 0; $i < $dependent_count; $i++) {
            if (!empty(trim($_POST['dependent_member_no'][$i] ?? ''))) {
                // Calculate dependent age
                $dependent_dob = $_POST['dependent_dob'][$i] ?? '';
                $dependent_age = 0;
                if (!empty($dependent_dob)) {
                    $dependent_age = date_diff(date_create($dependent_dob), date_create('today'))->y;
                }
                
                // Initialize dependent variables
                $dependent_surname = trim($_POST['dependent_surname'][$i] ?? '');
                $dependent_first_name = trim($_POST['dependent_first_name'][$i] ?? '');
                $dependent_other_names = trim($_POST['dependent_other_names'][$i] ?? '');
                $dependent_id_no = trim($_POST['dependent_id_no'][$i] ?? '');
                $dependent_relation = (int)($_POST['dependent_relation'][$i] ?? 3);
                $dependent_family_title = (int)($_POST['dependent_family_title'][$i] ?? 2);
                $dependent_employment_no = trim($_POST['dependent_employment_no'][$i] ?? '');
                $dependent_gender = (int)($_POST['dependent_gender'][$i] ?? 1);
                $dependent_passport_no = trim($_POST['dependent_passport_no'][$i] ?? '');
                $dependent_nhif_card_no = trim($_POST['dependent_nhif_card_no'][$i] ?? '');
                $dependent_marital_status = !empty($_POST['dependent_marital_status'][$i]) ? (int)$_POST['dependent_marital_status'][$i] : null;
                $dependent_date_employed = !empty($_POST['dependent_date_employed'][$i]) ? $_POST['dependent_date_employed'][$i] : null;
                $dependent_status = isset($_POST['dependent_status'][$i]) && $_POST['dependent_status'][$i] == '1' ? 1 : 0;
                $dependent_pin_no = trim($_POST['dependent_pin_no'][$i] ?? '');
                
                // Insert dependent into member_info
                $stmt_dependent = $conn->prepare($sql_member);
                if (!$stmt_dependent) {
                    throw new Exception('Failed to prepare dependent statement: ' . $conn->error);
                }
                
                $stmt_dependent->bind_param(
                    'ssssssisssiissssisssssi',
                    $family_no,
                    $_POST['dependent_member_no'][$i],
                    $dependent_surname,
                    $dependent_first_name,
                    $dependent_other_names,
                    $dependent_dob,
                    $dependent_id_no,
                    $dependent_relation,
                    $user_id,
                    $current_date,
                    $dependent_family_title,
                    $cancelled,
                    $dependent_employment_no,
                    $dependent_gender,
                    $dependent_passport_no,
                    $dependent_nhif_card_no,
                    $dependent_marital_status,
                    $dependent_date_employed,
                    $dependent_status,
                    $corp_id,
                    $principal_family_size,
                    $dependent_pin_no,
                    $dependent_age
                );
                
                if (!$stmt_dependent->execute()) {
                    throw new Exception('Failed to save dependent member: ' . $stmt_dependent->error);
                }
            }
        }
    }
    
    // Handle member benefits - CORRECTED SQL AND BINDING
    if (isset($_POST['benefit_code']) && is_array($_POST['benefit_code'])) {
        $benefit_count = count($_POST['benefit_code']);
        
        // Match the exact columns from your table schema
        $sql_benefit = "INSERT INTO member_benefits (
            member_no, benefit, `limit`, sharing, anniv, sub_limit_of, 
            suspended, claims, reserve, expense, balance, percent, status, 
            fund, exceed_limit, category, waiting_period, corp_id
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt_benefit = $conn->prepare($sql_benefit);
        if (!$stmt_benefit) {
            throw new Exception('Failed to prepare benefit statement: ' . $conn->error);
        }
        
        // Collect female dependents for maternity benefit assignment
        $female_dependents = [];
        if (isset($_POST['dependent_member_no']) && is_array($_POST['dependent_member_no'])) {
            for ($i = 0; $i < count($_POST['dependent_member_no']); $i++) {
                if (!empty($_POST['dependent_member_no'][$i]) && ($_POST['dependent_gender'][$i] ?? '') === '2') {
                    $female_dependents[] = $_POST['dependent_member_no'][$i];
                }
            }
        }
        
        for ($i = 0; $i < $benefit_count; $i++) {
            if (!empty($_POST['benefit_code'][$i])) {
                // Initialize benefit variables with proper type casting
                $benefit_code = (int)$_POST['benefit_code'][$i];
                $benefit_limit = (float)($_POST['benefit_limit'][$i] ?? 0.0);
                $benefit_sharing = isset($_POST['benefit_sharing'][$i]) ? (int)$_POST['benefit_sharing'][$i] : 0;
                $benefit_sharing = ($benefit_sharing === 1) ? 1 : 0;
                $benefit_anniv = (int)($_POST['benefit_anniv'][$i] ?? date('Y'));
                $benefit_sub_limit_of = !empty($_POST['benefit_sub_limit_of'][$i]) ? (int)$_POST['benefit_sub_limit_of'][$i] : null;
                $benefit_suspended = ($_POST['benefit_status'][$i] ?? '1') == '0' ? 1 : 0;
                $benefit_claims = 0.0;
                $benefit_reserve = 0.0;
                $benefit_expense = 0.0;
                $benefit_balance = (float)($_POST['benefit_limit'][$i] ?? 0.0);
                $benefit_percent = 0.0;
                $benefit_status = $_POST['benefit_status'][$i] ?? '1';
                
                // Use the main category variable directly
                $benefit_category = $category;
                
                // Debug logging - remove in production
                error_log("DEBUG: Saving benefit with category = '$benefit_category'");
                
                $benefit_fund = 0;
                $benefit_exceed_limit = 0;
                $benefit_waiting_period = null;
                
                // Check if this is a maternity benefit (assuming benefit code 3 is maternity)
                $is_maternity_benefit = ($benefit_code === 3);
                
                // Handle maternity benefit for male principal
                if ($is_maternity_benefit && $principal_gender === 1 && !empty($female_dependents)) {
                    // Assign maternity benefit to female dependents only
                    foreach ($female_dependents as $dependent_member) {
                        $stmt_benefit->bind_param(
                            'siddidddddsssiisis',  // Corrected type string: 18 parameters
                            $dependent_member,      // 1: member_no (string)
                            $benefit_code,          // 2: benefit (int)
                            $benefit_limit,         // 3: limit (decimal/double)
                            $benefit_sharing,       // 4: sharing (decimal/double)
                            $benefit_anniv,         // 5: anniv (int)
                            $benefit_sub_limit_of,  // 6: sub_limit_of (int/null)
                            $benefit_suspended,     // 7: suspended (decimal/double)
                            $benefit_claims,        // 8: claims (decimal/double)
                            $benefit_reserve,       // 9: reserve (decimal/double)
                            $benefit_expense,       // 10: expense (decimal/double)
                            $benefit_balance,       // 11: balance (decimal/double)
                            $benefit_percent,       // 12: percent (decimal/double)
                            $benefit_status,        // 13: status (string)
                            $benefit_fund,          // 14: fund (int)
                            $benefit_exceed_limit,  // 15: exceed_limit (int)
                            $benefit_category,      // 16: category (string)
                            $benefit_waiting_period, // 17: waiting_period (int/null)
                            $corp_id               // 18: corp_id (string)
                            );
                        
                        if (!$stmt_benefit->execute()) {
                            throw new Exception('Failed to save dependent maternity benefit: ' . $stmt_benefit->error);
                        }
                    }
                } else {
                    // Assign non-maternity benefits or maternity benefit for female principal
                    $stmt_benefit->bind_param(
                        'siddidddddsssiisis',  // Corrected type string: 18 parameters
                        $member_no,             // 1: member_no (string)
                        $benefit_code,          // 2: benefit (int)
                        $benefit_limit,         // 3: limit (decimal/double)
                        $benefit_sharing,       // 4: sharing (decimal/double)
                        $benefit_anniv,         // 5: anniv (int)
                        $benefit_sub_limit_of,  // 6: sub_limit_of (int/null)
                        $benefit_suspended,     // 7: suspended (decimal/double)
                        $benefit_claims,        // 8: claims (decimal/double)
                        $benefit_reserve,       // 9: reserve (decimal/double)
                        $benefit_expense,       // 10: expense (decimal/double)
                        $benefit_balance,       // 11: balance (decimal/double)
                        $benefit_percent,       // 12: percent (decimal/double)
                        $benefit_status,        // 13: status (string)
                        $benefit_fund,          // 14: fund (int)
                        $benefit_exceed_limit,  // 15: exceed_limit (int)
                        $benefit_category,      // 16: category (string)
                        $benefit_waiting_period, // 17: waiting_period (int/null)
                        $corp_id               // 18: corp_id (string)
                    );
                    
                    if (!$stmt_benefit->execute()) {
                        throw new Exception('Failed to save member benefit: ' . $stmt_benefit->error);
                    }
                    
                    // Add benefits for dependent members if family sharing is enabled
                    if ($benefit_sharing == 1 && isset($_POST['dependent_member_no']) && is_array($_POST['dependent_member_no'])) {
                        for ($j = 0; $j < count($_POST['dependent_member_no']); $j++) {
                            if (!empty($_POST['dependent_member_no'][$j])) {
                                // Skip male dependents for maternity benefit
                                if ($is_maternity_benefit && ($_POST['dependent_gender'][$j] ?? '') !== '2') {
                                    continue;
                                }
                                
                                $stmt_benefit->bind_param(
                                    'siddiddiddsssiiss',
                                    $_POST['dependent_member_no'][$j], // member_no (string)
                                    $benefit_code,          // benefit (int)
                                    $benefit_limit,         // limit (decimal)
                                    $benefit_sharing,       // sharing (decimal)
                                    $benefit_anniv,         // anniv (int)
                                    $benefit_sub_limit_of,  // sub_limit_of (int)
                                    $benefit_suspended,     // suspended (decimal)
                                    $benefit_claims,        // claims (decimal)
                                    $benefit_reserve,       // reserve (decimal)
                                    $benefit_expense,       // expense (decimal)
                                    $benefit_balance,       // balance (decimal)
                                    $benefit_percent,       // percent (decimal)
                                    $benefit_status,        // status (string)
                                    $benefit_fund,          // fund (int)
                                    $benefit_exceed_limit,  // exceed_limit (int)
                                    $benefit_category,      // category (string)
                                    $benefit_waiting_period, // waiting_period (int)
                                    $corp_id               // corp_id (string)
                                );
                                
                                if (!$stmt_benefit->execute()) {
                                    throw new Exception('Failed to save dependent benefit: ' . $stmt_benefit->error);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    // Handle member anniversaries
    if (isset($_POST['member_anniv']) && is_array($_POST['member_anniv'])) {
        $anniversary_count = count($_POST['member_anniv']);
        
        $sql_anniversary = "INSERT INTO member_anniversary (
            member_no, start_date, end_date, renewal_date, anniv, 
            user_id, date_entered, sync, renewal_notified, corp_id
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt_anniversary = $conn->prepare($sql_anniversary);
        if (!$stmt_anniversary) {
            throw new Exception('Failed to prepare anniversary statement: ' . $conn->error);
        }
        
        for ($i = 0; $i < $anniversary_count; $i++) {
            if (!empty($_POST['member_anniv'][$i])) {
                $sync = 0;
                $renewal_notified = 0;
                $anniv_start_date = $_POST['member_start_date'][$i] ?? '';
                $anniv_end_date = $_POST['member_end_date'][$i] ?? '';
                $anniv_renewal_date = $_POST['member_renewal_date'][$i] ?? '';
                $anniv_member_anniv = (int)($_POST['member_anniv'][$i] ?? 1);
                
                // Skip if required dates are missing
                if (empty($anniv_start_date) || empty($anniv_end_date) || empty($anniv_renewal_date)) {
                    continue;
                }
                
                // Bind parameters for anniversary
                $stmt_anniversary->bind_param(
                    'ssssssiiis',
                    $member_no,
                    $anniv_start_date,
                    $anniv_end_date,
                    $anniv_renewal_date,
                    $anniv_member_anniv,
                    $user_id,
                    $current_date,
                    $sync,
                    $renewal_notified,
                    $corp_id
                );
                
                if (!$stmt_anniversary->execute()) {
                    throw new Exception('Failed to save member anniversary: ' . $stmt_anniversary->error);
                }
                
                // Add anniversaries for dependent members
                if (isset($_POST['dependent_member_no']) && is_array($_POST['dependent_member_no'])) {
                    foreach ($_POST['dependent_member_no'] as $dependent_member) {
                        if (!empty($dependent_member)) {
                            $stmt_anniversary->bind_param(
                                'ssssssiiis',
                                $dependent_member,
                                $anniv_start_date,
                                $anniv_end_date,
                                $anniv_renewal_date,
                                $anniv_member_anniv,
                                $user_id,
                                $current_date,
                                $sync,
                                $renewal_notified,
                                $corp_id
                            );
                            
                            if (!$stmt_anniversary->execute()) {
                                throw new Exception('Failed to save dependent anniversary: ' . $stmt_anniversary->error);
                            }
                        }
                    }
                }
            }
        }
    }
    
    // Log the activity
    $sql_log = "INSERT INTO activity_log (
        user_id, action, table_name, record_id, new_values, 
        ip_address, user_agent, action_date
    ) VALUES (?, 'CREATE', 'member_info', ?, ?, ?, ?, NOW())";
    
    $stmt_log = $conn->prepare($sql_log);
    if ($stmt_log) {
        $new_values = json_encode([
            'member_no' => $member_no,
            'family_no' => $family_no,
            'member_type' => $member_type,
            'corp_id' => $corp_id,
            'category' => $category,
            'surname' => $principal_surname,
            'first_name' => $principal_first_name
        ]);
        $ip_address = $_SERVER['REMOTE_ADDR'] ?? '';
        $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
       
       $stmt_log->bind_param(
           'sssss',
           $user_id,
           $member_no,
           $new_values,
           $ip_address,
           $user_agent
       );
       
       $stmt_log->execute();
   }
   
   // Commit the transaction
   $conn->commit();
   
   // Clean output buffer and send success response
   ob_clean();
   echo json_encode([
       'success' => true,
       'message' => 'Member saved successfully!',
       'member_no' => $member_no,
       'family_no' => $family_no,
       'member_type' => $member_type,
       'category' => $category,
       'debug_info' => [
           'received_category' => $_POST['category'] ?? 'NOT_SET',
           'final_category' => $category,
           'corp_id' => $corp_id
       ]
   ]);
   
} catch (Exception $e) {
   // Rollback on error
   if ($conn->inTransaction()) {
       $conn->rollback();
   }
   
   // Clean output buffer and send error response
   ob_clean();
   echo json_encode([
       'success' => false,
       'error' => $e->getMessage(),
       'line' => $e->getLine(),
       'file' => basename($e->getFile()),
       'debug_info' => [
           'received_category' => $_POST['category'] ?? 'NOT_SET',
           'member_type' => $member_type ?? 'NOT_SET',
           'corp_id' => $corp_id ?? 'NOT_SET'
       ]
   ]);
} finally {
   // Reset autocommit and close connection
   if (isset($conn)) {
       $conn->autocommit(TRUE);
       $conn->close();
   }
}
?>