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

function get_fleximp_validation_status()
{
    return get_option('fleximp_validation_status', 'false');
}

function set_fleximp_validation_status($is_valid)
{
    update_option('fleximp_validation_status', $is_valid);
}

function get_fleximp_suspension_status()
{
    return get_option('fleximp_suspension_status', 'false');
}

function set_fleximp_suspension_status($is_suspended)
{
    update_option('fleximp_suspension_status', $is_suspended);
}

function set_fleximp_key($license_key)
{
    update_option('fleximp_is_premium', $license_key);
}

function remove_fleximp_key()
{
    delete_option('fleximp_is_premium');
}

function get_fleximp_key()
{
    return get_option('fleximp_is_premium');
}

// bundle
function get_fleximp_bundle_status()
{
    return get_option('fleximp_is_bundle', 'false');
}

function set_fleximp_bundle_status($is_bundle)
{
    update_option('fleximp_is_bundle', $is_bundle);
}

function remove_fleximp_bundle_status()
{
    delete_option('fleximp_is_bundle');
}


function fleximp_license_admin_scripts($hook)
{

    if ($hook == 'flex-importer_page_fleximp-license-key') {
        wp_enqueue_style('fleximp-license-css', FLEXIMP_PLUGIN_DIR_FILE . 'assets/css/fleximp-license-style.css', [], FLEXIMP_VER);
    }

    wp_enqueue_script('fleximp-notify-js', FLEXIMP_PLUGIN_DIR_FILE . '/assets/js/jquery.notify.min.js', [], FLEXIMP_VER);
    wp_register_script(
        'fleximp-license-admin-script',
        FLEXIMP_PLUGIN_DIR_FILE . 'assets/js/license_script.js',
        [],
        FLEXIMP_VER
    );

    $localize_script_arr = array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'wpnonce' => wp_create_nonce('admin_script_nonce'),
        'redirect_url' => admin_url('admin.php?page=fleximp-template-importer'),
    );

    wp_localize_script('fleximp-license-admin-script', 'localize_script_arr', $localize_script_arr);
    wp_enqueue_script('fleximp-license-admin-script');
}


add_action('admin_enqueue_scripts', 'fleximp_license_admin_scripts');

function license_activate_fleximp()
{

    if (empty($_POST['fleximp_is_premium'])) {
        wp_send_json(['status' => false, 'msg' => 'License key is required.']);
    }

    $license_key = $_POST['fleximp_is_premium'];
    $endpoint = FLEXIMP_LICENSE_URL . 'verifyTheme';

    $body = [
        'theme_license_key' => $license_key,
        'site_url' => site_url(),
        'plugin_text_domain' => 'flex-import',
    ];
    $body = wp_json_encode($body);

    $options = [
        'body' => $body,
        'headers' => ['Content-Type' => 'application/json'],
    ];

    $response = wp_remote_post($endpoint, $options);

    if (is_wp_error($response)) {
        remove_fleximp_key();
        set_fleximp_validation_status('false');
        wp_send_json(['status' => false, 'msg' => 'Something Went Wrong!']);
    } else {
        $response_body = json_decode(wp_remote_retrieve_body($response));

        if ($response_body->is_suspended == 1) {
            set_fleximp_suspension_status('true');
        } else {
            set_fleximp_suspension_status('false');
        }

        if ($response_body->status === false) {
            remove_fleximp_key();
            set_fleximp_validation_status('false');
            wp_send_json(['status' => false, 'msg' => $response_body->msg]);
        } else {

            // Store bundle status (default false if not provided)
            if (isset($response_body->is_bundle) && $response_body->is_bundle == true) {
                set_fleximp_bundle_status('true');
            } else {
                set_fleximp_bundle_status('false');
            }

            set_fleximp_validation_status('true');
            set_fleximp_key($license_key);

            wp_send_json([
                'status' => true,
                'msg' => 'Plugin Activated Successfully!',
                'is_bundle' => isset($response_body->is_bundle) ? $response_body->is_bundle : false
            ]);
        }

    }
}

add_action('wp_ajax_license_activate_fleximp', 'license_activate_fleximp');


function fleximp_invalidate_license()
{
    remove_fleximp_key();
    remove_fleximp_bundle_status();
    set_fleximp_validation_status('false');
}

function license_deactivate_fleximp()
{
    $license_key = $_POST['fleximp_license_key'];

    if ($license_key != '') {
        $endpoint = FLEXIMP_LICENSE_URL . 'deactivateDomain';
        $body = [
            'theme_license_key' => $license_key,
            'site_url' => site_url(),
        ];
        $body = wp_json_encode($body);

        $options = [
            'body' => $body,
            'headers' => ['Content-Type' => 'application/json'],
        ];

        $response = wp_remote_post($endpoint, $options);

        if (is_wp_error($response)) {
            wp_send_json(['status' => false, 'msg' => 'Something Went Wrong!']);
        } else {
            $response_body = json_decode(wp_remote_retrieve_body($response));

            if ($response_body->status === false) {
                wp_send_json(['status' => false, 'msg' => $response_body->msg]);
            } else {
                fleximp_invalidate_license();
                wp_send_json(['status' => true, 'msg' => $response_body->msg]);
            }
        }
    }
}
add_action('wp_ajax_license_deactivate_fleximp', 'license_deactivate_fleximp');

function fleximp_license_expiry_notice()
{

    $license_key = get_fleximp_key();
    $endpoint = FLEXIMP_LICENSE_URL . 'status';

    $body = [
        'theme_license_key' => $license_key,
        'site_url' => site_url(),
        'plugin_text_domain' => 'flex-import',
    ];
    $body = wp_json_encode($body);

    if ($license_key != "") {
        $response = wp_remote_post($endpoint, [
            'body' => $body,
            'headers' => ['Content-Type' => 'application/json'],
        ]);

        if (!is_wp_error($response)) {
            $response_body = json_decode(wp_remote_retrieve_body($response));

            if (isset($response_body->status) && $response_body->status === false) {
                fleximp_invalidate_license();
                echo '<div class="notice notice-error"><p>License key is expired!</p></div>';
            }

            if (isset($response_body->is_suspended) && $response_body->is_suspended == 1) {
                fleximp_invalidate_license();
                set_fleximp_suspension_status('false');
                echo '<div class="notice notice-error"><p>License key is suspended!</p></div>';
            }
        }
    }
}
add_action('admin_notices', 'fleximp_license_expiry_notice');