<?php

namespace PageVICO\Admin;

defined( 'ABSPATH' ) || exit;
class SettingsPage {
    public static function init() {
        add_action( 'admin_menu', array(__CLASS__, 'registerMenu'), 99 );
        add_action( 'admin_init', array(__CLASS__, 'registerSettings') );
        add_action( 'admin_enqueue_scripts', array(__CLASS__, 'enqueueAssets') );
        add_action( 'wp_ajax_pagevico_reset_settings', array(__CLASS__, 'handleResetSettings') );
        add_action( 'wp_ajax_pagevico_manage_partitions', array(__CLASS__, 'handleManagePartitions') );
        add_action( 'admin_enqueue_scripts', function () {
            if ( isset( $_GET['page'] ) && in_array( $_GET['page'], ['pagevico-dashboard-account', 'pagevico-dashboard-pricing', 'pagevico-dashboard-affiliation'] ) ) {
                wp_add_inline_style( 'wp-admin', '
		/* Freemius Pages Theming (Account, Upgrade, Affiliate) */
		
		.fs-section, .fs-wrap {
			background: #fff;
			border-radius: 16px;
			box-shadow: var(--shadow-md, 0 2px 8px rgba(0,0,0,0.04));
			border: 1px solid var(--neutral-200, #e6e6e6);
			padding: 1.5rem;
			font-family: "Segoe UI", system-ui, sans-serif;
		}
		
		.nav-tab-wrapper {
			border-bottom: 1px solid var(--neutral-200);
			margin-bottom: 1rem;
		}
		.nav-tab {
			background: var(--neutral-100);
			border: 1px solid var(--neutral-200);
			color: var(--neutral-600);
			border-radius: 8px 8px 0 0;
			font-weight: 500;
			padding: 0.6rem 1.2rem;
		}
		.nav-tab-active {
			background: #fff;
			border-bottom: 1px solid #fff;
			color: var(--primary-600);
		}
		
		.fs-section h3,
		.fs-section h4 {
			font-size: 1.1rem;
			color: var(--neutral-800);
			font-weight: 600;
			margin-bottom: 1rem;
		}
		
		.fs-key-value-table td {
			padding: 1rem 1.5rem;
		}
		.fs-key-value-table td:first-child {
			color: var(--neutral-600);
			font-weight: 500;
		}
		.fs-key-value-table code {
			background: var(--neutral-50);
			padding: 2px 6px;
			border-radius: 4px;
			font-family: monospace;
			color: var(--neutral-800);
		}
		
		.fs-tag.fs-warn {
			background: var(--danger-50);
			color: var(--danger-600);
			font-weight: 600;
			padding: 2px 8px;
			border-radius: 999px;
			font-size: 0.75rem;
		}
		
		.button,
		input[type=submit],
		.fs-button-inline {
			background: var(--neutral-100);
			border: 1px solid var(--neutral-200);
			color: var(--neutral-700);
			padding: 0.5rem 1rem;
			border-radius: 6px;
			font-weight: 500;
			font-size: 0.875rem;
			transition: all 0.2s ease;
		}
		.button:hover,
		.fs-button-inline:hover {
			background: var(--neutral-200);
			color: var(--neutral-900);
		}
		.button-primary,
		.fs-upgrade.button-primary {
			background: var(--primary-500) !important;
			border-color: var(--primary-500) !important;
			color: #fff !important;
		}
		.button-primary:hover {
			background: var(--primary-600) !important;
			border-color: var(--primary-600) !important;
		}
		
		.fs-header-actions a,
		.fs-button-inline {
			color: var(--danger-500);
			font-weight: 500;
		}
		.fs-button-inline .dashicons {
			font-size: 1rem;
		}
		
		/* Modal Styling */
		.fs-modal-dialog {
			background: #fff;
			border-radius: 12px;
			box-shadow: var(--shadow-lg, 0 12px 36px rgba(0,0,0,0.15));
		}
		.fs-modal-header h4 {
			color: var(--neutral-800);
			font-size: 1.1rem;
			font-weight: 600;
		}
		.fs-modal-body p {
			color: var(--neutral-700);
			font-size: 0.875rem;
		}
		.fs-modal-footer .button-primary {
			background-color: var(--danger-500) !important;
			border-color: var(--danger-500) !important;
			color: white !important;
		}
		.fs-modal-footer .button-secondary {
			background-color: var(--neutral-100);
			color: var(--neutral-800);
		}
		
		/* Affiliate Page */
		.fs-section .fs-affiliate-stats,
		.fs-section .fs-affiliate-details {
			background: var(--neutral-50);
			border-radius: 12px;
			padding: 1.25rem;
			margin-bottom: 1.5rem;
			border: 1px solid var(--neutral-200);
		}
		.fs-section .fs-affiliate-stats h4 {
			margin-top: 0;
		}
		.fs-section .fs-affiliate-details table td {
			padding: 0.75rem 1rem;
			font-size: 0.875rem;
			color: var(--neutral-700);
		}
		.fs-section .fs-affiliate-details code {
			background: var(--neutral-100);
			padding: 0.25rem 0.5rem;
			border-radius: 4px;
		}
		
		/* Responsive */
		@media screen and (max-width: 782px) {
			.fs-key-value-table td {
				padding: 0.75rem 1rem;
			}
			.fs-modal-dialog {
				margin: 1rem;
			}
		}
		
		/* Freemius Affiliate Page Customization */
		.pagevico-dashboard-affiliate {
			background-color: var(--neutral-50);
			padding: 2rem;
		}
		
		/* Wrapper Styling */
		#fs_affiliation_content_wrapper {
			background: #fff;
			border-radius: 16px;
			box-shadow: var(--shadow-md);
			border: 1px solid var(--neutral-200);
			padding: 2rem;
			font-family: inherit;
		}
		
		/* Headings and Description */
		#fs_affiliation_content_wrapper h3 {
			font-size: 1.1rem;
			color: var(--neutral-800);
			font-weight: 600;
			margin-top: 2rem;
		}
		
		#fs_affiliation_content_wrapper p,
		#fs_affiliation_content_wrapper ul {
			color: var(--neutral-700);
			font-size: 0.95rem;
			line-height: 1.6;
			margin-bottom: 1rem;
		}
		
		#fs_affiliation_content_wrapper ul {
			padding-left: 1.5rem;
		}
		
		/* Input Containers */
		#fs_affiliation_content_wrapper .input-container {
			margin-bottom: 1.25rem;
		}
		
		.input-label {
			display: block;
			font-weight: 600;
			color: var(--neutral-800);
			margin-bottom: 0.5rem;
			font-size: 0.9rem;
		}
		
		input.regular-text,
		textarea.regular-text {
			width: 100%;
			padding: 0.6rem 0.75rem;
			border: 1px solid var(--neutral-200);
			border-radius: 6px;
			font-size: 0.95rem;
			background: #fff;
			color: var(--neutral-800);
		}
		
		/* Description Text */
		.input-container .description {
			font-size: 0.85rem;
			color: var(--neutral-600);
			margin-top: 0.4rem;
		}
		
		/* Domain Add Link */
		#add_domain {
			display: inline-block;
			margin-top: 0.5rem;
			color: var(--primary-600);
			font-size: 0.85rem;
			font-weight: 500;
		}
		
