<?php
/*
Plugin Name: Asana Automator
Description: Run scheduled automations on Asana tasks such as cleanup, notifications, and custom actions.
Version: 1.0.1
Author: Paul Harvey
*/

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

if (!defined('AFB_AUTOMATOR_EMBEDDED')) {
    define('AFB_AUTOMATOR_EMBEDDED', true);
}

/* ---------------------------------------------------------------------------
   Constants
--------------------------------------------------------------------------- */
if (!defined('ASANA_AUTOMATOR_DIR')) {
    define('ASANA_AUTOMATOR_DIR', plugin_dir_path(__FILE__));
}

/* ---------------------------------------------------------------------------
   Always-loaded runtime requirements
--------------------------------------------------------------------------- */
require_once ASANA_AUTOMATOR_DIR . 'includes/compat.php';
require_once ASANA_AUTOMATOR_DIR . 'includes/cron-runtime.php';
require_once ASANA_AUTOMATOR_DIR . 'includes/automation-registry.php';
require_once ASANA_AUTOMATOR_DIR . 'includes/actions-delete-attachments.php';
require_once ASANA_AUTOMATOR_DIR . 'includes/dispatcher.php';
require_once ASANA_AUTOMATOR_DIR . 'includes/mapping-bootstrap.php';
require_once ASANA_AUTOMATOR_DIR . 'includes/webhook-handler.php';

/* ---------------------------------------------------------------------------
   Admin-only UI & settings
--------------------------------------------------------------------------- */
if (is_admin()) {
    require_once ASANA_AUTOMATOR_DIR . 'admin/settings-main.php';
    require_once ASANA_AUTOMATOR_DIR . 'admin/settings-rules.php';
    require_once ASANA_AUTOMATOR_DIR . 'admin/settings-mappings.php';
    require_once ASANA_AUTOMATOR_DIR . 'admin/webhook-admin.php';
    require_once ASANA_AUTOMATOR_DIR . 'admin/ajax-handlers.php';
    require_once ASANA_AUTOMATOR_DIR . 'admin/diagnostics.php';
}

/* ---------------------------------------------------------------------------
   CRON HOOK – Register + Schedule
--------------------------------------------------------------------------- */

add_action('init', function () {
    asana_automator_maybe_migrate_pat_accounts_to_afb_table();

    $legacy_hook = 'asana_automator_run';
    while ($ts = wp_next_scheduled($legacy_hook)) {
        wp_unschedule_event($ts, $legacy_hook);
    }

    if (!wp_next_scheduled(ASANA_AUTOMATOR_CRON_HOOK)) {
        wp_schedule_event(time() + 60, 'five_minutes', ASANA_AUTOMATOR_CRON_HOOK);
    }
});

/* ---------------------------------------------------------------------------
   Manual trigger endpoint  (needed for self-ping)
--------------------------------------------------------------------------- */

add_action('init', function () {
    if (isset($_GET['trigger_asana_cron']) && $_GET['trigger_asana_cron'] === '1') {
        do_action('asana_automator_cron_dispatch');
        exit; // silent success
    }
});

/* ---------------------------------------------------------------------------
   🚀 Self-ping loopback to ensure cron runs on quiet sites
--------------------------------------------------------------------------- */
add_action('init', function () {
    if (defined('DOING_CRON') && DOING_CRON) return; // don’t recurse during real cron

    $last = get_transient('asana_automator_last_ping');
    if (!$last || time() - $last > 300) { // every 5 mins
        set_transient('asana_automator_last_ping', time(), 300);

        file_put_contents(WP_CONTENT_DIR . '/cron-test.log',
            date('c') . " 🚀 Self-ping initiated\n", FILE_APPEND);

       $resp = wp_remote_get(home_url('/?trigger_asana_cron=1'), [
            'timeout'   => 3,
            'blocking'  => false,
            'sslverify' => false,
        ]);

        if (is_wp_error($resp)) {
            file_put_contents(WP_CONTENT_DIR . '/cron-test.log',
                date('c') . ' ❌ Self-ping failed: ' . $resp->get_error_message() . "\n", FILE_APPEND);
        }
    }
});