<?php

namespace OtomaticAi\Utils;

use Exception;
use OtomaticAi\Api\OtomaticAi\Client;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

class DataSync
{
    const TRANSIENT_KEY = 'otomatic_ai_data_sync_last_update';
    const CRON_HOOK = 'otomatic_ai_data_sync_cron_hook';
    const CRON_INTERVAL = 'five_minutes';
    const DATA_OPTION_NAME = 'otomatic_ai_data_sync';
    const SYNC_DATA_INTERVAL = 5 * MINUTE_IN_SECONDS;

    public static function init()
    {
        // Hook visiteurs
        add_action('init', [self::class, 'maybeUpdateData']);

        // Hook wp_cron
        add_action(self::CRON_HOOK, [self::class, 'maybeUpdateData']);

        // Ajouter l'intervalle custom
        add_filter('cron_schedules', [self::class, 'addCronSchedule']);
    }

    public static function maybeUpdateData()
    {
        if (false === get_transient(self::TRANSIENT_KEY)) {
            self::updateData();
        }
    }

    public static function updateData()
    {
        if (!Auth::check()) {
            return;
        }

        // get data
        try {
            $api = new Client;
            $data = $api->getSyncData();

            // save data
            update_option(self::DATA_OPTION_NAME, json_encode($data));

            // Met un transient pour éviter les appels trop fréquents
            set_transient(self::TRANSIENT_KEY, time(), self::SYNC_DATA_INTERVAL);
        } catch (Exception $e) {
        }
    }

    public static function getData($key = null, $default = null)
    {
        $data = get_option(self::DATA_OPTION_NAME);

        if (!$data) {
            return $default;
        }

        $data = json_decode($data, true);

        if ($key) {
            return Arr::get($data, $key, $default);
        }

        return $data;
    }

    public static function removeData()
    {
        delete_transient(self::TRANSIENT_KEY);
        delete_option(self::DATA_OPTION_NAME);
    }

    public static function addCronSchedule($schedules)
    {
        $schedules[self::CRON_INTERVAL] = [
            'interval' => self::SYNC_DATA_INTERVAL,
            'display'  => __('Every 5 Minutes')
        ];
        return $schedules;
    }

    public static function activate()
    {
        if (!wp_next_scheduled(self::CRON_HOOK)) {
            wp_schedule_event(time(), self::CRON_INTERVAL, self::CRON_HOOK);
        }
    }

    public static function deactivate()
    {
        wp_clear_scheduled_hook(self::CRON_HOOK);
    }
}
