<?php
if (!defined('ABSPATH')) {
    exit;
}

define('PLANWISEWP_CM_PER_INCH', 2.54);

function planwisewp_admin_getCmFromInput($value, $unit_system) {
    if (!is_numeric($value) || $value <= 0) return 0;
    if ($unit_system === 'imperial') {
        return floatval($value) * PLANWISEWP_CM_PER_INCH; 
    }
    return floatval($value); 
}

function planwisewp_handle_reset_settings() {
    if (!isset($_POST['planwisewp_reset_settings_nonce']) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['planwisewp_reset_settings_nonce'] ) ), 'planwisewp_reset_settings_action')) {
        wp_die( esc_html__('Security check failed!', 'planwise-floor-planner') );
    }
    if (!current_user_can('manage_options')) {
        wp_die( esc_html__('Access Denied.', 'planwise-floor-planner') );
    }

    $options_to_delete = [
        'planwisewp_default_user_limit',
        'planwisewp_limit_period',
        'planwisewp_unit_system',
        'planwisewp_page_title',
        'planwisewp_tooltip_title',
        'planwisewp_tooltip_content',
        'planwisewp_logged_out_message',
        'planwisewp_room_list',
        'planwisewp_free_window_width',
        'planwisewp_free_window_height',
        'planwisewp_free_door_width',
        'planwisewp_free_door_height',
        'planwisewp_button_colors',
        'planwisewp_marker_color',
    ];

    $deleted_count = 0;
    foreach ($options_to_delete as $option_name) {
        if (delete_option($option_name)) {
            $deleted_count++;
        }
    }

    $redirect_url = add_query_arg(
        ['page' => 'planwisewp-admin', 'tab' => 'settings', 'message' => 'settings_reset'],
        admin_url('admin.php')
    );
    wp_safe_redirect(esc_url_raw($redirect_url));
    exit;
}

function planwisewp_admin_getValueForInput($cmValue, $unit_system) {
    if (!is_numeric($cmValue)) return 0;
    if ($unit_system === 'imperial') {
        $value = floatval($cmValue) / PLANWISEWP_CM_PER_INCH;
        return round($value * 10) / 10; 
    }
    return round(floatval($cmValue)); 
}
define('PLANWISEWP_SQM_PER_SQFT', 0.092903);

function planwisewp_admin_formatArea($sqmValue, $unit_system) {
    if (!is_numeric($sqmValue)) $sqmValue = 0;
    if ($unit_system === 'imperial') {
        $sqFt = floatval($sqmValue) / PLANWISEWP_SQM_PER_SQFT;
        return round($sqFt * 10) / 10 . ' sq ft'; 
    } else {
        return round(floatval($sqmValue) * 100) / 100 . ' m²'; 
    }
}

