<?php
/**
 * Plugin Name: Admin Login Guard & Branding
 * Description: Change WordPress admin login URL and admin login logo with settings.
 * Version: 2.2.1
 * Author: Code and core
 * Author URI: https://codeandcore.com
 * Text Domain: admin-login-guard-branding
 * Requires at least: 5.0
 * Requires PHP: 7.4
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

if (!defined('ABSPATH')) {
    exit;
}

// Plugin constants for path and URL
define('admilogu_PATH', plugin_dir_path(__FILE__));
define('admilogu_URL', plugin_dir_url(__FILE__));

// Default Images and Media
define('admilogu_DEFAULT_LOGO', admilogu_URL . 'assets/images/wordpress-logo.svg');
define('admilogu_DEFAULT_BG', admilogu_URL . 'assets/images/adminlgb_wall.png');
define('admilogu_DEFAULT_VIDEO', admilogu_URL . 'assets/images/admin-video.mp4');

/**
 * Include helper functions
 */
require_once admilogu_PATH . 'includes/admilogu_utils.php';

/**
 * Include database functions
 */
require_once admilogu_PATH . 'includes/admilogu_database.php';

/**
 * Include login rewrites
 */
require_once admilogu_PATH . 'includes/admilogu_login_rewrites.php';

/**
 * Include security functions
 */
require_once admilogu_PATH . 'includes/admilogu_security.php';

/**
 * Include styling
 */
require_once admilogu_PATH . 'includes/admilogu_styling.php';

/**
 * Include 2FA
 */
require_once admilogu_PATH . 'includes/admilogu_2fa.php';

/**
 * Include admin dashboard
 */
if (is_admin()) {
    require_once admilogu_PATH . 'includes/admilogu_admin.php';
    require_once admilogu_PATH . 'includes/admilogu_telemetry.php';
    require_once admilogu_PATH . 'includes/admilogu_deactivation.php';
}

/**
 * Activate plugin: create DB table, flush rewrites, set transients.
 * Supports multisite network activation.
 *
 * @param bool $network_wide Whether the plugin is activated network-wide.
 */
function admilogu_activate($network_wide)
{
    if (is_multisite() && $network_wide) {
        global $wpdb;
        $blog_ids = $wpdb->get_col("SELECT blog_id FROM $wpdb->blogs"); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        foreach ($blog_ids as $blog_id) {
            switch_to_blog($blog_id);
            flush_rewrite_rules();
            admilogu_create_table();
            admilogu_set_defaults();
            restore_current_blog();
        }
    } else {
        flush_rewrite_rules();
        admilogu_create_table();
        admilogu_set_defaults();
    }

    // Migrate data from old adminlgb_ options if they exist
    admilogu_migrate_options();

    // Set transient for redirect
    set_transient('admilogu_activation_redirect', true, 30);
    set_transient('admilogu_show_telemetry_popup', true, 30);

    // Initial telemetry activation
    if (function_exists('admilogu_telemetry_activation')) {
        admilogu_telemetry_activation();
    }
}

/**
 * Save default option values to the database on first activation.
 *
 * Uses add_option() which is a no-op when the key already exists,
 * so existing settings are never overwritten.
 */
function admilogu_set_defaults()
{
    // General
    add_option('admilogu_enable_custom_login', 1);
    add_option('admilogu_login_slug', 'admin-login-guard-branding');
    add_option('admilogu_hide_backtoblog', 0);
    add_option('admilogu_fail_redirect_page', 0);
    add_option('admilogu_block_shortcuts', 1);

    // Logo
    add_option('admilogu_logo_url', '');
    add_option('admilogu_logo_width', '100%');
    add_option('admilogu_logo_height', '80px');
    add_option('admilogu_logo_title', '');
    add_option('admilogu_logo_link', 'https://wordpress.org/');
    add_option('admilogu_logo_target_blank', 1);
    add_option('admilogu_logo_bg_color', '');

    // Background
    add_option('admilogu_bg_type', 'image');
    add_option('admilogu_bg_image', '');
    add_option('admilogu_bg_video', '');
    add_option('admilogu_bg_video_mute', 1);
    add_option('admilogu_bg_color', '#f0f0f1');

    // Colours
    add_option('admilogu_loginform_bg_color', '#ffffff');
    add_option('admilogu_loginform_border_color', '#c3c4c7');
    add_option('admilogu_loginform_label_color', '#3c434a');
    add_option('admilogu_lostpwd_color', '#2271b1');
    add_option('admilogu_lostpwd_hover_color', '#135e96');
    add_option('admilogu_backtoblog_color', '#2271b1');
    add_option('admilogu_backtoblog_hover_color', '#135e96');
    add_option('admilogu_btn_bg_color', '#2271b1');
    add_option('admilogu_btn_text_color', '#ffffff');
    add_option('admilogu_btn_bg_hover_color', '#135e96');
    add_option('admilogu_btn_text_hover_color', '#ffffff');

    add_option('admilogu_enable_2fa', 0);

    add_option('admilogu_custom_css', '');
    add_option('admilogu_custom_js', '');
    add_option('admilogu_custom_font', '');
    add_option('admilogu_custom_footer', '');

    // Security
    add_option('admilogu_max_attempts', 3);
    add_option('admilogu_lockout_duration', 30);
    add_option('admilogu_ip_whitelist', '');
    add_option('admilogu_ip_blacklist', '');
    add_option('admilogu_notify_admin_lockout', 0);
    add_option('admilogu_notify_user_new_ip', 0);
}
register_activation_hook(__FILE__, 'admilogu_activate');

