<?php

use Starfish\Migrations as SRM_MIGRATIONS;
use Starfish\Feedback as SRM_FEEDBACK;
use Starfish\Logging as SRM_LOGGING;
use Starfish\Freemius as SRM_FREEMIUS;

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

/**
 * Process Plugin Migrations; triggered from Admin Notice.
 *
 * @return null
 * @see    /js/starfish-admin-main.js
 * @see    /init/actions/starfish-admin-notices.action.php
 */
function srm_start_plugin_migrations() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'forbidden', 403 );
	}
	check_ajax_referer( 'srm_settings', 'security' );

	if ( ! empty( $_POST['retry'] ) ) {
		delete_option( 'srm_migrations' );
		delete_transient( 'srm_pending_migrations' );
		delete_transient( 'srm_failed_migrations' );
		delete_transient( 'srm_successful_migrations' );
		SRM_MIGRATIONS::ingest();
	}
	try {
		SRM_MIGRATIONS::execute_pending();
		echo wp_json_encode( array( 'msg' => 'success' ) );
	} catch ( Exception $e ) {
		echo wp_json_encode( array( 'msg' => 'fail' ) );
	}
	wp_die();
}

add_action( 'wp_ajax_starfish-execute-migrations', 'srm_start_plugin_migrations' );

/**
 * Process Restoration of Options; triggered from Admin Funnel or Settings.
 * If $_POST['funnel_id'] is provided then the funnel will be restored to current default values.
 * Otherwise, the current defaults will be restored to original system default values
 *
 * @see /init/actions/starfish-admin-notices.action.php
 * @see /js/starfish-admin-funnel.js
 **/
function srm_restore_options_defaults() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'forbidden', 403 );
	}
	check_ajax_referer( 'srm_settings', 'security' );

	$options = isset( $_POST['options'] ) ? (array) wp_unslash( $_POST['options'] ) : array();
	if ( isset( $_POST['funnel_id'] ) ) {
		$funnel_id = (int) $_POST['funnel_id'];
		if ( ! current_user_can( 'edit_post', $funnel_id ) ) {
			wp_send_json_error( 'forbidden', 403 );
		}
		foreach ( $options as $option => $args ) {
			$meta_key = isset( $args['funnel_cf_id'] ) ? sanitize_key( $args['funnel_cf_id'] ) : '';
			if ( '' !== $meta_key && str_starts_with( $meta_key, '_srm_' ) ) {
				update_post_meta( $funnel_id, $meta_key, $args['current'] ?? '' );
			}
		}
	} else {
		foreach ( $options as $option => $args ) {
			$option_name = sanitize_key( $option );
			if ( str_starts_with( $option_name, 'srm_' ) && isset( $args['default'] ) ) {
				update_option( $option_name, stripslashes( $args['default'] ) );
			}
		}
	}
	echo wp_json_encode( array( 'type' => 'success' ) );
	wp_die();
}

add_action( 'wp_ajax_starfish-execute-restore-default-options', 'srm_restore_options_defaults' );

/**
 * Export Feedback
 **/
function srm_export_feedback() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'forbidden', 403 );
	}
	if ( ! isset( $_POST['security'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['security'] ) ), 'srm-export-feedback' ) ) {
		echo wp_json_encode( array( 'type' => 'failed' ) );
		wp_die();
	}
	$feedback  = null;
	$funnel_id = isset( $_POST['funnel_id'] ) ? absint( $_POST['funnel_id'] ) : null;
	$month     = isset( $_POST['month'] ) ? sanitize_text_field( wp_unslash( $_POST['month'] ) ) : null;

	// retrieve feedback
	$feedback = SRM_FEEDBACK::srm_get_feedback( $funnel_id, $month );

	// export feedback to CSV
	$filename = 'starfish_feedback_' . strtotime( 'now' ) . '.csv';

	// create a file pointer connected to the output stream
	$output = fopen( SRM_PLUGIN_PATH . '/exports/' . $filename, 'w' );

	// output the column headings
	fputcsv( $output, array( 'Date', 'ID', 'Reviewer Name', 'Reviewer Phone', 'Reviewer Email', 'Feedback', 'Message', 'Funnel', 'Destination' ) );

	// loop over the rows, outputting them
	while ( $feedback->have_posts() ) {
		$feedback->the_post();
		$response = get_post_meta( get_the_ID(), SRM_META_REVIEWER_FEEDBACK, true );
		$record   = array(
			'date'           => get_the_date(),
			'id'             => get_post_meta( get_the_ID(), SRM_META_TRACKING_ID, true ),
			'reviewer_name'  => get_post_meta( get_the_ID(), SRM_META_REVIEWER_NAME, true ),
			'reviewer_phone' => get_post_meta( get_the_ID(), SRM_META_REVIEWER_PHONE, true ),
			'reviewer_email' => get_post_meta( get_the_ID(), SRM_META_REVIEWER_EMAIL, true ),
			'feedback'       => ( true === filter_var( $response, FILTER_VALIDATE_BOOLEAN ) ) ? 'Positive' : 'Negative',
			'message'        => get_the_content(),
			'funnel'         => get_the_title( get_post_meta( get_the_ID(), SRM_META_FUNNEL_ID, true ) ),
			'destination'    => get_post_meta( get_the_ID(), SRM_META_DESTI_NAME, true ),
		);
		fputcsv( $output, $record );
	}
	echo wp_json_encode(
		array(
			'type'      => 'success',
			'url'       => SRM_PLUGIN_URL . '/exports/' . $filename,
			'file_name' => basename(
				$filename,
				'.csv'
			),
		)
	);
	wp_die();
}
add_action( 'wp_ajax_srm-export-feedback', 'srm_export_feedback' );