function planwisewp_render_statistics_tab() {
    if (!current_user_can('manage_options')) { 
        wp_die( esc_html__('Access Denied.', 'planwise-floor-planner') ); 
    }
    global $wpdb;

    $start_date = isset($_GET['start_date']) ? sanitize_text_field( wp_unslash( $_GET['start_date'] ) ) : wp_date('Y-m-01');
    $end_date = isset($_GET['end_date']) ? sanitize_text_field( wp_unslash( $_GET['end_date'] ) ) : wp_date('Y-m-d');

    if ( ( isset( $_GET['start_date'] ) || isset( $_GET['end_date'] ) ) ) {
        if ( ! isset( $_GET['planwisewp_stats_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_GET['planwisewp_stats_nonce'] ) ), 'planwisewp_stats_filter' ) ) {
            wp_die( esc_html__( 'Security check failed!', 'planwise-floor-planner' ) );
        }
    }

    $start_query_date = !empty($start_date) ? $start_date . ' 00:00:00' : '1970-01-01 00:00:00';
    $end_query_date = !empty($end_date) ? $end_date . ' 23:59:59' : current_time('mysql');

    $project_total_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(id) FROM {$wpdb->prefix}planwisewp_projects WHERE created_at BETWEEN %s AND %s", $start_query_date, $end_query_date));
    $project_user_ranking = $wpdb->get_results($wpdb->prepare("SELECT user_name, user_email, COUNT(id) AS created_count FROM {$wpdb->prefix}planwisewp_projects WHERE created_at BETWEEN %s AND %s GROUP BY user_id ORDER BY created_count DESC", $start_query_date, $end_query_date));
    $project_email_domain_ranking = $wpdb->get_results($wpdb->prepare("SELECT SUBSTRING_INDEX(user_email, '@', -1) as domain_name, COUNT(id) as domain_count FROM {$wpdb->prefix}planwisewp_projects WHERE created_at BETWEEN %s AND %s GROUP BY domain_name ORDER BY domain_count DESC", $start_query_date, $end_query_date));

    ?>
    <div class="planwisewp-admin">
        <h2><?php esc_html_e('Floor plan statistics', 'planwise-floor-planner'); ?></h2>
        
        <div class="question-group">
            <form method="GET" action="" id="date-filter-form">
                <input type="hidden" name="page" value="planwisewp-admin">
                <input type="hidden" name="tab" value="statistics">
                <input type="hidden" name="planwisewp_stats_nonce" value="<?php echo esc_attr( wp_create_nonce( 'planwisewp_stats_filter' ) ); ?>">
                <div class="question">
                    <label><?php esc_html_e('Select Period:', 'planwise-floor-planner'); ?></label>
                    <div style="display: flex; flex-wrap: wrap; gap: 1rem; align-items: center;">
                        <input type="date" id="start_date" name="start_date" value="<?php echo esc_attr($start_date); ?>">
                        <span>-</span>
                        <input type="date" id="end_date" name="end_date" value="<?php echo esc_attr($end_date); ?>">
                        <button type="submit"><?php esc_html_e('Filter', 'planwise-floor-planner'); ?></button>
                    </div>
                    <div style="display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; margin-top: 1rem;">
                        <button type="button" class="date-btn" data-period="all"><?php esc_html_e('All time', 'planwise-floor-planner'); ?></button>
                        <button type="button" class="date-btn" data-period="this_month"><?php esc_html_e('This month', 'planwise-floor-planner'); ?></button>
                        <button type="button" class="date-btn" data-period="prev_month"><?php esc_html_e('Previous month', 'planwise-floor-planner'); ?></button>
                        <button type="button" class="date-btn" data-period="30"><?php esc_html_e('Last 30 days', 'planwise-floor-planner'); ?></button>
                        <button type="button" class="date-btn" data-period="90"><?php esc_html_e('Last 90 days', 'planwise-floor-planner'); ?></button>
                    </div>
                </div>
            </form>
        </div>

        <div class="question-group">
            <h4>
                <?php 
                /* translators: %d: total number of projects */
                printf(esc_html__('User ranking - Floor Plans (%d total)', 'planwise-floor-planner'), esc_html($project_total_count)); 
                ?>
            </h4>
            <table class="wp-list-table widefat fixed striped">
                <thead><tr><th><?php esc_html_e('User', 'planwise-floor-planner'); ?></th><th><?php esc_html_e('Email', 'planwise-floor-planner'); ?></th><th style="width:150px;"><?php esc_html_e('Plans Created', 'planwise-floor-planner'); ?></th></tr></thead>
                <tbody>
                    <?php if(empty($project_user_ranking)): ?>
                        <tr><td colspan="3"><?php esc_html_e('No data for this period.', 'planwise-floor-planner'); ?></td></tr>
                    <?php else: foreach($project_user_ranking as $row): ?>
                        <tr>
                            <td><?php echo esc_html($row->user_name); ?></td>
                            <td><?php echo esc_html($row->user_email); ?></td>
                            <td><?php echo esc_html($row->created_count); ?></td>
                        </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>

        <div class="question-group">
            <h4><?php esc_html_e('Email domain aggregation - Floor Plans', 'planwise-floor-planner'); ?></h4>
            <table class="wp-list-table widefat fixed striped">
                <thead><tr><th><?php esc_html_e('Domain', 'planwise-floor-planner'); ?></th><th style="width:150px;"><?php esc_html_e('Plans Created', 'planwise-floor-planner'); ?></th></tr></thead>
                <tbody>
                    <?php if(empty($project_email_domain_ranking)): ?>
                        <tr><td colspan="2"><?php esc_html_e('No data for this period.', 'planwise-floor-planner'); ?></td></tr>
                    <?php else: foreach($project_email_domain_ranking as $row): ?>
                        <tr>
                            <td><?php echo esc_html($row->domain_name); ?></td>
                            <td><?php echo esc_html($row->domain_count); ?></td>
                        </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div> <?php
}

function planwisewp_render_settings_tab() {
    $is_pro = planwisewp_is_pro();
    if (!current_user_can('manage_options')) { wp_die( esc_html__('Access Denied.', 'planwise-floor-planner') ); }

    if (isset($_POST['planwisewp_save_settings_nonce']) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['planwisewp_save_settings_nonce'] ) ), 'planwisewp_save_settings_action')) {

    if (isset($_POST['planwisewp_unit_system']) && in_array( sanitize_key( $_POST['planwisewp_unit_system'] ), ['metric', 'imperial'])) {
        update_option('planwisewp_unit_system', sanitize_key( wp_unslash( $_POST['planwisewp_unit_system'] ) ));
    }

    $current_unit_system_for_save = get_option('planwisewp_unit_system', 'metric');

    if (isset($_POST['planwisewp_free_window_width'])) {
        $cm_value = planwisewp_admin_getCmFromInput( sanitize_text_field( wp_unslash( $_POST['planwisewp_free_window_width'] ) ), $current_unit_system_for_save);
        update_option('planwisewp_free_window_width', $cm_value);
    }
    if (isset($_POST['planwisewp_free_window_height'])) {
        $cm_value = planwisewp_admin_getCmFromInput( sanitize_text_field( wp_unslash( $_POST['planwisewp_free_window_height'] ) ), $current_unit_system_for_save);
        update_option('planwisewp_free_window_height', $cm_value);
    }
    if (isset($_POST['planwisewp_free_door_width'])) {
        $cm_value = planwisewp_admin_getCmFromInput( sanitize_text_field( wp_unslash( $_POST['planwisewp_free_door_width'] ) ), $current_unit_system_for_save);
        update_option('planwisewp_free_door_width', $cm_value);
    }
    if (isset($_POST['planwisewp_free_door_height'])) {
        $cm_value = planwisewp_admin_getCmFromInput( sanitize_text_field( wp_unslash( $_POST['planwisewp_free_door_height'] ) ), $current_unit_system_for_save);
        update_option('planwisewp_free_door_height', $cm_value);
    }

    if (isset($_POST['planwisewp_page_title'])) {
        update_option('planwisewp_page_title', sanitize_text_field( wp_unslash( $_POST['planwisewp_page_title'] ) ));
    }
    if (isset($_POST['planwisewp_tooltip_title'])) {
        update_option('planwisewp_tooltip_title', sanitize_text_field( wp_unslash( $_POST['planwisewp_tooltip_title'] ) ));
    }
    if (isset($_POST['planwisewp_tooltip_content'])) {
        $clean_tooltip_content = wp_kses_post( stripslashes_deep( wp_unslash( $_POST['planwisewp_tooltip_content'] ) ) );
        update_option('planwisewp_tooltip_content', $clean_tooltip_content);
    }
    if (isset($_POST['planwisewp_logged_out_message'])) {
        $clean_logged_out_message = wp_kses_post( stripslashes_deep( wp_unslash( $_POST['planwisewp_logged_out_message'] ) ) );
        update_option('planwisewp_logged_out_message', $clean_logged_out_message);
    }

    if (isset($_POST['planwisewp_room_list'])) {
        $rooms_raw = explode("\n", sanitize_textarea_field( wp_unslash( $_POST['planwisewp_room_list'] ) ));
        $rooms_clean = array_map('trim', $rooms_raw);
        $rooms_filtered = array_filter($rooms_clean);
        update_option('planwisewp_room_list', json_encode(array_values($rooms_filtered)));
    }

    if (isset($_POST['planwisewp_marker_color'])) {
        update_option('planwisewp_marker_color', sanitize_hex_color( wp_unslash( $_POST['planwisewp_marker_color'] ) ));
    }

    $button_colors = [];
    if (isset($_POST['planwisewp_button_colors']) && is_array($_POST['planwisewp_button_colors'])) {
        $unslashed_colors = wp_unslash( $_POST['planwisewp_button_colors'] );
        foreach($unslashed_colors as $key => $color) {
            $button_colors[sanitize_key($key)] = sanitize_hex_color($color);
        }
        update_option('planwisewp_button_colors', $button_colors);
    }

    add_settings_error('planwisewp_settings', 'settings_updated', __('Settings saved successfully.', 'planwise-floor-planner'), 'updated');
}

     settings_errors('planwisewp_settings');

     $unit_system = get_option('planwisewp_unit_system', 'metric');
     $page_title = get_option('planwisewp_page_title', __('PlanWiseWP online floor plan and measurement report creation', 'planwise-floor-planner'));
     $tooltip_title = get_option('planwisewp_tooltip_title', __('Usage Guide', 'planwise-floor-planner'));
     $free_win_w_cm = get_option('planwisewp_free_window_width', '100');
     $free_win_h_cm = get_option('planwisewp_free_window_height', '120');
     $free_door_w_cm = get_option('planwisewp_free_door_width', '80');
     $free_door_h_cm = get_option('planwisewp_free_door_height', '210');
     $display_win_w = planwisewp_admin_getValueForInput($free_win_w_cm, $unit_system);
     $display_win_h = planwisewp_admin_getValueForInput($free_win_h_cm, $unit_system);
     $display_door_w = planwisewp_admin_getValueForInput($free_door_w_cm, $unit_system);
     $display_door_h = planwisewp_admin_getValueForInput($free_door_h_cm, $unit_system);
     $free_size_unit_label = ($unit_system === 'metric') ? 'cm' : 'in'; 
     $default_tooltip_content_value = sprintf(
        '<h4>%1$s</h4><p><strong>%2$s:</strong> %3$s</p><p><strong>%4$s:</strong> %5$s</p><p><strong>%6$s:</strong> %7$s</p><p><strong>%8$s:</strong> %9$s</p><p><strong>%10$s:</strong> %11$s</p><p><strong>%12$s:</strong> %13$s</p><p><strong>%14$s:</strong> %15$s</p><p><strong>%16$s:</strong> %17$s</p><p><strong>%18$s:</strong> %19$s</p><p><strong>%20$s:</strong> %21$s</p><p><strong>%22$s:</strong> %23$s</p>',
        esc_html__('Usage Guide', 'planwise-floor-planner'), esc_html__('Basic Settings', 'planwise-floor-planner'), esc_html__('Enter the ceiling height and the thinnest partition wall thickness.', 'planwise-floor-planner'), esc_html__('Creating Rooms', 'planwise-floor-planner'), esc_html__('Select a room name, enter its dimensions (internal measurements), then click the \'+\' button.', 'planwise-floor-planner'), esc_html__('Moving', 'planwise-floor-planner'), esc_html__('Hold down the left mouse button and move the element. Elements snap magnetically. On touch screens, touch and drag.', 'planwise-floor-planner'), esc_html__('Connecting Walls', 'planwise-floor-planner'), esc_html__('The distance between rooms should be at least the wall thickness, maximum twice that. Use the Pillar/Wall Filler element for thicker walls (PRO).', 'planwise-floor-planner'), esc_html__('Selection & Functions', 'planwise-floor-planner'), esc_html__('Right-click on an element to open the menu (resize, rotate, delete). On touch screens, tap, then long-press the element.', 'planwise-floor-planner'), esc_html__('Tiled Height', 'planwise-floor-planner'), esc_html__('You can specify the height of the room\'s tiling in the right-click menu (PRO).', 'planwise-floor-planner'), esc_html__('Openings', 'planwise-floor-planner'), esc_html__('Set the size, click the \'+\' button, then click on the wall. For windows, also enter the sill height.', 'planwise-floor-planner'), esc_html__('Markers', 'planwise-floor-planner'), esc_html__('Click the \'!\' button, then click on the drawing to place a marker (PRO).', 'planwise-floor-planner'), esc_html__('Panning View', 'planwise-floor-planner'), esc_html__('Hold down the right mouse button or use two fingers to move the canvas.', 'planwise-floor-planner'), esc_html__('Zooming', 'planwise-floor-planner'), esc_html__('Use the mouse wheel, the +/- buttons, or two-finger pinch.', 'planwise-floor-planner'), esc_html__('Saving/Loading/Exporting', 'planwise-floor-planner'), esc_html__('Use the Project and Export buttons (Saving/Loading and advanced export are PRO features).', 'planwise-floor-planner')
    );
     $tooltip_content = get_option('planwisewp_tooltip_content', $default_tooltip_content_value );

    $default_logged_out_message_value = sprintf(
        '<h1>%1$s</h1><br><p style="text-align: justify;">%2$s</p><p style="text-align: justify;">%3$s</p><p>%4$s</p>',
        esc_html__('Welcome to the PlanWiseWP Online Floor Plan Creator!', 'planwise-floor-planner'),
        esc_html__('Login is required to use the floor plan and measurement report creator. With this tool, you can easily create scaled and dimensioned floor plans directly in your browser for various purposes like home renovation planning, real estate listings, interior design mockups, facility management, or insurance claims documentation. You can save the scaled plan as an image (PRO allows watermark removal and advanced export formats).', 'planwise-floor-planner'),
        esc_html__('The online floor plan creator is free for personal use. Please log in to use the floor plan creator application!', 'planwise-floor-planner'),esc_html__('Please log in to use the PlanWiseWP application!', 'planwise-floor-planner')
    );
     $logged_out_message = get_option('planwisewp_logged_out_message', $default_logged_out_message_value);
     $default_rooms_array = ['Living Room', 'Kitchen', 'Dining Room', 'Bathroom', 'Bedroom 1', 'Bedroom 2', 'Kids Room', 'Office', 'Hallway', 'Corridor', 'Anteroom', 'Walk-in Closet', 'Pantry', 'WC', 'Garage', 'Balcony', 'Basement', 'Storage', 'Utility Room'];
     $room_list_json = get_option('planwisewp_room_list', json_encode($default_rooms_array));
     $room_list_array = json_decode($room_list_json, true);
     $room_list_text = is_array($room_list_array) ? implode("\n", $room_list_array) : '';
     $marker_color = get_option('planwisewp_marker_color', '#dc3545');
     $default_button_colors_array = [
        'add_room' => '#17a2b8', 'filler' => '#17a2b8', 'zoom' => '#6c757d', 
         'hamburger' => '#664BC4',
        'marker_dot' => '#dc3545', 'marker_window' => '#17a2b8', 'marker_door' => '#17a2b8', 'marker_opening' => '#17a2b8',
        'export_png' => '#28a745', 'export_txt' => '#28a745', 'export_csv' => '#28a745',
        'project_save' => '#ffc107', 'project_load' => '#ffc107',
        'edit_rotate' => '#17a2b8', 'edit_delete' => '#dc3545'
    ];
     $button_colors = get_option('planwisewp_button_colors', $default_button_colors_array);

     ?>
     <div class="planwisewp-admin">
         <h2><?php esc_html_e('PlanWiseWP Settings', 'planwise-floor-planner'); ?></h2>

         <div class="planwisewp-usage-box" style="background: #fff; border: 1px solid #ccd0d4; padding: 15px 20px; border-radius: 8px; margin-bottom: 2rem; border-left-width: 4px; border-left-color: var(--pw-primary);">
            <h3 style="margin-top: 0;"><?php esc_html_e('How to use', 'planwise-floor-planner'); ?></h3>
            <p><?php esc_html_e('To display the floor plan editor on any page or post, simply insert the following shortcode into the content:', 'planwise-floor-planner'); ?></p>
            <p><input type="text" value="[planwisewp]" readonly onfocus="this.select();" style="width: 200px; text-align: center; background: #f0f0f0; cursor: copy;"></p>
         </div>
         <form method="post" action="">
            <?php wp_nonce_field('planwisewp_save_settings_action', 'planwisewp_save_settings_nonce'); ?>

            <table class="form-table">
                <tbody>
                    <tr>
                        <th scope="row"><?php esc_html_e('Unit system:', 'planwise-floor-planner'); ?></th>
                        <td>
                            <fieldset>
                                <label style="font-weight: normal; margin-right: 20px;">
                                    <input type="radio" name="planwisewp_unit_system" value="metric" <?php checked($unit_system, 'metric'); ?>>
                                    <?php esc_html_e('Metric (cm / m)', 'planwise-floor-planner'); ?>
                                </label>
                                <label style="font-weight: normal;">
                                    <input type="radio" name="planwisewp_unit_system" value="imperial" <?php checked($unit_system, 'imperial'); ?>>
                                    <?php esc_html_e('Imperial (in / ft)', 'planwise-floor-planner'); ?>
                                </label>
                            </fieldset>
                            <p class="description"><?php esc_html_e('Select the default measurement system for the entire plugin.', 'planwise-floor-planner'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row" colspan="2">
                            <h3 style="margin-bottom: 5px;"><?php esc_html_e('Free version default sizes', 'planwise-floor-planner'); ?></h3>
                            <p style="font-weight: normal; font-style: italic; color: #666; margin-top: 0;"><?php esc_html_e('Set the fixed opening sizes for the free version.', 'planwise-floor-planner'); ?></p>
                        </th>
                    </tr>
                    <tr>
                        <th scope="row"><label for="planwisewp_free_window_width">
                            <?php 
                            /* translators: %s: unit label (e.g., 'cm' or 'in') */
                            printf(esc_html__('Free window width (%s):', 'planwise-floor-planner'), esc_html($free_size_unit_label)); 
                            ?>
                        </label></th>
                        <td><input type="number" name="planwisewp_free_window_width" id="planwisewp_free_window_width" value="<?php echo esc_attr($display_win_w); ?>" data-cm-value="<?php echo esc_attr($free_win_w_cm); ?>" class="regular-text free-default-size-input" style="width: 100px;" min="1" step="0.1"> <span class="unit-label"><?php echo esc_html($free_size_unit_label); ?></span></td>
                    </tr>
                     <tr>
                        <th scope="row"><label for="planwisewp_free_window_height">
                            <?php 
                            /* translators: %s: unit label (e.g., 'cm' or 'in') */
                            printf(esc_html__('Free window height (%s):', 'planwise-floor-planner'), esc_html($free_size_unit_label)); 
                            ?>
                        </label></th>
                        <td><input type="number" name="planwisewp_free_window_height" id="planwisewp_free_window_height" value="<?php echo esc_attr($display_win_h); ?>" data-cm-value="<?php echo esc_attr($free_win_h_cm); ?>" class="regular-text free-default-size-input" style="width: 100px;" min="1" step="0.1"> <span class="unit-label"><?php echo esc_html($free_size_unit_label); ?></span></td>
                    </tr>
                     <tr>
                        <th scope="row"><label for="planwisewp_free_door_width">
                            <?php 
                            /* translators: %s: unit label (e.g., 'cm' or 'in') */
                            printf(esc_html__('Free door width (%s):', 'planwise-floor-planner'), esc_html($free_size_unit_label)); 
                            ?>
                        </label></th>
                        <td><input type="number" name="planwisewp_free_door_width" id="planwisewp_free_door_width" value="<?php echo esc_attr($display_door_w); ?>" data-cm-value="<?php echo esc_attr($free_door_w_cm); ?>" class="regular-text free-default-size-input" style="width: 100px;" min="1" step="0.1"> <span class="unit-label"><?php echo esc_html($free_size_unit_label); ?></span></td>
                    </tr>
                     <tr>
                        <th scope="row"><label for="planwisewp_free_door_height">
                            <?php 
                            /* translators: %s: unit label (e.g., 'cm' or 'in') */
                            printf(esc_html__('Free door height (%s):', 'planwise-floor-planner'), esc_html($free_size_unit_label)); 
                            ?>
                        </label></th>
                        <td><input type="number" name="planwisewp_free_door_height" id="planwisewp_free_door_height" value="<?php echo esc_attr($display_door_h); ?>" data-cm-value="<?php echo esc_attr($free_door_h_cm); ?>" class="regular-text free-default-size-input" style="width: 100px;" min="1" step="0.1"> <span class="unit-label"><?php echo esc_html($free_size_unit_label); ?></span></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="planwisewp_page_title"><?php esc_html_e('Frontend page title (H1):', 'planwise-floor-planner'); ?></label></th>
                        <td><input type="text" name="planwisewp_page_title" id="planwisewp_page_title" value="<?php echo esc_attr($page_title); ?>" class="regular-text"></td>
                    </tr>

                    <tr>
                        <th scope="row"><label for="planwisewp_tooltip_title"><?php esc_html_e('Tooltip trigger text:', 'planwise-floor-planner'); ?></label></th>
                        <td><input type="text" name="planwisewp_tooltip_title" id="planwisewp_tooltip_title" value="<?php echo esc_attr($tooltip_title); ?>" class="regular-text"></td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="planwisewp_tooltip_content"><?php esc_html_e('Tooltip content (HTML allowed):', 'planwise-floor-planner'); ?></label></th>
                        <td>
                            <?php 
                            wp_editor($tooltip_content, 'planwisewp_tooltip_content', [
                                'textarea_name' => 'planwisewp_tooltip_content', 
                                'textarea_rows' => 15, 
                                'media_buttons' => false, 
                                'tinymce' => [
                                    'content_style' => 'body { font-family: Inter, sans-serif; }'
                                ]
                            ]);
                            ?>
                            <p class="description">
                                <?php esc_html_e('Allowed HTML tags for formatting:', 'planwise-floor-planner'); ?> 
                                <code>&lt;p&gt;</code>, <code>&lt;br&gt;</code>, <code>&lt;strong&gt;</code> (<?php esc_html_e('bold', 'planwise-floor-planner'); ?>), <code>&lt;b&gt;</code> (<?php esc_html_e('bold', 'planwise-floor-planner'); ?>), <code>&lt;em&gt;</code> (<?php esc_html_e('italic', 'planwise-floor-planner'); ?>), <code>&lt;i&gt;</code> (<?php esc_html_e('italic', 'planwise-floor-planner'); ?>), <code>&lt;ul&gt;</code> (<?php esc_html_e('list', 'planwise-floor-planner'); ?>), <code>&lt;ol&gt;</code> (<?php esc_html_e('numbered list', 'planwise-floor-planner'); ?>), <code>&lt;li&gt;</code> (<?php esc_html_e('list item', 'planwise-floor-planner'); ?>), <code>&lt;h4&gt;</code> (<?php esc_html_e('heading', 'planwise-floor-planner'); ?>).
                            </p>
                            </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="planwisewp_room_list"><?php esc_html_e('Room name presets:', 'planwise-floor-planner'); ?></label></th>
                        <td>
                            <textarea name="planwisewp_room_list" id="planwisewp_room_list" rows="10" class="large-text"><?php echo esc_textarea($room_list_text); ?></textarea>
                            <p class="description"><?php esc_html_e('Enter one room name per line. These will appear in the "New Room" dropdown.', 'planwise-floor-planner'); ?></p>
                        </td>
                    </tr>
                     <tr>
                        <th scope="row"><label for="planwisewp_logged_out_message"><?php esc_html_e('Logged-out user message (HTML allowed):', 'planwise-floor-planner'); ?></label></th>
                        <td><?php wp_editor($logged_out_message, 'planwisewp_logged_out_message', ['textarea_name' => 'planwisewp_logged_out_message', 'textarea_rows' => 15, 'media_buttons' => true]);?>
                           <p class="description">
                                <?php 
                                /* translators: %s: placeholder code <code>[login_button]</code> */
                                printf(esc_html__('Use %s where you want the login button to appear (the link is added automatically by the shortcode).', 'planwise-floor-planner'), '<code>[login_button]</code>'); 
                                ?>
                           </p>
                           <p class="description"><?php esc_html_e('You can add shortcodes or other dynamic content here.', 'planwise-floor-planner'); ?></p>
                           <p class="description">
                                <?php esc_html_e('Allowed HTML tags for formatting:', 'planwise-floor-planner'); ?> 
                                <code>&lt;p&gt;</code>, <code>&lt;br&gt;</code>, <code>&lt;strong&gt;</code> (<?php esc_html_e('bold', 'planwise-floor-planner'); ?>), <code>&lt;b&gt;</code> (<?php esc_html_e('bold', 'planwise-floor-planner'); ?>), <code>&lt;em&gt;</code> (<?php esc_html_e('italic', 'planwise-floor-planner'); ?>), <code>&lt;i&gt;</code> (<?php esc_html_e('italic', 'planwise-floor-planner'); ?>), <code>&lt;ul&gt;</code> (<?php esc_html_e('list', 'planwise-floor-planner'); ?>), <code>&lt;ol&gt;</code> (<?php esc_html_e('numbered list', 'planwise-floor-planner'); ?>), <code>&lt;li&gt;</code> (<?php esc_html_e('list item', 'planwise-floor-planner'); ?>), <code>&lt;h4&gt;</code> (<?php esc_html_e('heading', 'planwise-floor-planner'); ?>).
                           </p>
                        </td>
                    </tr>
                     <tr>
                         <th scope="row"><?php esc_html_e('Button colors:', 'planwise-floor-planner'); ?></th>
                         <td>
                             <?php
                             $current_colors = is_array($button_colors) ? $button_colors : $default_button_colors_array;
                             $merged_colors = wp_parse_args($current_colors, $default_button_colors_array); 

                             foreach ($merged_colors as $key => $color):
                                $label = ucwords(str_replace(['_', '-'], ' ', $key));
                                $label_map = [
                                    'Add Room' => __('Add Room', 'planwise-floor-planner'),
                                    'Filler' => __('Pillar/Filler', 'planwise-floor-planner'),
                                    'Zoom' => __('Zoom In/Out', 'planwise-floor-planner'),
                                    'Hamburger' => __('Hamburger Menu', 'planwise-floor-planner'),
                                    'Marker Dot' => __('Marker (!)', 'planwise-floor-planner'),
                                    'Marker Window' => __('Marker (Window)', 'planwise-floor-planner'),
                                     'Marker Door' => __('Marker (Door)', 'planwise-floor-planner'),
                                     'Marker Opening' => __('Marker (Opening)', 'planwise-floor-planner'),
                                     'Export Png' => __('Export PNG', 'planwise-floor-planner'),
                                     'Export Txt' => __('Export TXT', 'planwise-floor-planner'),
                                     'Export Csv' => __('Export CSV', 'planwise-floor-planner'),
                                     'Project Save' => __('Project Save', 'planwise-floor-planner'),
                                     'Project Load' => __('Project Load', 'planwise-floor-planner'),
                                     'Edit Rotate' => __('Edit Rotate', 'planwise-floor-planner'),
                                     'Edit Delete' => __('Edit Delete', 'planwise-floor-planner'),
                                ];
                                $label = $label_map[$label] ?? $label;
                             ?>
                                <p style="margin-bottom: 5px;">
                                    <label for="color_<?php echo esc_attr($key); ?>" style="display:inline-block; width: 160px; padding-right: 10px;"><?php echo esc_html($label); ?>:</label>
                                    <input type="color" id="color_<?php echo esc_attr($key); ?>" name="planwisewp_button_colors[<?php echo esc_attr($key); ?>]" value="<?php echo esc_attr($color); ?>">
                                </p>
                             <?php endforeach; ?>
                             <p class="description"><?php esc_html_e('Customize the background color of frontend buttons.', 'planwise-floor-planner'); ?></p>
                         </td>
                     </tr>

                </tbody>
            </table>

            <?php submit_button(__('Save settings', 'planwise-floor-planner')); ?>
         </form>
         <div style="margin-top: 3rem; padding-top: 1.5rem; border-top: 1px dashed #ccc;">
             <h2><?php esc_html_e('Reset Settings', 'planwise-floor-planner'); ?></h2>
             <p style="color: #c00; font-weight: bold;"><?php esc_html_e('Warning: This action cannot be undone. All PlanWiseWP settings will be permanently deleted and reset to their default values.', 'planwise-floor-planner'); ?></p>
             <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" id="planwisewp-reset-form">
                 <input type="hidden" name="action" value="planwisewp_reset_settings">
                 <?php wp_nonce_field('planwisewp_reset_settings_action', 'planwisewp_reset_settings_nonce'); ?>
                 <?php submit_button(
                        __('Reset All Settings to Default', 'planwise-floor-planner'),
                        'delete',
                        'planwisewp_reset_button',
                        true,
                        ['id' => 'planwisewp-reset-button-confirm'] 
                    ); ?>
             </form>
     </div> <?php
     wp_enqueue_media();
     ?>
     <?php
 }

