<?php

/**
 * Setup all the admin stuff.
 */
function zbr_admin_init()
{
}

add_action('wp_dashboard_setup', 'zbr_add_dashboard_widgets');
add_action('admin_init', 'zbr_admin_init');

function zbr_add_dashboard_widgets()
{
    $title = 'Ziber API Plugin';
    wp_add_dashboard_widget('dashboard_zbr_widget', $title, 'zbr_dashboard_widget_output');
}

/**
 * Output the contents of the dashboard widget
 */
function zbr_dashboard_widget_output($post, $callback_args)
{
?>

    <div x-data="widget">
        <a class="button" @click.prevent="activate()" :class="active ? 'disabled':''">
            <span class="spinner" :class="active ? 'is-active':''"></span>
            <?php _e('Start import', 'zbr-api'); ?>
        </a>
    </div>
<?php
}

/**
 * Enqueue the scripts
 */
function zbr_dashboard_widget_enqueue($hook)
{
    $asset_file = include plugin_dir_path(ZBR_PLUGIN) . 'build/index.asset.php';

    wp_enqueue_script(
        'zbr-dashboard-widget',
        plugins_url('build/index.js', ZBR_PLUGIN),
        $asset_file['dependencies'],
        $asset_file['version']
    );

    wp_localize_script('zbr-dashboard-widget', 'zbr', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('zbr-nonce'),
    ));
}

function zbr_dashboard_run_import()
{
    // get the id from the POST
    $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);

    // if no id is set, error out
    if (!$id) {
        wp_send_json_error('No id set');
    }

    // run the import
    Zbr_Plugin_Core::instance()->load_api_data($id);
}

function zbr_dashboard_create_import()
{
    // create a new import
    $id = Zbr_Plugin_Core::instance()->create_new_import();
    
    wp_send_json($id);
}

function zbr_get_latest_run()
{
    global $wpdb;
    $tablePrefix = $wpdb->prefix . 'zbr_';
    $logTable = $tablePrefix . 'loading_logs';

    $results = $wpdb->get_results("SELECT * FROM $logTable ORDER BY createdAt DESC LIMIT 1 ");
    wp_send_json($results);
}

add_action('wp_ajax_zbr_run_import', 'zbr_dashboard_run_import');
add_action('wp_ajax_zbr_create_import', 'zbr_dashboard_create_import');
add_action('wp_ajax_zbr_get_latest_run', 'zbr_get_latest_run');
add_action('admin_enqueue_scripts', 'zbr_dashboard_widget_enqueue');
