<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

function modify_user_roles() {
    // Remove all default roles except administrator & subscriber
    global $wp_roles;
    if (!isset($wp_roles)) {
        $wp_roles = new WP_Roles();
    }
    
    $default_roles = ['editor', 'author', 'contributor']; // Keep 'administrator' and 'subscriber'
    foreach ($default_roles as $role) {
        if ($wp_roles->is_role($role)) {
            remove_role($role);
        }
    }

    // Define new roles (using capitalized names)
    $custom_roles = ['Client', 'Lab', 'Specialist', 'Supervisor', 'Accountant', 'Manager'];
    $capabilities = [
        'read' => true,
        'upload_files' => true,
        'unfiltered_upload' => true,
    ];
    
    // Add new roles with defined capabilities
    foreach ($custom_roles as $role) {
        if (!$wp_roles->is_role($role)) {
            add_role($role, $role, $capabilities);
        }
    }
}
add_action('init', 'modify_user_roles');

function hide_admin_bar_except_admin($show_admin_bar) {
    if (!current_user_can('administrator')) {
        return false;
    }
    return $show_admin_bar;
}
add_filter('show_admin_bar', 'hide_admin_bar_except_admin');

// Display extra user fields
function custom_user_meta_fields($user) {
    $user_phone = get_user_meta($user->ID, 'user_phone', true);
    $user_type = get_user_meta($user->ID, 'user_type', true);
    $user_status = get_user_meta($user->ID, 'user_status', true);
    $user_status_text = get_user_meta($user->ID, 'user_status_text', true);
    $user_sms = get_user_meta($user->ID, 'user_sms', true) ?: [];
    $user_profile = get_user_meta($user->ID, 'user_profile', true);
    $user_organization_name = get_user_meta($user->ID, 'user_organization_name', true);
    
    // Get address data as array
    $user_address_data = get_user_meta($user->ID, 'user_address', true);
    if (is_string($user_address_data)) {
        $user_address_data = json_decode($user_address_data, true);
    }
    if (!is_array($user_address_data)) {
        $user_address_data = [
            'geo_coordinates' => '',
            'address' => '',
            'details' => '',
            'notes' => '',
            'phone' => ''
        ];
    }
    ?>
    <h2>Custom User Info</h2>
    <table class="form-table">
        <tr>
            <th><label for="user_phone">Phone Number</label></th>
            <td>
                <input type="text" name="user_phone" id="user_phone" value="<?php echo esc_attr($user_phone); ?>" class="regular-text" />
            </td>
        </tr>
        <tr>
            <th><label>User Type</label></th>
            <td>
                <label><input type="radio" name="user_type" value="Clinic" <?php checked($user_type, 'Clinic'); ?>> Clinic</label><br>
                <label><input type="radio" name="user_type" value="Lab" <?php checked($user_type, 'Lab'); ?>> Lab</label>
            </td>
        </tr>
        <tr>
            <th><label>User Status</label></th>
            <td>
                <label><input type="radio" name="user_status" value="active" <?php checked($user_status, 'active'); ?>> Active</label><br>
                <label><input type="radio" name="user_status" value="limited" <?php checked($user_status, 'limited'); ?>> Limited</label><br>
                <label><input type="radio" name="user_status" value="blocked" <?php checked($user_status, 'blocked'); ?>> Blocked</label>
            </td>
        </tr>
        <tr>
            <th><label for="user_status_text">Status Description</label></th>
            <td>
                <textarea name="user_status_text" id="user_status_text" rows="3" class="large-text"><?php echo esc_textarea($user_status_text); ?></textarea>
            </td>
        </tr>
        <tr>
            <th><label>User SMS Notifications</label></th>
            <td>
                <label><input type="checkbox" name="user_sms[]" value="submit" <?php checked(in_array('submit', $user_sms)); ?>> Submit</label><br>
                <label><input type="checkbox" name="user_sms[]" value="process" <?php checked(in_array('process', $user_sms)); ?>> Process</label><br>
                <label><input type="checkbox" name="user_sms[]" value="completed" <?php checked(in_array('completed', $user_sms)); ?>> Completed</label>
            </td>
        </tr>
        <tr>
            <th><label for="user_profile">Profile Image URL</label></th>
            <td>
                <input type="text" name="user_profile" id="user_profile" value="<?php echo esc_url($user_profile); ?>" class="regular-text" />
                <?php if ($user_profile): ?>
                    <div><img src="<?php echo esc_url($user_profile); ?>" alt="Profile Image" style="max-width:150px;margin-top:10px;"></div>
                <?php endif; ?>
            </td>
        </tr>
        <tr>
            <th><label for="user_address_geo">Geo Coordinates</label></th>
            <td>
                <input type="text" name="user_address_geo" id="user_address_geo" value="<?php echo esc_attr($user_address_data['geo_coordinates']); ?>" class="regular-text" placeholder="Latitude, Longitude" />
            </td>
        </tr>
        <tr>
            <th><label for="user_address_main">Address</label></th>
            <td>
                <input type="text" name="user_address_main" id="user_address_main" value="<?php echo esc_attr($user_address_data['address']); ?>" class="regular-text" />
            </td>
        </tr>
        <tr>
            <th><label for="user_address_details">Address Details</label></th>
            <td>
                <input type="text" name="user_address_details" id="user_address_details" value="<?php echo esc_attr($user_address_data['details']); ?>" class="regular-text" placeholder="Street, Building, Floor, Unit" />
            </td>
        </tr>
        <tr>
            <th><label for="user_address_notes">Address Notes</label></th>
            <td>
                <textarea name="user_address_notes" id="user_address_notes" rows="3" class="large-text" placeholder="Additional notes or landmarks"><?php echo esc_textarea($user_address_data['notes']); ?></textarea>
            </td>
        </tr>
        <tr>
            <th><label for="user_address_phone">Address Phone</label></th>
            <td>
                <input type="tel" name="user_address_phone" id="user_address_phone" value="<?php echo esc_attr($user_address_data['phone']); ?>" class="regular-text" placeholder="Phone number for this address" />
            </td>
        </tr>
        <tr>
            <th><label for="user_organization_name">Organization Name</label></th>
            <td>
                <input type="text" name="user_organization_name" id="user_organization_name" value="<?php echo esc_attr($user_organization_name); ?>" class="regular-text" />
            </td>
        </tr>
    </table>
    <?php
}
add_action('show_user_profile', 'custom_user_meta_fields');
add_action('edit_user_profile', 'custom_user_meta_fields');

