<?php

namespace Blazemedia\OneSignal\Push;

/**
 * Auto Push notifications for WordPress posts
 */
class AutoPush
{
    /**
     * Initialize auto push functionality
     */
    public function __construct()
    {
        \add_action('transition_post_status', function($new_status, $old_status, $post) {

            if ($old_status !== 'publish' && $new_status === 'publish') {
                // Recupera i post type abilitati dalla settings page
                $enabled_types = \get_option('onesignal_enabled_post_types', '');
                $enabled_types = array_filter(array_map('trim', explode(',', $enabled_types)));
                if (empty($enabled_types)) {
                    $enabled_types = ['post'];
                }

                // Filtra per post type
                if (in_array($post->post_type, $enabled_types, true)) {
                    $this->sendPostNotification($post);
                }
            }
            
        }, 10, 3);
    }

    /**
     * Send notification for published post
     */
    public function sendPostNotification(\WP_Post $post)
    {
        // Check if auto push is enabled
        if (!\get_option('onesignal_auto_push', false)) {
            return;
        }

        // Only send for new posts (not updates)
        if (\wp_is_post_revision($post->ID) || \wp_is_post_autosave($post->ID)) {
            return;
        }

        try {
            $pushManager = new PushManager();
            $pushManager->sendPostNotification($post);
            
            // Log success
            error_log("OneSignal: Auto push sent for post {$post->ID}");
        } catch (\Exception $e) {
            // Log error
            error_log("OneSignal: Auto push failed for post {$post->ID}: " . $e->getMessage());
        }
    }
} 