		#add_domain.disabled {
			pointer-events: none;
			color: var(--neutral-400);
		}
		
		/* Extra Domains */
		.extra-domain-input-container {
			display: flex;
			gap: 0.5rem;
			align-items: center;
			margin-bottom: 0.5rem;
		}
		
		.extra-domain-input-container input {
			flex-grow: 1;
		}
		
		.remove-domain .dashicons-no {
			color: var(--danger-500);
			cursor: pointer;
		}
		
		/* Consent Checkbox */
		#legal_consent_checkbox {
			margin-right: 0.5rem;
		}
		
		/* Buttons */
		#fs_affiliation_content_wrapper .button {
			background: var(--neutral-100);
			border: 1px solid var(--neutral-200);
			color: var(--neutral-700);
			padding: 0.6rem 1.2rem;
			border-radius: 6px;
			font-size: 0.875rem;
			font-weight: 500;
			transition: all 0.2s ease;
			margin-top: 1.5rem;
			height: 55px !important;
		}
		
		#fs_affiliation_content_wrapper .button:hover {
			background: var(--neutral-200);
			color: var(--neutral-900);
		}
		
		#fs_affiliation_content_wrapper .button-primary {
			background: var(--primary-500) !important;
			border-color: var(--primary-500) !important;
			color: #fff !important;
		}
		
		#fs_affiliation_content_wrapper .button-primary:hover {
			background: var(--primary-600) !important;
			border-color: var(--primary-600) !important;
		}
		
		/* Error and Success Messages */
		#error_message,
		#message {
			padding: 1rem;
			border-radius: 6px;
			font-size: 0.9rem;
			margin-bottom: 1rem;
		}
		
		#error_message {
			background: var(--danger-50);
			color: var(--danger-600);
			border: 1px solid var(--danger-500);
		}
		
		#message {
			background: var(--success-50);
			color: var(--success-600);
			border: 1px solid var(--success-500);
		}
		
		/* Responsive Tweaks */
		@media (max-width: 768px) {
			.extra-domain-input-container {
				flex-direction: column;
				align-items: stretch;
			}
		}
		
				' );
            }
        } );
    }

    public static function registerMenu() {
        add_submenu_page(
            'pagevico-dashboard',
            // translators: %s: Page title
            __( 'Settings', 'page-visit-counter-analytics' ),
            // translators: %s: Menu title
            __( 'Settings', 'page-visit-counter-analytics' ),
            'manage_options',
            'pagevico-settings',
            array(__CLASS__, 'renderPage')
        );
    }

    public static function registerSettings() {
        // Register settings with proper sanitization callbacks
        register_setting( 'PageVICO_settings', 'PageVICO_enable_tracking', 'rest_sanitize_boolean' );
        register_setting( 'PageVICO_settings', 'PageVICO_short_number', 'rest_sanitize_boolean' );
        register_setting( 'PageVICO_settings', 'PageVICO_post_types', array(__CLASS__, 'sanitizeArray') );
        register_setting( 'PageVICO_settings', 'PageVICO_exclude_roles', array(__CLASS__, 'sanitizeArray') );
        register_setting( 'PageVICO_settings', 'PageVICO_block_users', array(__CLASS__, 'sanitizeArray') );
        register_setting( 'PageVICO_settings', 'PageVICO_block_posts', array(__CLASS__, 'sanitizeIntArray') );
        register_setting( 'PageVICO_settings', 'PageVICO_block_ips', 'sanitize_textarea_field' );
        register_setting( 'PageVICO_settings', 'PageVICO_analytics_retention', 'absint' );
        register_setting( 'PageVICO_settings', 'PageVICO_heatmap_retention', 'absint' );
        register_setting( 'PageVICO_settings', 'session_timeout_minutes', 'absint' );
        // Call the original settings manager if needed for additional settings
        \PageVICO\Settings\SettingsManager::registerSettings();
    }

    /**
     * Sanitize an array of strings
     */
    public static function sanitizeArray( $input ) {
        if ( !is_array( $input ) ) {
            return array();
        }
        return array_map( 'sanitize_text_field', $input );
    }

    /**
     * Sanitize an array of integers
     */
    public static function sanitizeIntArray( $input ) {
        if ( !is_array( $input ) ) {
            return array();
        }
        return array_map( 'intval', $input );
    }

    public static function handleResetSettings() {
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Unauthorized' );
        }
        check_ajax_referer( 'PageVICO_reset_settings', 'nonce' );
        \PageVICO\Settings\SettingsManager::resetSettings();
        wp_send_json_success( array(
            'message' => __( 'Settings have been reset to default values.', 'page-visit-counter-analytics' ),
        ) );
    }

    public static function handleManagePartitions() {
        if ( !current_user_can( 'manage_options' ) ) {
            wp_send_json_error( 'Unauthorized' );
        }
        check_ajax_referer( 'PageVICO_manage_partitions', 'nonce' );
        // Run the partition management
        $result = \PageVICO\Database\Installer::manage_partitions();
        if ( $result ) {
            wp_send_json_success( [
                'message' => __( 'Database partitions have been successfully updated.', 'page-visit-counter-analytics' ),
            ] );
        } else {
            wp_send_json_error( [
                'message' => __( 'Failed to update database partitions. Check server logs for details.', 'page-visit-counter-analytics' ),
            ] );
        }
    }

    public static function enqueueAssets( $hook ) {
        $page = ( isset( $_GET['page'] ) ? sanitize_key( $_GET['page'] ) : '' );
        if ( $page !== 'pagevico-settings' ) {
            return;
        }
        // Register Bootstrap CSS
        wp_register_style(
            'pagevico-bootstrap',
            PageVICO_PLUGIN_URL . 'assets/css/bootstrap.min.css',
            array(),
            '5.3.3'
        );
        // Register admin styles
        wp_register_style(
            'pagevico-admin-styles',
            PageVICO_PLUGIN_URL . 'assets/css/admin.css',
            array('pagevico-bootstrap'),
            PageVICO_VERSION
        );
        // Add custom color scheme
        $custom_css = "\n\t\t\t:root {\n\t\t\t\t--pagevico-primary: #FF6B00;\n\t\t\t\t--pagevico-secondary: #FFB000; \n\t\t\t\t--pagevico-body: #000000;\n\t\t\t\t--pagevico-gray: #F5F5F5;\n\t\t\t}\n\t\t\t\n\t\t\t.bg-primary { \n\t\t\t\tbackground-color: var(--pagevico-primary) !important; \n\t\t\t}\n\t\t\t.bg-secondary, .bg-warning { \n\t\t\t\tbackground-color: var(--pagevico-secondary) !important; \n\t\t\t}\n\t\t\t.bg-light { \n\t\t\t\tbackground-color: var(--pagevico-gray) !important; \n\t\t\t}\n\t\t\t.bg-info {\n\t\t\t\tbackground-color: var(--pagevico-primary) !important;\n\t\t\t\topacity: 0.9;\n\t\t\t}\n\t\t\t.card-header.bg-info {\n\t\t\t\tborder-bottom: none;\n\t\t\t}\n\t\t\t\n\t\t\t.btn-primary {\n\t\t\t\tbackground-color: var(--pagevico-primary);\n\t\t\t\tborder-color: var(--pagevico-primary);\n\t\t\t}\n\t\t\t.btn-primary:hover, .btn-primary:focus {\n\t\t\t\tbackground-color: #e66100;\n\t\t\t\tborder-color: #e66100;\n\t\t\t}\n\t\t\t\n\t\t\t.btn-warning, .btn-secondary {\n\t\t\t\tbackground-color: var(--pagevico-secondary);\n\t\t\t\tborder-color: var(--pagevico-secondary);\n\t\t\t\tcolor: #000;\n\t\t\t}\n\t\t\t.btn-warning:hover, .btn-secondary:hover, \n\t\t\t.btn-warning:focus, .btn-secondary:focus {\n\t\t\t\tbackground-color: #e59f00;\n\t\t\t\tborder-color: #e59f00;\n\t\t\t\tcolor: #000;\n\t\t\t}\n\t\t\t\n\t\t\t.btn-info {\n\t\t\t\tbackground-color: var(--pagevico-primary);\n\t\t\t\tborder-color: var(--pagevico-primary);\n\t\t\t\tcolor: #fff;\n\t\t\t}\n\t\t\t.btn-info:hover, .btn-info:focus {\n\t\t\t\tbackground-color: #e66100;\n\t\t\t\tborder-color: #e66100;\n\t\t\t\tcolor: #fff;\n\t\t\t}\n\t\t\t\n\t\t\t.nav-pills .nav-link.active, \n\t\t\t.nav-pills .show>.nav-link {\n\t\t\t\tbackground-color: var(--pagevico-primary);\n\t\t\t}\n\t\t\t\n\t\t\t.form-check-input:checked {\n\t\t\t\tbackground-color: var(--pagevico-primary);\n\t\t\t\tborder-color: var(--pagevico-primary);\n\t\t\t}\n\t\t\t\n\t\t\t.badge.bg-primary {\n\t\t\t\tbackground-color: var(--pagevico-primary) !important;\n\t\t\t}\n\t\t\t\n\t\t\t.text-primary {\n\t\t\t\tcolor: var(--pagevico-primary) !important;\n\t\t\t}\n\t\t\t\n\t\t\ta {\n\t\t\t\tcolor: var(--pagevico-primary);\n\t\t\t}\n\t\t\ta:hover {\n\t\t\t\tcolor: #e66100;\n\t\t\t}\n\t\t";
        wp_add_inline_style( 'pagevico-admin-styles', $custom_css );
        // Enqueue styles
        wp_enqueue_style( 'pagevico-bootstrap' );
        wp_enqueue_style( 'pagevico-admin-styles' );
        // Register Bootstrap JS Bundle
        wp_register_script(
            'pagevico-bootstrap-bundle',
            PageVICO_PLUGIN_URL . 'assets/js/bootstrap.bundle.min.js',
            array('jquery'),
            '5.3.3',
            true
        );
        // Register settings script
        wp_register_script(
            'pagevico-settings',
            PageVICO_PLUGIN_URL . 'assets/js/settings.js',
            array('jquery', 'pagevico-bootstrap-bundle'),
            PageVICO_VERSION,
            true
        );
        // Register import script
        wp_register_script(
            'pagevico-import',
            PageVICO_PLUGIN_URL . 'assets/js/admin/import.js',
            array('jquery'),
            PageVICO_VERSION,
            true
        );
        // Enqueue scripts
        wp_enqueue_script( 'pagevico-bootstrap-bundle' );
        wp_enqueue_script( 'pagevico-settings' );
        // Only load import scripts if the import tab is active
        if ( isset( $_GET['tab'] ) && $_GET['tab'] === 'import' ) {
            wp_enqueue_script( 'pagevico-import' );
            wp_localize_script( 'pagevico-import', 'pagevicoImport', array(
                'nonce'          => wp_create_nonce( 'pagevico_import_nonce' ),
                'ajaxUrl'        => admin_url( 'admin-ajax.php' ),
                'importRunning'  => __( 'Import is running in the background. You can close this page.', 'page-visit-counter-analytics' ),
                'importComplete' => __( 'Import completed successfully!', 'page-visit-counter-analytics' ),
                'importError'    => __( 'Error during import. Please check error logs.', 'page-visit-counter-analytics' ),
            ) );
        }
        // Localize script
        wp_localize_script( 'pagevico-settings', 'pagevicoSettings', array(
            'ajax_url'           => admin_url( 'admin-ajax.php' ),
            'nonce'              => wp_create_nonce( 'PageVICO_reset_settings' ),
            'partition_nonce'    => wp_create_nonce( 'PageVICO_manage_partitions' ),
            'geo_db_url'         => rest_url( 'pagevico/v1/update-geo-db' ),
            'geo_db_nonce'       => wp_create_nonce( 'wp_rest' ),
            'confirm_reset'      => __( 'Are you sure you want to reset all settings to default values?', 'page-visit-counter-analytics' ),
            'confirm_partitions' => __( 'This will update the database partitions. Continue?', 'page-visit-counter-analytics' ),
        ) );
        // Add inline JavaScript for enhanced functionality
        $custom_js = "\n\t\t\tjQuery(document).ready(function(\$) {\n\t\t\t\t// Define custom chart colors\n\t\t\t\tif (window.Chart) {\n\t\t\t\t\t// Set default colors for all Chart.js instances\n\t\t\t\t\tChart.defaults.color = '#000000';\n\t\t\t\t\tChart.defaults.borderColor = '#E6E6E6';\n\t\t\t\t\t\n\t\t\t\t\t// Set default colors for datasets\n\t\t\t\t\tconst primaryColor = '#FF6B00';\n\t\t\t\t\tconst secondaryColor = '#FFB000';\n\t\t\t\t\t\n\t\t\t\t\t// Create an array of default colors for datasets\n\t\t\t\t\tChart.defaults.plugins.colors = {\n\t\t\t\t\t\tforceOverride: true,\n\t\t\t\t\t\tpalette: ['#FF6B00', '#FFB000', '#FF9A50', '#FFCC66', '#FF8533', '#E66100', '#CC5500']\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t});\n\t\t";
        wp_add_inline_script( 'pagevico-settings', $custom_js );
    }

    public static function renderPage() {
        $roles = wp_roles()->roles;
        $selected_roles = get_option( 'PageVICO_exclude_roles', array() );
        // Get the current tab
        $current_tab = ( isset( $_GET['tab'] ) ? sanitize_key( $_GET['tab'] ) : 'general' );
        if ( isset( $_POST['PageVICO_clear_all_data'] ) && check_admin_referer( 'PageVICO_clear_data', 'PageVICO_nonce' ) ) {
            global $wpdb;
            $wpdb->query( "TRUNCATE TABLE " . PageVICO_TABLE_SESSIONS );
            $wpdb->query( "TRUNCATE TABLE " . PageVICO_TABLE_PAGEVIEWS );
            add_action( 'admin_notices', function () {
                echo '<div class="notice notice-success is-dismissible"><p>All analytics data cleared successfully.</p></div>';
            } );
        }
        ?>
		<div class="pagevico-dashboard">
			<?php 
        include PageVICO_PLUGIN_DIR . 'templates/header.php';
        ?>

			<!-- Main Content -->
			<main class="pagevico-main pagevico-settings-page">
				<div class="pagevico-section">
					<div class="pagevico-section-header">
						<h2>
							<span class="dashicons dashicons-admin-settings"></span>
							<?php 
        esc_html_e( 'Settings', 'page-visit-counter-analytics' );
        ?>
						</h2>
					</div>
					<div class="pagevico-section-content pagevico-settings-content">
						<!-- Tabs -->
						<ul class="nav nav-tabs mb-4 pagevico-settings-tabs">
							<li class="nav-item">
								<a class="nav-link active" href="?page=pagevico-settings&tab=general">
									<?php 
        esc_html_e( 'General', 'page-visit-counter-analytics' );
        ?>
								</a>
							</li>
						</ul>
						
						<!-- General Settings Tab -->
						<form method="post" action="options.php" class="pagevico-settings-form">
							<?php 
        settings_fields( 'PageVICO_settings' );
        ?>
							<div class="pagevico-settings-group">
								<h4><?php 
        esc_html_e( 'Tracking Options', 'page-visit-counter-analytics' );
        ?></h4>
								<div class="pagevico-settings-grid">

								<!-- Enable Counter -->
								<div class="mb-2 pagevico-settings-field pagevico-settings-field--checkbox pagevico-settings-field--full">
									<input type="checkbox" id="PageVICO_enable_tracking" name="PageVICO_enable_tracking" value="1" <?php 
        checked( 1, get_option( 'PageVICO_enable_tracking', 1 ) );
        ?> />
									<label for="PageVICO_enable_tracking">
										<?php 
        esc_html_e( 'Enable visitor tracking', 'page-visit-counter-analytics' );
        ?>
									</label>
								</div>

								<!-- Show Short Numbers -->
								<div class="mb-3 pagevico-settings-field pagevico-settings-field--checkbox pagevico-settings-field--full">
									<input type="checkbox" id="PageVICO_short_number" name="PageVICO_short_number" value="1" <?php 
        checked( 1, get_option( 'PageVICO_short_number' ) );
        ?> />
									<label for="PageVICO_short_number">
										<?php 
        esc_html_e( 'Show numbers in short format (e.g. 1.2k)', 'page-visit-counter-analytics' );
        ?>
									</label>
								</div>

								<?php 
        ?>


								<!-- Track Post Types -->
								<div class="mb-3 pagevico-settings-field">
									<label for="PageVICO_post_types" class="form-label"><?php 
        esc_html_e( 'Track Post Types', 'page-visit-counter-analytics' );
        ?></label>
									<select name="PageVICO_post_types[]" id="PageVICO_post_types" multiple class="form-select" style="height: 120px;">
										<?php 
        foreach ( get_post_types( array(
            'public' => true,
        ), 'objects' ) as $type ) {
            ?>
											<option value="<?php 
            echo esc_attr( $type->name );
            ?>" <?php 
            selected( in_array( $type->name, (array) get_option( 'PageVICO_post_types', array('post', 'page') ) ) );
            ?>>
												<?php 
            echo esc_html( $type->label );
            ?>
											</option>
										<?php 
        }
        ?>
									</select>
								</div>

								<!-- Exclude Roles -->
								<div class="mb-3 pagevico-settings-field">
									<label for="PageVICO_exclude_roles" class="form-label"><?php 
        esc_html_e( 'Exclude User Roles from Tracking', 'page-visit-counter-analytics' );
        ?></label>
									<select name="PageVICO_exclude_roles[]" id="PageVICO_exclude_roles" multiple class="form-select" style="height: 120px;">
										<?php 
        foreach ( wp_roles()->roles as $key => $role ) {
            ?>
											<option value="<?php 
            echo esc_attr( $key );
            ?>" <?php 
            selected( in_array( $key, (array) get_option( 'PageVICO_exclude_roles', array() ) ) );
            ?>>
												<?php 
            echo esc_html( $role['name'] );
            ?>
											</option>
										<?php 
        }
        ?>
									</select>
								</div>

								<!-- Block Usernames -->
								<div class="mb-3 pagevico-settings-field">
									<label for="PageVICO_block_users" class="form-label"><?php 
        esc_html_e( 'Block Specific Users (by login name)', 'page-visit-counter-analytics' );
        ?></label>
									<select name="PageVICO_block_users[]" id="PageVICO_block_users" multiple class="form-select" style="height: 100px;">
										<?php 
        foreach ( get_users( array(
            'fields' => array('user_login'),
        ) ) as $user ) {
            ?>
											<option value="<?php 
            echo esc_attr( $user->user_login );
            ?>" <?php 
            selected( in_array( $user->user_login, (array) get_option( 'PageVICO_block_users', array() ) ) );
            ?>>
												<?php 
            echo esc_html( $user->user_login );
            ?>
											</option>
										<?php 
        }
        ?>
									</select>
								</div>

								<!-- Block Specific Posts/Pages -->
								<div class="mb-3 pagevico-settings-field pagevico-settings-field--full">
									<label for="PageVICO_block_posts" class="form-label"><?php 
        esc_html_e( 'Block Specific Pages/Posts from Counting', 'page-visit-counter-analytics' );
        ?></label>
									<select name="PageVICO_block_posts[]" id="PageVICO_block_posts" multiple class="form-select" style="height: 150px;">
										<?php 
        foreach ( get_posts( array(
            'post_type'   => 'any',
            'numberposts' => -1,
            'orderby'     => 'title',
        ) ) as $post ) {
            ?>
											<option value="<?php 
            echo esc_attr( $post->ID );
            ?>" <?php 
            selected( in_array( $post->ID, (array) get_option( 'PageVICO_block_posts', array() ) ) );
            ?>>
																							<?php 
            echo esc_html( ( $post->post_title ?: '(' . $post->post_type . ') ID: ' . $post->ID ) );
            ?>
											</option>
										<?php 
        }
        ?>
									</select>
								</div>

								<!-- Block IP Addresses -->
								<div class="mb-3 pagevico-settings-field pagevico-settings-field--full">
									<label for="PageVICO_block_ips" class="form-label"><?php 
        esc_html_e( 'Block IP Addresses', 'page-visit-counter-analytics' );
        ?></label>
									<textarea class="form-control" id="PageVICO_block_ips" name="PageVICO_block_ips" rows="4" placeholder="<?php 
        esc_attr_e( 'Enter IPs (one per line). Supports single IPs (e.g., 192.168.1.1), CIDR notation (e.g., 192.168.1.0/24), or ranges (e.g., 192.168.1.1-192.168.1.100)', 'page-visit-counter-analytics' );
        ?>"><?php 
        echo esc_textarea( get_option( 'PageVICO_block_ips', '' ) );
        ?></textarea>
									<div class="form-text text-muted">
										<?php 
        esc_html_e( 'Supports single IPs, CIDR notation (192.168.1.0/24), and IP ranges (192.168.1.1-192.168.1.100)', 'page-visit-counter-analytics' );
        ?>
									</div>
								</div>

								<!-- Analytics Data Retention -->
								<div class="mb-3 pagevico-settings-field pagevico-settings-field--compact">
									<label for="PageVICO_analytics_retention" class="form-label">
										<?php 
        esc_html_e( 'Analytics Data Retention (days)', 'page-visit-counter-analytics' );
        ?>
									</label>
									<input type="number" 
											id="PageVICO_analytics_retention" 
											name="PageVICO_analytics_retention" 
											class="form-control" 
											min="1" 
											max="365" 
											value="<?php 
        echo esc_attr( get_option( 'PageVICO_analytics_retention', 90 ) );
        ?>" />
									<small class="form-text text-muted">
										<?php 
        esc_html_e( 'Number of days to keep analytics data. Data older than this will be automatically deleted.', 'page-visit-counter-analytics' );
        ?>
									</small>
								</div>
								
								<!-- Session Timeout -->
								<div class="mb-3 pagevico-settings-field pagevico-settings-field--compact">
									<label for="session_timeout_minutes" class="form-label">
										<?php 
        esc_html_e( 'Session Timeout (minutes)', 'page-visit-counter-analytics' );
        ?>
									</label>
									<input type="number" 
											id="session_timeout_minutes" 
											name="session_timeout_minutes" 
											class="form-control" 
											min="5" 
											max="120" 
											value="<?php 
        echo esc_attr( get_option( 'session_timeout_minutes', 30 ) );
        ?>" />
									<small class="form-text text-muted">
										<?php 
        esc_html_e( 'Number of minutes of inactivity after which a user session is considered ended.', 'page-visit-counter-analytics' );
        ?>
									</small>
								</div>

								<?php 
        ?>
								</div>
							</div>

							

							<div class="pagevico-settings-actions">
								<button type="submit" class="btn btn-primary"><?php 
        esc_html_e( 'Save Changes', 'page-visit-counter-analytics' );
        ?></button>
							</div>
						</form>

					</div>
				</div>

				<div class="pagevico-section">
					<div class="pagevico-section-header">
						<h2>
							<span class="dashicons dashicons-location"></span>
							<?php 
        esc_html_e( 'Geolocation Database', 'page-visit-counter-analytics' );
        ?>
						</h2>
					</div>
					<div class="pagevico-section-content">
						<div class="card mb-3 p-0">
							<div class="card-header bg-primary text-white">
								<?php 
        esc_html_e( 'Geographic Database Management', 'page-visit-counter-analytics' );
        ?>
							</div>
							<div class="card-body">
								<h5 class="card-title"><?php 
        esc_html_e( 'Geo Database Status', 'page-visit-counter-analytics' );
        ?></h5>
								<?php 
        $geo_path = ( defined( 'PageVICO_GEO_DB_PATH' ) ? PageVICO_GEO_DB_PATH : '' );
        // translators: %s: Message for Geo Database not downloaded
        $last_modified = ( file_exists( $geo_path ) ? sprintf( esc_html__( 'Last updated: %s', 'page-visit-counter-analytics' ), date_i18n( get_option( 'date_format' ), filemtime( $geo_path ) ) ) : esc_html__( 'Not downloaded yet.', 'page-visit-counter-analytics' ) );
        ?>
								<p><strong><?php 
        esc_html_e( 'Last Updated:', 'page-visit-counter-analytics' );
        ?></strong> <span id="pagevico-geo-last-updated"><?php 
        echo esc_html( $last_modified );
        ?></span></p>
								<p class="text-muted"><?php 
        esc_html_e( 'The Geo database is automatically updated every 2 weeks.', 'page-visit-counter-analytics' );
        ?></p>
								<button type="button" id="pagevico-update-geo-db" class="btn btn-primary">
									<span class="dashicons dashicons-download"></span>
									<?php 
        esc_html_e( 'Update Geo Database Now', 'page-visit-counter-analytics' );
        ?>
								</button>
								<div id="pagevico-geo-update-message" class="mt-2" style="display: none;"></div>
							</div>
						</div>
					</div>
				</div>
				<div class="pagevico-section">
					<div class="pagevico-section-header">
						<h2>
							<span class="dashicons dashicons-admin-tools"></span>
							<?php 
        esc_html_e( 'Maintenance', 'page-visit-counter-analytics' );
        ?>
						</h2>
					</div>
					<div class="pagevico-section-content">
						<div class="row">
							<div class="col-md-6">
								<div class="card border-danger mb-3 p-0">
									<div class="card-header bg-danger text-white">
										<?php 
        esc_html_e( 'Danger Zone', 'page-visit-counter-analytics' );
        ?>
									</div>
									<div class="card-body">
										<h5 class="card-title"><?php 
        esc_html_e( 'Clear Analytics Data', 'page-visit-counter-analytics' );
        ?></h5>
										<p class="card-text"><?php 
        esc_html_e( 'This will permanently delete all visit records and statistics. This action cannot be undone.', 'page-visit-counter-analytics' );
        ?></p>
										<form method="post">
											<?php 
        wp_nonce_field( 'PageVICO_clear_data', 'PageVICO_nonce' );
        ?>
											<button type="submit" name="PageVICO_clear_all_data" class="btn btn-danger" onclick="return confirm('<?php 
        esc_attr_e( 'Are you sure? This will delete all visit records.', 'page-visit-counter-analytics' );
        ?>');">
												<?php 
        esc_html_e( 'Clear All Analytics Data', 'page-visit-counter-analytics' );
        ?>
											</button>
										</form>
									</div>
								</div>
							</div>
							
							<div class="col-md-6">
								<div class="card border-warning mb-3 p-0">
									<div class="card-header bg-warning text-dark">
										<?php 
        esc_html_e( 'Reset Settings', 'page-visit-counter-analytics' );
        ?>
									</div>
									<div class="card-body">
										<h5 class="card-title"><?php 
        esc_html_e( 'Reset to Default Settings', 'page-visit-counter-analytics' );
        ?></h5>
										<p class="card-text"><?php 
        esc_html_e( 'This will reset all settings to their default values. Your analytics data will not be affected.', 'page-visit-counter-analytics' );
        ?></p>
										<button type="button" id="pagevico-reset-settings" class="btn btn-warning">
											<?php 
        esc_html_e( 'Reset All Settings', 'page-visit-counter-analytics' );
        ?>
										</button>
										<div id="pagevico-reset-message" class="mt-2" style="display: none;"></div>
									</div>
								</div>
							</div>
						</div>

						<?php 
        ?>
					</div>
				</div>
			</main>

			<?php 
        include PageVICO_PLUGIN_DIR . 'templates/footer.php';
        ?>
		</div>
		<?php 
    }

}