function planwisewp_render_project_log_tab() {
    $is_pro = planwisewp_is_pro();
     if (!current_user_can('manage_options')) { wp_die( esc_html__('Access Denied.', 'planwise-floor-planner') ); }
     global $wpdb;
     $table_name = $wpdb->prefix . 'planwisewp_projects'; 
     $unit_system = get_option('planwisewp_unit_system', 'metric');
     
     if ($wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $table_name ) ) != $table_name) { 
         echo '<h2>' . esc_html__('Project log', 'planwise-floor-planner') . '</h2>';
         echo '<p>' . esc_html__('The project log table does not exist. Please reactivate the plugin.', 'planwise-floor-planner') . '</p>';
         return; 
     }
     
     $items_per_page = 50;
     $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
     $offset = ($current_page - 1) * $items_per_page;
     $total_items = $wpdb->get_var("SELECT COUNT(id) FROM {$wpdb->prefix}planwisewp_projects");
     $total_pages = ceil($total_items / $items_per_page);
     $logs = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}planwisewp_projects ORDER BY created_at DESC LIMIT %d OFFSET %d", $items_per_page, $offset));

     ?>
     <div class="planwisewp-admin">
         <h2><?php esc_html_e('Project Log', 'planwise-floor-planner'); ?></h2>
         <p>
            <?php 
            /* translators: %s: a formatted number (e.g., '<strong>123</strong>') */
            printf( wp_kses( __( 'Total of %s saved projects found in the log.', 'planwise-floor-planner' ), [ 'strong' => [] ] ), '<strong>' . esc_html( number_format_i18n( $total_items, 0 ) ) . '</strong>' ); 
            ?>
         </p>
         <?php if (!empty($logs)) : ?>
             <table class="wp-list-table widefat fixed striped">
                 <thead>
                    <tr>
                         <th style="width: 160px;"><?php esc_html_e('Date', 'planwise-floor-planner'); ?></th>
                         <th><?php esc_html_e('User', 'planwise-floor-planner'); ?></th>
                         <th><?php esc_html_e('Email', 'planwise-floor-planner'); ?></th>
                         <th style="text-align:center; width: 80px;"><?php esc_html_e('Rooms', 'planwise-floor-planner'); ?></th>
                         <th style="text-align:right; width: 120px;">
                            <?php 
                            /* translators: %s: unit label (e.g., 'm²' or 'sq ft') */
                            printf(esc_html__('Total Area (%s)', 'planwise-floor-planner'), esc_html($unit_system === 'metric' ? 'm²' : 'sq ft')); 
                            ?>
                         </th>
                         <th> 
                        </th>
                    </tr>
                </thead>
                 <tbody>
                     <?php foreach ($logs as $log) : 
                     ?>
                         <tr>
                             <td><?php echo esc_html($log->created_at); ?></td>
                             <td><?php echo esc_html($log->user_name); ?></td>
                             <td><?php echo esc_html($log->user_email); ?></td>
                             <td style="text-align:center;"><?php echo esc_html($log->rooms_count); ?></td>
                             <td style="text-align:right;"><?php echo esc_html(planwisewp_admin_formatArea($log->total_floor_area, $unit_system)); ?></td>
                             <td style="text-align:center;">
                             </td>
                             <td style="text-align:center;">
                             </td>
                             <td style="text-align:center;">
                             </td>
                         </tr>
                     <?php endforeach; ?>
                 </tbody>
             </table>
         <?php else : ?>
             <p><?php esc_html_e('No log entries found yet.', 'planwise-floor-planner'); ?></p>
         <?php endif; ?>
         <?php if ($total_pages > 1) : ?>
             <div class="tablenav"><div class="tablenav-pages" style="margin: 1em 0;">
                 <?php
                 echo wp_kses_post( paginate_links([
                     'base'      => add_query_arg('paged', '%#%'),
                     'format'    => '?paged=%#%',
                     'current'   => $current_page,
                     'total'     => $total_pages,
                     'prev_text' => __('&laquo; Previous', 'planwise-floor-planner'),
                     'next_text' => __('Next &raquo;', 'planwise-floor-planner'),
                 ]) );
                 ?>
             </div></div>
         <?php endif; ?>
     </div>
     <div id="json-modal" style="display:none; position:fixed; z-index:9999; left:0; top:0; width:100%; height:100%; overflow:auto; background-color:rgba(0,0,0,0.6);">
         <div style="background-color:#fefefe; margin:10% auto; padding:20px; border:1px solid #888; width:80%; max-width:800px; border-radius: 8px; position:relative;">
             <span id="json-modal-close" style="color:#aaa; float:right; font-size:28px; font-weight:bold; cursor:pointer;">&times;</span>
             <h4><?php esc_html_e('Saved project data (JSON)', 'planwise-floor-planner'); ?></h4>
             <pre style="white-space:pre-wrap; word-wrap:break-word; background-color:#f0f0f0; padding:15px; border-radius:4px; max-height: 400px; overflow-y: auto;"></pre>
         </div>
     </div>
     <?php
 }

