<?php
/**
 * Salesforce integration AJAX handlers for SiteStaffr admin.
 *
 * Connect / Disconnect / status for the Settings → Integrations card. All three
 * require a valid nonce + manage_options and delegate to SiteStaffr_Salesforce.
 *
 * @package    SiteStaffr
 * @subpackage SiteStaffr/admin/traits
 * @since      1.36.0
 */

if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * Encapsulates the Salesforce connect/disconnect/status AJAX actions.
 */
trait SiteStaffr_Admin_Salesforce_Ajax_Trait {

	/**
	 * Shared guard: verify nonce + capability, or send a JSON error and return false.
	 *
	 * @return bool
	 */
	private function sf_ajax_guard() {
		if ( ! check_ajax_referer( 'sitestaffr_ajax_nonce', 'nonce', false ) ) {
			wp_send_json_error( array( 'message' => __( 'Security check failed. Please refresh and try again.', 'sitestaffr' ) ) );
			return false;
		}
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => __( 'You do not have permission to do this.', 'sitestaffr' ) ) );
			return false;
		}
		if ( ! class_exists( 'SiteStaffr_Salesforce' ) ) {
			wp_send_json_error( array( 'message' => __( 'Salesforce integration unavailable.', 'sitestaffr' ) ) );
			return false;
		}
		return true;
	}

	/**
	 * Begin the OAuth connect flow: return the Salesforce authorize URL for the
	 * browser to redirect to.
	 *
	 * @return void
	 */
	public function ajax_sf_connect() {
		if ( ! $this->sf_ajax_guard() ) {
			return;
		}
		$url = SiteStaffr_Salesforce::get_authorize_url();
		if ( '' === $url ) {
			wp_send_json_error( array( 'message' => __( 'Could not start the Salesforce connection. Check that this site has completed setup.', 'sitestaffr' ) ) );
			return;
		}
		wp_send_json_success( array( 'authorize_url' => $url ) );
	}

	/**
	 * Disconnect Salesforce (revoke + clear at the middleware).
	 *
	 * @return void
	 */
	public function ajax_sf_disconnect() {
		if ( ! $this->sf_ajax_guard() ) {
			return;
		}
		if ( SiteStaffr_Salesforce::disconnect() ) {
			wp_send_json_success( array( 'message' => __( 'Salesforce disconnected.', 'sitestaffr' ) ) );
			return;
		}
		wp_send_json_error( array( 'message' => __( 'Could not disconnect Salesforce. Please try again.', 'sitestaffr' ) ) );
	}

	/**
	 * Return the current (freshly fetched) connection status.
	 *
	 * @return void
	 */
	public function ajax_sf_status() {
		if ( ! $this->sf_ajax_guard() ) {
			return;
		}
		wp_send_json_success( SiteStaffr_Salesforce::get_status( true ) );
	}
}
