<?php
/**
 * WP Cron Event Schedule Tool.
 *
 * Allows the agent to schedule new WordPress cron events with single or
 * recurring recurrence patterns.
 *
 * @package   Agenistrator
 * @since     1.0.0
 * @author    Alex Ruban <alex@maximum.guru>
 * @author    Maximum Software Inc <contact@maximum.software>
 * @license   GPL-3.0-only
 * @link      https://agenistrator.com/
 *
 * SPDX-FileCopyrightText: 2025-2026 Alex Ruban <alex@maximum.guru>
 * SPDX-FileCopyrightText: 2025-2026 Maximum Software Inc <contact@maximum.software>
 * SPDX-License-Identifier: GPL-3.0-only
 */

namespace Agenistrator;

// Direct access prevention
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * WP_Cron_Event_Schedule_Tool class.
 */
class WP_Cron_Event_Schedule_Tool extends Tool {

	/**
	 * Get the tool ID.
	 *
	 * @return string The tool ID.
	 * @since     1.0.0
	 */
	public function get_id() {
		return 'schedule_cron_event';
	}

	/**
	 * Get the tool name.
	 *
	 * @return string The tool name.
	 * @since     1.0.0
	 */
	public function get_name() {
		return __( 'Schedule Cron Event', 'agenistrator' );
	}

	/**
	 * Get the description of the tool.
	 *
	 * @return string The description of the tool.
	 * @since     1.0.0
	 */
	public function get_description() {
		return 'Schedules a new WordPress cron event. Can be a one-time event or recurring.';
	}

	/**
	 * Get the parameters for this tool.
	 *
	 * @return array Parameters schema in JSON Schema format.
	 * @since     1.0.0
	 */
	public function get_parameters() {
		return array(
			'type'       => 'object',
			'properties' => array(
				'hook'       => array(
					'type'        => 'string',
					'description' => 'The hook name for the cron event.',
				),
				'next_run'   => array(
					'type'        => 'string',
					'description' => 'When to run the event. Can be a Unix timestamp, a strtotime()-compatible string (e.g., "+1 hour", "tomorrow 9am"), or "now".',
				),
				'recurrence' => array(
					'type'        => 'string',
					'description' => 'Recurrence schedule name (e.g., "hourly", "twicedaily", "daily", "weekly"). Omit for a one-time event.',
				),
				'args'       => array(
					'type'        => 'array',
					'description' => 'Optional arguments to pass to the hook callback.',
					'items'       => array( 'type' => 'string' ),
				),
			),
			'required'   => array( 'hook', 'next_run' ),
		);
	}

	/**
	 * Check if the current user has permission to execute this tool.
	 *
	 * @return bool Whether the user has permission.
	 * @since     1.0.0
	 */
	public function current_user_can_execute() {
		return current_user_can( 'manage_options' );
	}

	/**
	 * Check if this tool is read-only.
	 *
	 * @return bool False - this tool modifies data.
	 * @since     1.0.0
	 */
	public function is_read_only() {
		return false;
	}

	/**
	 * Execute the tool with the given arguments.
	 *
	 * @param array $args The arguments for the tool.
	 * @return array The result of executing the tool.
	 * @since     1.0.0
	 */
	protected function execute( $args ) {
		$hook = trim( $args['hook'] );
		if ( ! preg_match( '/^[a-zA-Z_][a-zA-Z0-9_]*$/', $hook ) ) {
			return $this->error_response( 'Invalid hook name format. Must start with a letter or underscore, followed by letters, numbers, or underscores.' );
		}

		$next_run   = $args['next_run'];
		$recurrence = $args['recurrence'] ?? null;
		$event_args = $args['args'] ?? array();

		// Parse next_run time.
		if ( is_numeric( $next_run ) ) {
			$timestamp = (int) $next_run;
		} elseif ( 'now' === strtolower( $next_run ) ) {
			$timestamp = time();
		} else {
			$timestamp = strtotime( $next_run );
			if ( false === $timestamp ) {
				return $this->error_response( "Invalid next_run time format: {$next_run}" );
			}
		}

		// Validate recurrence if provided.
		if ( $recurrence ) {
			$schedules = wp_get_schedules();
			if ( ! isset( $schedules[ $recurrence ] ) ) {
				$available = implode( ', ', array_keys( $schedules ) );
				return $this->error_response( "Invalid recurrence: {$recurrence}. Available schedules: {$available}" );
			}
		}

		// Schedule the event.
		if ( $recurrence ) {
			$result = wp_schedule_event( $timestamp, $recurrence, $hook, $event_args );
		} else {
			$result = wp_schedule_single_event( $timestamp, $hook, $event_args );
		}

		if ( false === $result ) {
			return $this->error_response( 'Failed to schedule cron event. The event may already be scheduled.' );
		}

		return $this->success_response(
			'Cron event scheduled successfully',
			array(
				'hook'          => $hook,
				'next_run'      => $timestamp,
				'next_run_date' => gmdate( 'Y-m-d H:i:s e', $timestamp ),
				'recurrence'    => $recurrence ? $recurrence : 'one-time',
				'args'          => $event_args,
			)
		);
	}
}
