<?php
namespace ONLINE_ADAv4;

/**
 * Plugin Name:       Accessibility Suite by Ability, Inc
 * Plugin URI:        https://adaplugin.com
 * Description:       The most powerful and comprehensive Accessibility Suite. Achieve and maintain ADA/WCAG compliance faster than ever before. Audit, identify, get instruction, and fix.
 * Version:           4.20
 * Author:            Ability, Inc
 * Author URI:        https://adaplugin.com
 * License:           GPL-2.0+
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.txt
 * Text Domain:       accessibility-suite
 * Domain Path:       /languages
 */

if (!defined('ABSPATH')) {
    exit;
}
if (!defined('ACCESSSUITEMODE')) {
    //define('ACCESSSUITEMODE','dev');
    define('ACCESSSUITEMODE','production');
}

require_once plugin_dir_path(__FILE__) . 'includes/classes/Plugin.php';
global $info;
$info = [
    "name" => "online-accessibility",
    "name_pretty" => "Accessibility Suite",
    "version" => "4.20",
    "file" => __FILE__,
    "path" => plugin_dir_path(__FILE__),
    "url"  => rtrim(plugin_dir_url(__FILE__), "/"),
    "ext-quickref" => "https://www.w3.org/WAI/WCAG21/quickref/",
    "int-quickref" => admin_url("edit.php?post_type=wcag_scan&page=wcag-guidelines"),
    "site_url" => site_url(),
    "home_url" => home_url(),
    "chunkSize" => get_option("_oadaas_scan_schunk_size", 700000),
    "db_row_limit" => get_option("_oadaas_db_row_limit", 25),
    "license_url" => "https://accounts.onlineada.com",
    "license_key" => "accessibility-suite-pro-license",
    "license_status_key" => "accessibility-suite-pro-license-status",
    "license" => trim(get_option('accessibility-suite-pro-license')),
    'item_name' => 'ADA Plugin',
    "routes" => [
        "check_license" => [
            "slug" => "/licensing/plugin/check_license",
            "method" => "POST"
        ],
        "activate_license" => [
            "slug" => "/licensing/plugin/activate_license",
            "method" => "POST"
        ],
        "product_info" => [
            "slug" => "/licensing/plugin/product_info",
            "method" => "POST"
        ]
    ]
];

register_activation_hook($info['file'], __NAMESPACE__.'\\activate');
register_deactivation_hook($info['file'], __NAMESPACE__.'\\deactivate');

function activate($path)
{
    global $info;
    add_option('oadaas-show-activation-message', 1, '', 'yes');

    Helper::create_table();
    Helper::create_false_positives_table();

    if (!file_exists(wp_upload_dir()["basedir"] . "/oadaas")) {
        wp_mkdir_p(wp_upload_dir()["basedir"] . "/oadaas", 0777, true);
    }
    
    flush_rewrite_rules();

    if(is_plugin_active('accessibility-suite-pro/index.php')){
        deactivate_plugins('accessibility-suite-pro/index.php', true);
    }
    $pro_path = WP_PLUGIN_DIR . "/accessibility-suite-pro";
   
    if(is_dir($pro_path)){
        rrmdir($pro_path);
    }

    if(Services\License::getInstance()->check_license($info)  === "valid"){
        create_sitemap_initial_pro();
    }else{
        create_sitemap_initial_free();
    }
}

function rrmdir($dir) {
    require_once ( ABSPATH . '/wp-admin/includes/class-wp-filesystem-base.php' );
    require_once ( ABSPATH . '/wp-admin/includes/class-wp-filesystem-direct.php' );
    $fileSystemDirect = new \WP_Filesystem_Direct(false);
    if (is_dir($dir)) {
        $objects = scandir($dir); 
        foreach ($objects as $object) { 
            if ($object != "." && $object != "..") { 
                if (is_dir($dir."/".$object))
                    $fileSystemDirect->rmdir($dir, true);
                else
                    wp_delete_file($dir."/".$object);
            }
        }
        rmdir($dir); // phpcs:ignore
    }
}

function create_sitemap_initial_free()
{
    //Logic for scanning database for all pages here, non-pro version since we haven't gotten to license checking yet
    if(!get_option("_oadaas_sitemap")){
        $sitemap = ["non_query_links" => [sanitize_text_field(untrailingslashit(home_url()))]];

        $result = update_option("_oadaas_sitemap", $sitemap);
        if (!$result) {
            error_log($info["name_pretty"] . ': failed to create sitemap in database');
        }
    }
}

function create_sitemap_initial_pro()
{
    //Logic for scanning database for all pages here
    $sitemap = [];
    $pages = get_pages();
    $posts = get_posts();
    $merged = array_merge($pages, $posts);
    $pattern = "/\.\w+$/";
    foreach ($merged as $object) {
        $page_link = untrailingslashit(sanitize_text_field(get_page_link($object->ID)));
        preg_match($pattern, $page_link, $match);
        if (!empty($match) && $match[0] !== ".php") {
            continue;
        }

        if (strpos($page_link, "?") !== false) {
            $sitemap["query_links"][] = $page_link;
            continue;
        }
        $sitemap["non_query_links"][] = $page_link;
    }

    $result = update_option("_oadaas_sitemap", $sitemap);
}

function deactivate()
{
    global $info;
    $result = delete_option("_oadaas_sitemap");
    if (!$result) {
        error_log($info["name_pretty"] .": Error deleting sitemap from database");
    }

    delete_option($info["name"] . "-license-status");
    flush_rewrite_rules();
}
        
Plugin::instance($info);

add_action("admin_init", function(){
    if(is_plugin_active('accessibility-suite-pro/index.php')){
        deactivate_plugins('accessibility-suite-pro/index.php', true);
    }
    $pro_path = WP_PLUGIN_DIR . "/accessibility-suite-pro";
   
    if(is_dir($pro_path)){
        rrmdir($pro_path);
    }
});