function planwisewp_render_admin_page() {
    $active_tab = isset($_GET['tab']) ? sanitize_key( wp_unslash( $_GET['tab'] ) ) : 'settings'; 
    ?>
    <div class="wrap">
        <h1><?php esc_html_e('PlanWiseWP Administration', 'planwise-floor-planner'); ?></h1>

        <nav class="nav-tab-wrapper">
            <a href="?page=planwisewp-admin&tab=settings" class="nav-tab <?php echo $active_tab == 'settings' ? 'nav-tab-active' : ''; ?>"><?php esc_html_e('Settings', 'planwise-floor-planner'); ?></a>
            <a href="?page=planwisewp-admin&tab=project_log" class="nav-tab <?php echo $active_tab == 'project_log' ? 'nav-tab-active' : ''; ?>"><?php esc_html_e('Project Log', 'planwise-floor-planner'); ?></a>
            <a href="?page=planwisewp-admin&tab=statistics" class="nav-tab <?php echo $active_tab == 'statistics' ? 'nav-tab-active' : ''; ?>"><?php esc_html_e('Statistics', 'planwise-floor-planner'); ?></a>
            <?php 
            if (function_exists('pwfp_fs') && is_object(pwfp_fs())) {
                if (method_exists(pwfp_fs(), 'get_account_url')) {
                    echo '<a href="' . esc_url(pwfp_fs()->get_account_url()) . '" class="nav-tab">' . esc_html__('Account', 'planwise-floor-planner') . '</a>';
                }
                if (method_exists(pwfp_fs(), 'is_premium') && !pwfp_fs()->is_premium() && method_exists(pwfp_fs(), 'get_upgrade_url')) {
                echo '<a href="' . esc_url(pwfp_fs()->get_upgrade_url()) . '" class="nav-tab">' . esc_html__('Upgrade to PRO', 'planwise-floor-planner') . '</a>';}
            }
            ?>
        </nav>

        <div class="tab-content" style="margin-top: 20px;">
            <?php
            switch ($active_tab) {
                case 'project_log':
                    planwisewp_render_project_log_tab(); 
                    break;
                case 'statistics':
                    planwisewp_render_statistics_tab(); 
                    break;
                case 'settings':
                default:
                    planwisewp_render_settings_tab(); 
                    break;
            }
            ?>
        </div>
    </div>
    <?php
}

function planwisewp_admin_notices() {
    
    $page = isset($_GET['page']) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
    $message = isset($_GET['message']) ? sanitize_key( wp_unslash( $_GET['message'] ) ) : '';

    if ($page === 'planwisewp-admin') {

        settings_errors('planwisewp_settings');

        if (!empty($message)) {
            $message_text = '';
            $type = 'success';
            
            switch ($message) {
                 case 'error': $message_text = __('An error occurred. Please try again.', 'planwise-floor-planner'); $type = 'error'; break;
                 case 'delete_error': $message_text = __('Error deleting log entry.', 'planwise-floor-planner'); $type = 'error'; break;
                 case 'settings_reset': $message_text = __('All PlanWiseWP settings have been reset to their default values.', 'planwise-floor-planner'); $type = 'success'; break;    
            }

            if ($message_text) {
                add_settings_error('planwisewp_main', 'planwisewp_message', $message_text, $type);
            }
        }
        settings_errors('planwisewp_main');
    }
}
add_action('admin_notices', 'planwisewp_admin_notices');
add_action('admin_post_planwisewp_reset_settings', 'planwisewp_handle_reset_settings');
?>