<?php
/**
 * Deployment Tab: Scheduled Tasks
 *
 * Displays all agent scheduled tasks, their status, and next run time.
 * Included by admin/deployment.php — do not load directly.
 *
 * @package    Agent_Builder
 * @subpackage Admin
 * @since      1.7.0
 *
 * php version 8.1
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Handle delete scheduled task action.
if ( isset( $_POST['agentic_delete_task'] ) && check_admin_referer( 'agentic_delete_task' ) ) {
	$agentic_delete_hook    = sanitize_text_field( wp_unslash( $_POST['agentic_delete_hook'] ?? '' ) );
	$agentic_delete_agent   = sanitize_key( wp_unslash( $_POST['agentic_delete_agent'] ?? '' ) );
	$agentic_delete_task_id = sanitize_key( wp_unslash( $_POST['agentic_delete_task_id'] ?? '' ) );
	if ( $agentic_delete_hook ) {
		wp_clear_scheduled_hook( $agentic_delete_hook );

		// Disable the Deployments row so the tab shows "Not Scheduled".
		if ( class_exists( '\Agentic\Deployments' ) && $agentic_delete_agent && $agentic_delete_task_id ) {
			foreach ( \Agentic\Deployments::all( \Agentic\Deployments::TYPE_SCHEDULED_TASK, $agentic_delete_agent ) as $agentic_st_del ) {
				if ( ( $agentic_st_del['config']['task_id'] ?? '' ) === $agentic_delete_task_id ) {
					\Agentic\Deployments::disable( $agentic_st_del['id'] );
					break;
				}
			}
		}

		\Agentic\Security_Log::log_system(
			'settings_changed',
			'scheduled_tasks',
			array(
				'setting' => 'delete_task',
				'changes' => array( 'hook' => $agentic_delete_hook ),
			)
		);
		echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Scheduled task removed.', 'agent-builder' ) . '</p></div>';
	}
}

// Handle schedule task action.
if ( isset( $_POST['agentic_schedule_task'] ) && check_admin_referer( 'agentic_schedule_task' ) ) {
	$agentic_sched_hook      = sanitize_text_field( wp_unslash( $_POST['agentic_sched_hook'] ?? '' ) );
	$agentic_sched_recur     = sanitize_text_field( wp_unslash( $_POST['agentic_sched_recurrence'] ?? '' ) );
	$agentic_sched_agent     = sanitize_key( wp_unslash( $_POST['agentic_sched_agent'] ?? '' ) );
	$agentic_sched_task_id   = sanitize_key( wp_unslash( $_POST['agentic_sched_task_id'] ?? '' ) );
	$agentic_valid_schedules = array_keys( wp_get_schedules() );
	if ( $agentic_sched_hook && in_array( $agentic_sched_recur, $agentic_valid_schedules, true ) ) {
		$agentic_next_ts = time();
		if ( ! wp_next_scheduled( $agentic_sched_hook ) ) {
			wp_schedule_event( $agentic_next_ts, $agentic_sched_recur, $agentic_sched_hook );
		} else {
			$agentic_next_ts = (int) wp_next_scheduled( $agentic_sched_hook );
		}

		// Update or create the Deployments row.
		if ( class_exists( '\Agentic\Deployments' ) && $agentic_sched_agent && $agentic_sched_task_id ) {
			$agentic_st_found = null;
			foreach ( \Agentic\Deployments::all( \Agentic\Deployments::TYPE_SCHEDULED_TASK, $agentic_sched_agent ) as $agentic_st_sch ) {
				if ( ( $agentic_st_sch['config']['task_id'] ?? '' ) === $agentic_sched_task_id ) {
					$agentic_st_found = $agentic_st_sch;
					break;
				}
			}

			$agentic_st_cfg = array(
				'task_id'     => $agentic_sched_task_id,
				'schedule'    => $agentic_sched_recur,
				'mode'        => 'autonomous',
				'description' => '',
				'next_run'    => gmdate( 'Y-m-d H:i:s', $agentic_next_ts ),
				'last_run'    => $agentic_st_found['config']['last_run'] ?? null,
				'last_status' => $agentic_st_found['config']['last_status'] ?? null,
			);

			if ( $agentic_st_found ) {
				\Agentic\Deployments::save(
					array_merge(
						array(
							'id'      => $agentic_st_found['id'],
							'enabled' => 1,
						),
						array( 'config' => $agentic_st_cfg )
					)
				);
			} else {
				\Agentic\Deployments::save(
					array(
						'type'       => \Agentic\Deployments::TYPE_SCHEDULED_TASK,
						'agent_slug' => $agentic_sched_agent,
						'label'      => ucwords( str_replace( '-', ' ', $agentic_sched_agent ) ) . ' — ' . $agentic_sched_task_id,
						'enabled'    => 1,
						'source'     => \Agentic\Deployments::SOURCE_ADMIN,
						'config'     => $agentic_st_cfg,
					)
				);
			}
		}

		\Agentic\Security_Log::log_system(
			'settings_changed',
			'scheduled_tasks',
			array(
				'setting' => 'schedule_task',
				'changes' => array(
					'hook'       => $agentic_sched_hook,
					'recurrence' => $agentic_sched_recur,
				),
			)
		);
		echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Scheduled task registered.', 'agent-builder' ) . '</p></div>';
	}
}

// Collect all scheduled tasks from active agents.
$agentic_registry  = \Agentic_Agent_Registry::get_instance();
$agentic_instances = $agentic_registry->get_all_instances();
$agentic_all_tasks = array();

// Pre-load Deployments rows indexed by agent_slug + task_id.
$agentic_st_rows = array();
if ( class_exists( '\Agentic\Deployments' ) ) {
	foreach ( \Agentic\Deployments::all( \Agentic\Deployments::TYPE_SCHEDULED_TASK ) as $agentic_st_r ) {
		$agentic_st_key                     = $agentic_st_r['agent_slug'] . '|' . ( $agentic_st_r['config']['task_id'] ?? '' );
		$agentic_st_rows[ $agentic_st_key ] = $agentic_st_r;
	}
}

foreach ( $agentic_instances as $agentic_agent ) {
	$agentic_tasks = $agentic_agent->get_scheduled_tasks();
	foreach ( $agentic_tasks as $agentic_task ) {
		$agentic_hook      = $agentic_agent->get_cron_hook( $agentic_task['id'] );
		$agentic_next_run  = wp_next_scheduled( $agentic_hook );
		$agentic_schedules = wp_get_schedules();

		$agentic_st_key = $agentic_agent->get_id() . '|' . $agentic_task['id'];
		$agentic_st_row = $agentic_st_rows[ $agentic_st_key ] ?? null;

		// Auto-register in Deployments on first display.
		if ( class_exists( '\Agentic\Deployments' ) && ! $agentic_st_row ) {
			$agentic_st_new_id = \Agentic\Deployments::save(
				array(
					'type'       => \Agentic\Deployments::TYPE_SCHEDULED_TASK,
					'agent_slug' => $agentic_agent->get_id(),
					'label'      => $agentic_agent->get_name() . ' — ' . $agentic_task['name'],
					'enabled'    => false !== $agentic_next_run ? 1 : 0,
					'source'     => \Agentic\Deployments::SOURCE_AUTO,
					'config'     => array(
						'task_id'     => $agentic_task['id'],
						'schedule'    => $agentic_task['schedule'],
						'mode'        => ! empty( $agentic_task['prompt'] ) ? 'autonomous' : 'direct',
						'description' => $agentic_task['description'] ?? '',
						'next_run'    => $agentic_next_run ? gmdate( 'Y-m-d H:i:s', (int) $agentic_next_run ) : null,
						'last_run'    => null,
						'last_status' => null,
					),
				)
			);
			$agentic_st_row    = \Agentic\Deployments::get( $agentic_st_new_id );
		}

		$agentic_all_tasks[] = array(
			'agent_id'         => $agentic_agent->get_id(),
			'agent_name'       => $agentic_agent->get_name(),
			'agent_icon'       => $agentic_agent->get_icon(),
			'task_id'          => $agentic_task['id'],
			'task_name'        => $agentic_task['name'],
			'description'      => $agentic_task['description'] ?? '',
			'schedule'         => $agentic_task['schedule'],
			'schedule_display' => $agentic_schedules[ $agentic_task['schedule'] ]['display'] ?? ucfirst( $agentic_task['schedule'] ),
			'hook'             => $agentic_hook,
			'next_run'         => $agentic_next_run,
			'registered'       => false !== $agentic_next_run,
			'mode'             => ! empty( $agentic_task['prompt'] ) ? 'autonomous' : 'direct',
			'last_run'         => $agentic_st_row['config']['last_run'] ?? null,
			'last_status'      => $agentic_st_row['config']['last_status'] ?? null,
		);
	}
}

?>
<?php if ( empty( $agentic_all_tasks ) ) : ?>
	<div class="notice notice-info">
		<p><?php esc_html_e( 'No scheduled tasks found. Activate assistants that define scheduled tasks to see them here.', 'agent-builder' ); ?></p>
	</div>
<?php else : ?>
	<table class="widefat striped">
		<thead>
			<tr>
				<th><?php esc_html_e( 'Agent', 'agent-builder' ); ?></th>
				<th><?php esc_html_e( 'Task', 'agent-builder' ); ?></th>
				<th><?php esc_html_e( 'Schedule', 'agent-builder' ); ?></th>
				<th><?php esc_html_e( 'Mode', 'agent-builder' ); ?></th>
				<th><?php esc_html_e( 'Status', 'agent-builder' ); ?></th>
				<th><?php esc_html_e( 'Next Run', 'agent-builder' ); ?></th>
				<th><?php esc_html_e( 'Last Run', 'agent-builder' ); ?></th>
				<th><?php esc_html_e( 'Actions', 'agent-builder' ); ?></th>
			</tr>
		</thead>
		<tbody>
			<?php foreach ( $agentic_all_tasks as $agentic_task_row ) : ?>
			<tr>
				<td>
					<span class="agentic-agent-icon"><?php echo esc_html( $agentic_task_row['agent_icon'] ); ?></span>
					<?php echo esc_html( $agentic_task_row['agent_name'] ); ?>
				</td>
				<td>
					<strong><?php echo esc_html( $agentic_task_row['task_name'] ); ?></strong>
					<?php if ( $agentic_task_row['description'] ) : ?>
						<br><small class="agentic-text-muted"><?php echo esc_html( $agentic_task_row['description'] ); ?></small>
					<?php endif; ?>
				</td>
				<td><?php echo esc_html( $agentic_task_row['schedule_display'] ); ?></td>
				<td>
					<?php if ( 'autonomous' === $agentic_task_row['mode'] ) : ?>
						<span title="<?php esc_attr_e( 'Runs through the LLM with AI reasoning and tool calls', 'agent-builder' ); ?>" style="color: #2271b1;">🤖 <?php esc_html_e( 'AI', 'agent-builder' ); ?></span>
					<?php else : ?>
						<span title="<?php esc_attr_e( 'Runs the callback method directly without LLM', 'agent-builder' ); ?>" style="color: #646970;">⚙️ <?php esc_html_e( 'Direct', 'agent-builder' ); ?></span>
					<?php endif; ?>
				</td>
				<td>
					<?php if ( $agentic_task_row['registered'] ) : ?>
						<span class="agentic-status-active">&#9679; <?php esc_html_e( 'Active', 'agent-builder' ); ?></span>
					<?php else : ?>
						<span class="agentic-status-inactive">&#9679; <?php esc_html_e( 'Not Scheduled', 'agent-builder' ); ?></span>
					<?php endif; ?>
				</td>
				<td>
					<?php if ( $agentic_task_row['next_run'] ) : ?>
						<?php echo esc_html( wp_date( 'Y-m-d H:i', $agentic_task_row['next_run'] ) ); ?>
						<br><small class="agentic-text-muted">
							<?php
							$agentic_diff = $agentic_task_row['next_run'] - time();
							if ( $agentic_diff > 0 ) {
								/* translators: %s: human-readable time difference */
								printf( esc_html__( 'in %s', 'agent-builder' ), esc_html( human_time_diff( time(), $agentic_task_row['next_run'] ) ) );
							} else {
								esc_html_e( 'overdue', 'agent-builder' );
							}
							?>
						</small>
					<?php else : ?>
						&mdash;
					<?php endif; ?>
				</td>
				<td>
					<?php if ( $agentic_task_row['last_run'] ) : ?>
						<?php echo esc_html( wp_date( 'Y-m-d H:i', strtotime( $agentic_task_row['last_run'] ) ) ); ?>
						<?php if ( $agentic_task_row['last_status'] ) : ?>
							<br><small class="<?php echo 'ok' === $agentic_task_row['last_status'] ? 'agentic-text-green' : 'agentic-text-danger'; ?>">
								<?php echo esc_html( $agentic_task_row['last_status'] ); ?>
							</small>
						<?php endif; ?>
					<?php else : ?>
						&mdash;
					<?php endif; ?>
				</td>
				<td>
					<?php if ( $agentic_task_row['registered'] ) : ?>
						<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=agentic-run-task&agent=' . rawurlencode( $agentic_task_row['agent_id'] ) . '&task=' . rawurlencode( $agentic_task_row['task_id'] ) ), 'agentic_run_task', '_wpnonce' ) ); ?>" class="button button-small">
							<?php esc_html_e( 'Run Now', 'agent-builder' ); ?>
						</a>
						<form method="post" class="agentic-form-inline" data-agentic-confirm="<?php echo esc_attr( __( 'Remove this scheduled task from the cron queue?', 'agent-builder' ) ); ?>" data-agentic-confirm-danger>
							<?php wp_nonce_field( 'agentic_delete_task' ); ?>
							<input type="hidden" name="agentic_delete_hook"    value="<?php echo esc_attr( $agentic_task_row['hook'] ); ?>">
							<input type="hidden" name="agentic_delete_agent"   value="<?php echo esc_attr( $agentic_task_row['agent_id'] ); ?>">
							<input type="hidden" name="agentic_delete_task_id" value="<?php echo esc_attr( $agentic_task_row['task_id'] ); ?>">
							<button type="submit" name="agentic_delete_task" value="1" class="button button-small agentic-text-danger">
								<?php esc_html_e( 'Delete', 'agent-builder' ); ?>
							</button>
						</form>
					<?php else : ?>
						<form method="post" class="agentic-form-inline">
							<?php wp_nonce_field( 'agentic_schedule_task' ); ?>
							<input type="hidden" name="agentic_sched_hook"       value="<?php echo esc_attr( $agentic_task_row['hook'] ); ?>">
							<input type="hidden" name="agentic_sched_recurrence" value="<?php echo esc_attr( $agentic_task_row['schedule'] ); ?>">
							<input type="hidden" name="agentic_sched_agent"      value="<?php echo esc_attr( $agentic_task_row['agent_id'] ); ?>">
							<input type="hidden" name="agentic_sched_task_id"    value="<?php echo esc_attr( $agentic_task_row['task_id'] ); ?>">
							<button type="submit" name="agentic_schedule_task" value="1" class="button button-small button-primary">
								<?php esc_html_e( 'Schedule', 'agent-builder' ); ?>
							</button>
						</form>
					<?php endif; ?>
				</td>
			</tr>
			<?php endforeach; ?>
		</tbody>
	</table>

	<div class="agentic-embed-note">
		<h3><?php esc_html_e( 'How Scheduled Tasks Work', 'agent-builder' ); ?></h3>
		<ul>
			<li><?php esc_html_e( 'Tasks use WordPress cron (WP-Cron) which runs when someone visits your site.', 'agent-builder' ); ?></li>
			<li><?php esc_html_e( 'For reliable scheduling on low-traffic sites, set up a real cron job to hit wp-cron.php.', 'agent-builder' ); ?></li>
			<li><?php esc_html_e( 'Tasks are automatically registered when an assistant is activated and removed when deactivated.', 'agent-builder' ); ?></li>
			<li><?php esc_html_e( 'AI mode tasks run through the LLM with full tool access. Direct mode tasks call a PHP method. If the LLM is not configured, AI tasks gracefully fall back to direct mode.', 'agent-builder' ); ?></li>
			<li><?php esc_html_e( 'Every execution is logged in the Audit Log with timing, mode, and outcome details.', 'agent-builder' ); ?></li>
		</ul>
	</div>
<?php endif; ?>
