<?php
/**
 * Plugin Name: Push notification by Pushmarket.io
 * Description: To send web push notification hussle free and engage with your audience. send marketing notifications and increase traffic and engagement.
 * Version: 0.1.3
 * Author: Aditya panther /presswink technology
 * Author URI: https://presswink.com
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

define( 'PMIO_PROJECT_ID_OPTION', 'pmio_project_id' );
define( 'PMIO_SECRET_OPTION', 'pmio_secret' );

/**
 * Add the Pushmarket.io settings page to the WordPress admin menu.
 */
function pmio_add_admin_menu() {
    add_options_page(
        'Pushmarket.io Settings',
        'Pushmarket.io',
        'manage_options',
        'pmio-settings',
        'pmio_settings_page_callback'
    );
}
add_action( 'admin_menu', 'pmio_add_admin_menu' );

/**
 * Register the settings for Pushmarket.io.
 */
function pmio_settings_init() {
    register_setting(
        'pmio_options_group',
        PMIO_PROJECT_ID_OPTION,
        array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => ''
        )
    );

    register_setting(
        'pmio_options_group',
        PMIO_SECRET_OPTION,
        array(
            'type'              => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default'           => ''
        )
    );

    add_settings_section(
        'pmio_main_section',
        'Pushmarket.io API Credentials',
        'pmio_section_callback',
        'pmio-settings'
    );

    add_settings_field(
        'pmio_project_id_field',
        'Project ID',
        'pmio_project_id_callback',
        'pmio-settings',
        'pmio_main_section'
    );

    add_settings_field(
        'pmio_secret_field',
        'Project Secret',
        'pmio_secret_callback',
        'pmio-settings',
        'pmio_main_section'
    );
}
add_action( 'admin_init', 'pmio_settings_init' );

/**
 * Callback function for the settings section description.
 */
function pmio_section_callback() {
    echo '<p>Enter your Pushmarket.io Project ID and Secret below.</p>';
}

/**
 * Callback function to render the Project ID input field.
 */
function pmio_project_id_callback() {
    $project_id = get_option( PMIO_PROJECT_ID_OPTION, '' );
    echo '<input type="text" id="' . PMIO_PROJECT_ID_OPTION . '" name="' . PMIO_PROJECT_ID_OPTION . '" value="' . esc_attr( $project_id ) . '" class="regular-text" />';
    echo '<p class="description">Your unique Project ID from Pushmarket.io.</p>';
}

/**
 * Callback function to render the Project Secret input field.
 */
function pmio_secret_callback() {
    echo '<input type="password" id="pmio_secret" name="' . PMIO_SECRET_OPTION . '" value="" class="regular-text" />';
    echo '<p class="description">Enter your Pushmarket.io Project Secret. For security, it will not be displayed after saving.</p>';
    echo '<p class="description"><em>Note: This field will appear empty even if a secret is saved. Enter it again to update.</em></p>';
}

/**
 * Render the Pushmarket.io settings page.
 */
function pmio_settings_page_callback() {
    ?>
    <div class="wrap">
        <h1>Pushmarket.io Settings</h1>
        <form method="post" action="options.php">
            <?php
            settings_fields( 'pmio_options_group' );
            do_settings_sections( 'pmio-settings' );
            submit_button();
            ?>
        </form>
    </div>
    <?php
}

/**
 * Sends a cURL request to Pushmarket.io when a post is published.
 */
function pmio_send_post_data_on_publish( $post_id, $post ) {
    if ( 'post' !== $post->post_type || 'publish' !== $post->post_status || wp_is_post_revision( $post_id ) || wp_is_post_autosave( $post_id ) ) {
        return;
    }

    $project_id = get_option( PMIO_PROJECT_ID_OPTION, '' );
    $project_secret = get_option( PMIO_SECRET_OPTION, '' );

    if ( empty( $project_id ) || empty( $project_secret ) ) {
        error_log( 'Pushmarket.io Plugin Error: Project ID or Secret not configured. Post ID: ' . $post_id );
        return;
    }

    $api_endpoint = 'http://api.pushmarket.io/send-notification';

    $post_title = $post->post_title;
    $post_description = wp_trim_words( $post->post_content, 50, '...' );

    $lang_code = substr( get_bloginfo( 'language' ), 0, 2 );
    $lang = ( 'en' === $lang_code ) ? 'eng' : $lang_code;

    $categories = get_the_category( $post_id );
    $topic = ! empty( $categories ) ? $categories[0]->name : null;

    $icon_url = has_post_thumbnail( $post_id ) ? get_the_post_thumbnail_url( $post_id, 'thumbnail' ) : null;

    $p_data = array(
        'title'  => $post_title,
        'lang'   => $lang,
        'body'   => $post_description,
        'topic'  => $topic,
        'icon'   => $icon_url,
        'status' => 'sent',
    );

    $payload_data = array(
        'type' => "sent",
        'data' => $p_data,
    );

    $json_data = json_encode( $payload_data );

    $response = wp_remote_post( $api_endpoint, array(
        'method'      => 'POST',
        'timeout'     => 15,
        'headers'     => array(
            'Content-Type'   => 'application/json',
            'project-id'     => $project_id,
            'project-secret' => $project_secret,
            'Access-Control-Allow-Origin' => '*'
        ),
        'body'        => $json_data,
        'data_format' => 'body',
    ) );

    if ( is_wp_error( $response ) ) {
        error_log( 'Pushmarket.io Plugin WP_HTTP_API Error: ' . $response->get_error_message() . ' for Post ID: ' . $post_id );
    } else {
        $http_code = wp_remote_retrieve_response_code( $response );
        $body = wp_remote_retrieve_body( $response );

        error_log( 'Pushmarket.io Plugin Response (HTTP ' . $http_code . '): ' . $body . ' for Post ID: ' . $post_id );

        if ( $http_code >= 200 && $http_code < 300 ) {
            error_log( 'Pushmarket.io Plugin: Post data successfully sent for Post ID ' . $post_id );
        } else {
            error_log( 'Pushmarket.io Plugin: Failed to send post data for Post ID ' . $post_id . '. HTTP Code: ' . $http_code . ', Response: ' . $body );
        }
    }
}
add_action( 'publish_post', 'pmio_send_post_data_on_publish', 10, 2 );

function pmio_enqueue_scripts() {
    if ( is_admin() ) {
        return;
    }

    $project_id = get_option( PMIO_PROJECT_ID_OPTION, '' );
    if ( empty( $project_id ) ) {
        return;
    }

    wp_enqueue_script(
        'pmio-sdk-js',
        'https://pushmarket.io/sdk/pushmarket-io.js?projectId=' . $project_id,
        array(),
        null,
        false
    );

    wp_localize_script(
        'pmio-sdk-js',
        'pmio_vars',
        array(
            'sw_url'    => esc_url( plugins_url( 'js/sw.js', __FILE__ ) ),
            'projectId' => $project_id,
        )
    );
}
add_action( 'wp_enqueue_scripts', 'pmio_enqueue_scripts' );