/**
 * Ensure the DB table exists and options are migrated on every plugin load.
 *
 * admilogu_create_table() uses dbDelta which is safe to call repeatedly — it
 * only creates or alters, never drops. This handles already-active installs
 * that never went through the activation hook after the prefix rename.
 * admilogu_migrate_options() checks for the old adminlgb_ option keys and
 * copies them once; subsequent calls are effectively no-ops.
 */
function admilogu_plugins_loaded()
{
    admilogu_create_table();
    admilogu_set_defaults();
    admilogu_migrate_options();
}
add_action('plugins_loaded', 'admilogu_plugins_loaded');

/**
 * Migrate options from old adminlgb_ prefix to admilogu_ prefix.
 *
 * Copies existing option values to the new keys and deletes the old ones,
 * preserving settings for sites that already had the plugin installed.
 */
function admilogu_migrate_options()
{
    $option_map = array(
        'adminlgb_login_slug' => 'admilogu_login_slug',
        'adminlgb_logo_url' => 'admilogu_logo_url',
        'adminlgb_logo_width' => 'admilogu_logo_width',
        'adminlgb_logo_height' => 'admilogu_logo_height',
        'adminlgb_logo_title' => 'admilogu_logo_title',
        'adminlgb_logo_link' => 'admilogu_logo_link',
        'adminlgb_logo_target_blank' => 'admilogu_logo_target_blank',
        'adminlgb_logo_bg_color' => 'admilogu_logo_bg_color',
        'adminlgb_bg_type' => 'admilogu_bg_type',
        'adminlgb_bg_image' => 'admilogu_bg_image',
        'adminlgb_bg_video' => 'admilogu_bg_video',
        'adminlgb_bg_video_mute' => 'admilogu_bg_video_mute',
        'adminlgb_bg_color' => 'admilogu_bg_color',
        'adminlgb_lostpwd_color' => 'admilogu_lostpwd_color',
        'adminlgb_backtoblog_color' => 'admilogu_backtoblog_color',
        'adminlgb_lostpwd_hover_color' => 'admilogu_lostpwd_hover_color',
        'adminlgb_backtoblog_hover_color' => 'admilogu_backtoblog_hover_color',
        'adminlgb_hide_backtoblog' => 'admilogu_hide_backtoblog',
        'adminlgb_loginform_bg_color' => 'admilogu_loginform_bg_color',
        'adminlgb_loginform_border_color' => 'admilogu_loginform_border_color',
        'adminlgb_loginform_label_color' => 'admilogu_loginform_label_color',
        'adminlgb_btn_bg_color' => 'admilogu_btn_bg_color',
        'adminlgb_btn_text_color' => 'admilogu_btn_text_color',
        'adminlgb_btn_bg_hover_color' => 'admilogu_btn_bg_hover_color',
        'adminlgb_btn_text_hover_color' => 'admilogu_btn_text_hover_color',
        'adminlgb_max_attempts' => 'admilogu_max_attempts',
        'adminlgb_lockout_duration' => 'admilogu_lockout_duration',
        'adminlgb_fail_redirect_page' => 'admilogu_fail_redirect_page',
        'adminlgb_tracking_optin' => 'admilogu_tracking_optin',
        'adminlgb_plugin_version' => 'admilogu_plugin_version',
    );

    foreach ($option_map as $old_key => $new_key) {
        $old_value = get_option($old_key);
        if ($old_value !== false && get_option($new_key) === false) {
            update_option($new_key, $old_value);
            delete_option($old_key);
        }
    }

    // Optionally rename the DB table if old one exists
    global $wpdb;
    $old_table = $wpdb->prefix . 'adminlgb_login_history';
    $new_table = $wpdb->prefix . 'admilogu_login_history';

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $old_exists = $wpdb->get_var("SHOW TABLES LIKE '$old_table'");
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    $new_exists = $wpdb->get_var("SHOW TABLES LIKE '$new_table'");

    if ($old_exists && !$new_exists) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $wpdb->query("RENAME TABLE `$old_table` TO `$new_table`");
    }
}

/**
 * Handle new blog creation in multisite
 *
 * @param int $blog_id The ID of the newly created blog.
 */
function admilogu_new_blog($blog_id)
{
    if (!function_exists('is_plugin_active_for_network')) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }
    if (is_plugin_active_for_network(plugin_basename(__FILE__))) {
        switch_to_blog($blog_id);
        admilogu_create_table();
        flush_rewrite_rules();
        restore_current_blog();
    }
}
add_action('wpmu_new_blog', 'admilogu_new_blog');

/**
 * Deactivation Hook
 */
function admilogu_deactivate()
{
    flush_rewrite_rules();

    // Telemetry deactivation
    if (function_exists('admilogu_telemetry_deactivation')) {
        admilogu_telemetry_deactivation();
    }
}
register_deactivation_hook(__FILE__, 'admilogu_deactivate');


/**
 * Add settings link to plugin action links
 *
 * @param array $links Array of existing action links.
 * @return array Modified array of action links with the settings link added.
 */
function admilogu_settings_link($links)
{
    $settings_link = '<a href="admin.php?page=admilogu-settings#general">' . __('Settings', 'admin-login-guard-branding') . '</a>';
    array_unshift($links, $settings_link);
    return $links;
}
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'admilogu_settings_link');