/**
 * Delete Feedback Export
 **/
function srm_delete_feedback_export() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'forbidden', 403 );
	}
	if ( ! isset( $_POST['security'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['security'] ) ), 'srm-export-feedback' ) ) {
		echo wp_json_encode( array( 'type' => 'failed' ) );
		wp_die();
	}

	$raw  = isset( $_POST['file'] ) ? sanitize_text_field( wp_unslash( $_POST['file'] ) ) : '';
	// Strip any directory components and disallow anything other than the expected name shape.
	$safe = basename( $raw );
	if ( '' === $safe || ! preg_match( '/^starfish_feedback_\d+$/', $safe ) ) {
		echo wp_json_encode( array( 'type' => 'failed' ) );
		wp_die();
	}
	$path = SRM_PLUGIN_PATH . 'exports/' . $safe . '.csv';
	$real = realpath( $path );
	$base = realpath( SRM_PLUGIN_PATH . 'exports/' );

	if ( $real && $base && 0 === strpos( $real, $base . DIRECTORY_SEPARATOR ) && unlink( $real ) ) {
		echo wp_json_encode( array( 'type' => 'success' ) );
	} else {
		echo wp_json_encode( array( 'type' => 'failed' ) );
	}
	wp_die();
}
add_action( 'wp_ajax_srm-delete-feedback-export', 'srm_delete_feedback_export' );

/**
 * Purge Log file
 */
function srm_purge_logfile() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'forbidden', 403 );
	}
	if ( ! isset( $_POST['security'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['security'] ) ), 'srm_settings' ) ) {
		echo wp_json_encode( array( 'type' => 'failed' ) );
		wp_die();
	}
	$purged = SRM_LOGGING::purgeLogs();
	if ( $purged ) {
		echo wp_json_encode(
			array(
				'type'    => 'success',
				'content' => 'No Logs Available.',
			)
		);
	} else {
		echo wp_json_encode( array( 'type' => 'failed' ) );
	}
	wp_die();
}
add_action( 'wp_ajax_srm-settings-logs-purge', 'srm_purge_logfile' );

/**
 * Refresh Log file
 */
function srm_refresh_logfile() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'forbidden', 403 );
	}
	check_ajax_referer( 'srm_settings', 'security' );
	if ( file_exists( SRM_LOG_FILE ) ) {
		$logs = file_get_contents( SRM_LOG_FILE );
		if ( ! empty( $logs ) ) {
			$results = wp_json_encode(
				array(
					'type'    => 'success',
					'content' => $logs,
				)
			);
		} else {
			$results = wp_json_encode(
				array(
					'type'    => 'success',
					'content' => 'No Logs Available.',
				)
			);
		}
	} else {
		$results = wp_json_encode(
			array(
				'type'    => 'success',
				'content' => 'No Logs Available.',
			)
		);
	}
	echo $results;
	wp_die();
}
add_action( 'wp_ajax_srm-settings-logs-refresh', 'srm_refresh_logfile' );

/**
 * Refresh Plan Limits
 */
function srm_refresh_plan_limits() {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_send_json_error( 'forbidden', 403 );
	}
	check_ajax_referer( 'srm_settings', 'security' );
	if ( delete_transient( SRM_TRAN_PLAN_LIMITS ) ) {
		$srm_error_cya = '01';
		$plan_limits   = SRM_FREEMIUS::srm_get_plan_limit();
		SRM_LOGGING::addEntry(
			array(
				'level'   => SRM_LOGGING::SRM_INFO,
				'action'  => 'Successfully refreshed Plan Limits',
				'message' => null,
				'code'    => 'SRM_B_RPL_A_' . $srm_error_cya,
			)
		);
		$results = wp_json_encode(
			array(
				'type'    => 'success',
				'content' => [
					'collections' => $plan_limits['collections'],
					'profiles'    => $plan_limits['profiles'],
					'funnels'     => $plan_limits['funnels'],
				]
			)
		);
	} else {
		$results = wp_json_encode(
			array(
				'type'    => 'failure',
				'content' => null,
			)
		);
	}
	echo $results;
	wp_die();
}
add_action( 'wp_ajax_starfish-execute-plan-limit-refresh', 'srm_refresh_plan_limits' );

/**
 * Get Transient for front-end usage.
 *
 * @return void
 */
function srm_get_transient() {
	if ( ! current_user_can( 'edit_posts' ) ) {
		wp_send_json_error( 'forbidden', 403 );
	}
	check_ajax_referer( 'srm_settings', 'security' );

	$requested = isset( $_POST['transient'] ) ? sanitize_key( wp_unslash( $_POST['transient'] ) ) : '';
	$allowed   = array(
		SRM_TRAN_CRON_LAST_PROFILE_SCRAPE_DATE,
		SRM_TRAN_PLAN_LIMITS,
		SRM_TRAN_RICHREVIEWS_MIGRATION,
		'srm_pending_migrations',
		'srm_successful_migrations',
		'srm_failed_migrations',
	);
	if ( ! in_array( $requested, $allowed, true ) ) {
		echo wp_json_encode( array( 'type' => 'failure', 'content' => null ) );
		wp_die();
	}
	$transient = get_transient( $requested );
	if ( $transient ) {
		$results = wp_json_encode(
			array(
				'type'    => 'success',
				'content' => $transient
			)
		);
	} else {
		$results = wp_json_encode(
			array(
				'type'    => 'failure',
				'content' => $transient,
			)
		);
	}
	echo $results;
	wp_die();
}
add_action( 'wp_ajax_starfish-get-transient', 'srm_get_transient' );
