<?php
/**
 * Plugin Name: OneSignal by BlazeMedia
 * Plugin URI: https://github.com/blazemedia/onesignal
 * Description: WordPress plugin for OneSignal integration
 * Version: 1.0.0
 * Author: BlazeMedia
 * Author URI: https://blazemedia.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: onesignal
 * Domain Path: /languages
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Define plugin constants
if (!defined('ONESIGNAL_PLUGIN_VERSION')) define('ONESIGNAL_PLUGIN_VERSION', '1.0.0');
if (!defined('ONESIGNAL_PLUGIN_FILE')) define('ONESIGNAL_PLUGIN_FILE', __FILE__);
if (!defined('ONESIGNAL_PLUGIN_DIR')) define('ONESIGNAL_PLUGIN_DIR', plugin_dir_path(__FILE__));
if (!defined('ONESIGNAL_PLUGIN_URL')) define('ONESIGNAL_PLUGIN_URL', plugin_dir_url(__FILE__));

// Autoloader
require_once ONESIGNAL_PLUGIN_DIR . 'vendor/autoload.php';

// Initialize the plugin
add_action('plugins_loaded', function() {
    try {
        // Initialize the main plugin class
        $plugin = new \Blazemedia\OneSignal\Plugin;

    } catch (Exception $e) {
        error_log('OneSignal Plugin Error: ' . $e->getMessage());
    }
});

// Activation hook
register_activation_hook(__FILE__, function() {
    
    // Ensure settings are registered
    if (class_exists('\Blazemedia\OneSignal\Admin\Admin')) {
        $admin = new \Blazemedia\OneSignal\Admin\Admin();
        $admin->initSettings();
    }

    serviceWorkerCopy();

});

// Deactivation hook
register_deactivation_hook(__FILE__, function() {
    // Deactivation tasks
}); 




function serviceWorkerCopy() {
    
    // Percorso sorgente: dove sono i file nel tuo plugin
    $source_dir = ONESIGNAL_PLUGIN_DIR;

    // Percorso di destinazione: root pubblica (es. /web/)
    $destination_dir = str_replace('wp/', '', ABSPATH );

    $files = [ 
        'OneSignalSDKWorker.js', 
        // 'OneSignalSDK.sw.js' 
    ] ;
    
    foreach ($files as $filename) {
        
        $destination = $destination_dir . $filename;

        $content = @file_get_contents( ONESIGNAL_PLUGIN_DIR . $filename );
        
        if ($content === false) {
            error_log("Errore il $filename è vuoto");            
            continue;
        }

        if (@file_put_contents($destination, $content) === false) {
            error_log("Errore nel salvare $filename in $destination");
            continue;
        }
        
        error_log("✅ $filename scaricato e copiato correttamente.");
    }
}