// Save extra user fields
function save_custom_user_meta_fields($user_id) {
    if (!current_user_can('edit_user', $user_id)) return false;

    update_user_meta($user_id, 'user_phone', sanitize_text_field($_POST['user_phone']));
    update_user_meta($user_id, 'user_type', sanitize_text_field($_POST['user_type']));
    update_user_meta($user_id, 'user_status', sanitize_text_field($_POST['user_status']));
    update_user_meta($user_id, 'user_status_text', sanitize_textarea_field($_POST['user_status_text']));
    update_user_meta($user_id, 'user_sms', array_map('sanitize_text_field', $_POST['user_sms'] ?? []));
    update_user_meta($user_id, 'user_profile', esc_url_raw($_POST['user_profile']));
    update_user_meta($user_id, 'user_organization_name', sanitize_text_field($_POST['user_organization_name']));
    
    // Save address data as JSON array
    $address_data = [
        'geo_coordinates' => sanitize_text_field($_POST['user_address_geo'] ?? ''),
        'address' => sanitize_text_field($_POST['user_address_main'] ?? ''),
        'details' => sanitize_text_field($_POST['user_address_details'] ?? ''),
        'notes' => sanitize_textarea_field($_POST['user_address_notes'] ?? ''),
        'phone' => sanitize_text_field($_POST['user_address_phone'] ?? '')
    ];
    
    update_user_meta($user_id, 'user_address', json_encode($address_data));
}
add_action('personal_options_update', 'save_custom_user_meta_fields');
add_action('edit_user_profile_update', 'save_custom_user_meta_fields');
