<?php
/**
 * Plugin Name: Locomote by Diffusal - AI Content Automation
 * Plugin URI: https://locomote.io/
 * Description: Simple to use WordPress plugin that automates your content creation, scheduling, and publishing. All in one place.
 * Version: 1.0.1
 * Author: Diffusal
 * Author URI: https://diffusal.io/
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: diffusal-locomote
 *
 * @package Locomote
 */

 /*
 * Locomote by Diffusal - AI Content Automation
 * Copyright (c) 2025 GIIKI DOOEL
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see https://www.gnu.org/licenses/.
 */


// Make sure we don't expose any info if called directly.
if ( ! function_exists( 'add_action' ) ) {
	exit;
}


/**
 * Hook the 'locomote_create_menu' function into the 'admin_menu' action.
 * This function is responsible for adding a main menu item to the WordPress admin sidebar.
 * The page will contain the ID of the HTML element that hosts the JSX components.
 */
add_action( 'admin_menu', 'locomote_create_menu' );

/**
 * Adds a main menu item to the WordPress admin sidebar.
 * The page will contain the ID of the HTML element that hosts our JSX components.
 *
 * @return void
 */
function locomote_create_menu() {
    add_menu_page(
        esc_html__( 'Locomote Admin', 'diffusal-locomote' ),
        esc_html__( 'Locomote', 'diffusal-locomote' ),
        'manage_options',
        'diffusal-locomote-dashboard',
        'locomote_display_menu',
        'dashicons-admin-generic',
        30
    );

    add_submenu_page(
        'diffusal-locomote-dashboard',
        'Dashboard',
        'Dashboard',
        'manage_options',
        'diffusal-locomote-dashboard',
        'locomote_display_menu'
    );

    add_submenu_page(
        'diffusal-locomote-dashboard',
        'Settings',
        'Settings',
        'manage_options',
        'diffusal-locomote-settings',
        'locomote_display_menu'
    );

    add_submenu_page(
        'diffusal-locomote-dashboard',
        'Tasks',
        'Tasks',
        'manage_options',
        'diffusal-locomote-tasks',
        'locomote_display_menu'
    );
}



/**
 * Callback function to display the submenu page.
 * Outputs the HTML element with the ID 'main' where JSX components will be rendered.
 *
 * @return void
 */
function locomote_display_menu() {
	echo '<div id="main"></div>';
}


/**
 * Hook the 'locomote_enqueue_script' function into the 'admin_enqueue_scripts' action.
 * This function is responsible for enqueueing the JavaScript script generated by WebPack.
 */
add_action( 'admin_enqueue_scripts', 'locomote_enqueue_script' );

/**
 * Enqueues the JavaScript script generated by WebPack for the plugin.
 *
 * @return void
 */
function locomote_enqueue_script() {
    
    $is_dev = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG;


    $bundle_path = $is_dev 
        ? plugins_url( '/public/bundle.js', __FILE__ ) // Development bundle
        : plugins_url( '/dist/public/bundle.js', __FILE__ ); // Production bundle

	$version = file_exists( $bundle_path ) ? filemtime( $bundle_path ) : time();

    wp_enqueue_script(
        'diffusal-locomote-plugin-reactjs',
        $bundle_path,
        array( 'wp-element', 'wp-components' ),
        $version,
        true 
    );

    // Localize dynamic settings
    $current_user = wp_get_current_user();
        wp_localize_script( 'diffusal-locomote-plugin-reactjs', 'wpPluginReactConfig', array(
        'apiBaseUrl' => get_rest_url(),
        'ajaxUrl' => admin_url( 'admin-ajax.php' ),
        'siteUrl' => get_site_url(),
        'currentUser' => array(
            'id' => $current_user ? $current_user->ID : 0,
            'login' => $current_user ? $current_user->user_login : '',
            'email' => $current_user ? $current_user->user_email : '',
        ),
        'featureToggles' => array(
            'enableExperimentalFeature' => true,
        ),
        'appVersion' => '1.0.1',
    ) ); 
}

add_action('init', function () {

    $origin = '';
    if ( isset( $_SERVER['HTTP_ORIGIN'] ) ) {
        $origin = sanitize_text_field( wp_unslash( $_SERVER['HTTP_ORIGIN'] ) );
        header( "Access-Control-Allow-Origin: $origin" );
    }

    header( "Access-Control-Allow-Methods: GET, POST, OPTIONS" );
    header( "Access-Control-Allow-Credentials: true" );
    header( "Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With" );

    $method = isset( $_SERVER['REQUEST_METHOD'] )
        ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) )
        : '';

    if ( $method === 'OPTIONS' ) {
        status_header( 200 );
        exit;
    }
});


/**
 * AJAX: Generate or fetch an Application Password named "locomote_app" for the current user
 */
add_action( 'wp_ajax_locomote_generate_app_password', 'locomote_generate_app_password' );
function locomote_generate_app_password() {
    if ( ! current_user_can( 'manage_options' ) ) {
        wp_send_json_error( array( 'message' => 'Unauthorized' ), 403 );
    }

    if ( ! class_exists( 'WP_Application_Passwords' ) ) {
        wp_send_json_error( array( 'message' => 'Application Passwords not available' ), 500 );
    }

    $user_id = get_current_user_id();
    if ( ! $user_id ) {
        wp_send_json_error( array( 'message' => 'No current user' ), 400 );
    }

    $app_name = 'locomote_app';
    $existing_password = '';

    $existing = WP_Application_Passwords::get_user_application_passwords( $user_id );
    if ( is_array( $existing ) ) {
        foreach ( $existing as $item ) {
            if ( isset( $item['name'] ) && $item['name'] === $app_name ) {
                // We cannot recover the raw password; create a new one to present to the client
                // Alternatively, delete and recreate to ensure a fresh visible password
                WP_Application_Passwords::delete_application_password( $user_id, $item['uuid'] );
                break;
            }
        }
    }

    $created = WP_Application_Passwords::create_new_application_password( $user_id, array( 'name' => $app_name ) );
    // Core returns array( $new_password, $item )
    if ( is_wp_error( $created ) || ! is_array( $created ) ) {
        wp_send_json_error( array( 'message' => 'Failed to create application password' ), 500 );
    }

    $new_password = '';
    if ( isset( $created[0] ) && is_string( $created[0] ) ) {
        $new_password = $created[0];
    } elseif ( isset( $created['password'] ) ) {
        $new_password = $created['password'];
    }

    if ( empty( $new_password ) ) {
        wp_send_json_error( array( 'message' => 'Could not read generated password' ), 500 );
    }

    $user = get_user_by( 'id', $user_id );
    wp_send_json_success( array(
        'wp_url' => get_site_url(),
        'wp_username' => $user ? $user->user_login : '',
        'wp_email' => $user ? $user->user_email : '',
        'wp_app_password' => $new_password,
        'app_name' => $app_name,
    ) );
}

