<?php
/**
 * Admin Trial Bookings Class
 *
 * Handles the admin interface for trial bookings
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/admin
 * @since      1.0.61
 */

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

/**
 * Admin Trial Bookings Class
 *
 * @since 1.0.61
 */
class MACM_Admin_Trial_Bookings {

	/**
	 * Initialize the class
	 *
	 * @since 1.0.61
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ), 20 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'wp_ajax_macm_mark_booking_complete', array( $this, 'mark_booking_complete' ) );
		add_action( 'wp_ajax_macm_mark_booking_pending', array( $this, 'mark_booking_pending' ) );
		add_action( 'wp_ajax_macm_send_booking_email', array( $this, 'send_booking_email' ) );
		add_action( 'wp_ajax_macm_save_admin_note', array( $this, 'save_admin_note' ) );
		add_action( 'admin_post_macm_save_trial_booking_settings', array( $this, 'save_settings' ) );
	}

	/**
	 * Add submenu page
	 *
	 * @since 1.0.61
	 */
	public function add_menu_page() {
		add_submenu_page(
			'martial-arts-club-manager',
			__( 'Trial Classes', 'martial-arts-club-manager' ),
			__( 'Trial Classes', 'martial-arts-club-manager' ),
			'manage_macm_settings',
			'kcm-trial-bookings',
			array( $this, 'render_page' )
		);
	}

	/**
	 * Enqueue scripts
	 *
	 * @since 1.0.61
	 * @param string $hook The current admin page hook.
	 */
	public function enqueue_scripts( $hook ) {
		// Check if we're on the trial bookings page using filter_input for secure access.
		$current_page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( 'kcm-trial-bookings' !== sanitize_key( (string) $current_page ) ) {
			return;
		}

		// Enqueue media uploader and editor.
		wp_enqueue_media();
		wp_enqueue_editor();

		wp_enqueue_script(
			'kcm-admin-trial-bookings',
			plugins_url( 'assets/js/admin-trial-bookings.js', dirname( __DIR__ ) ),
			array( 'jquery', 'wp-tinymce' ),
			'1.0.63',
			true
		);

		wp_localize_script(
			'kcm-admin-trial-bookings',
			'macmTrialBookingsAdmin',
			array(
				'ajaxurl' => admin_url( 'admin-ajax.php' ),
				'nonce'   => wp_create_nonce( 'macm_trial_bookings_admin' ),
			)
		);

		wp_enqueue_style(
			'kcm-admin-trial-bookings',
			plugins_url( 'assets/css/admin-trial-bookings.css', dirname( __DIR__ ) ),
			array(),
			'1.0.63'
		);
	}

	/**
	 * Render admin page
	 *
	 * @since 1.0.61
	 */
	public function render_page() {
		if ( ! current_user_can( 'manage_macm_settings' ) ) {
			wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'martial-arts-club-manager' ) );
		}

		// Get current tab using filter_input for secure access.
		$allowed_tabs = array( 'bookings', 'settings' );

		// Reports tab is premium-only.
		if ( function_exists( 'macm_fs' ) && macm_fs()->can_use_premium_code() ) {
			array_splice( $allowed_tabs, 1, 0, 'reports' );
		}

		$tab_input     = filter_input( INPUT_GET, 'tab', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$tab_sanitized = ! empty( $tab_input ) ? sanitize_key( $tab_input ) : 'bookings';
		$tab           = in_array( $tab_sanitized, $allowed_tabs, true ) ? $tab_sanitized : 'bookings';

		include MACM_PLUGIN_DIR . 'templates/admin/trial-bookings-page.php';
	}

	/**
	 * Mark booking as complete
	 *
	 * @since 1.0.61
	 */
	public function mark_booking_complete() {
		check_ajax_referer( 'macm_trial_bookings_admin', 'nonce' );

		if ( ! current_user_can( 'manage_macm_settings' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'martial-arts-club-manager' ) ) );
		}

		$booking_id = isset( $_POST['booking_id'] ) ? absint( wp_unslash( $_POST['booking_id'] ) ) : 0;

		if ( ! $booking_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid booking ID.', 'martial-arts-club-manager' ) ) );
		}

		global $wpdb;

		// Invalidate booking cache before update.
		wp_cache_delete( 'macm_trial_booking_' . $booking_id, 'macm' );

		$updated = $wpdb->update(
			$wpdb->prefix . 'macm_trial_bookings',
			array(
				'status'       => 'completed',
				'completed_at' => current_time( 'mysql' ),
			),
			array( 'id' => $booking_id ),
			array( '%s', '%s' ),
			array( '%d' )
		);

		if ( false !== $updated ) {
			wp_send_json_success( array( 'message' => __( 'Booking marked as complete.', 'martial-arts-club-manager' ) ) );
		} else {
			wp_send_json_error( array( 'message' => __( 'Failed to update booking.', 'martial-arts-club-manager' ) ) );
		}
	}

	/**
	 * Mark booking as pending
	 *
	 * @since 1.0.76
	 */
	public function mark_booking_pending() {
		check_ajax_referer( 'macm_trial_bookings_admin', 'nonce' );

		if ( ! current_user_can( 'manage_macm_settings' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'martial-arts-club-manager' ) ) );
		}

		$booking_id = isset( $_POST['booking_id'] ) ? absint( wp_unslash( $_POST['booking_id'] ) ) : 0;

		if ( ! $booking_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid booking ID.', 'martial-arts-club-manager' ) ) );
		}

		global $wpdb;

		// Invalidate booking cache before update.
		wp_cache_delete( 'macm_trial_booking_' . $booking_id, 'macm' );

		$updated = $wpdb->update(
			$wpdb->prefix . 'macm_trial_bookings',
			array(
				'status'       => 'pending',
				'completed_at' => null,
			),
			array( 'id' => $booking_id ),
			array( '%s', '%s' ),
			array( '%d' )
		);

		if ( false !== $updated ) {
			wp_send_json_success( array( 'message' => __( 'Booking marked as pending.', 'martial-arts-club-manager' ) ) );
		} else {
			wp_send_json_error( array( 'message' => __( 'Failed to update booking.', 'martial-arts-club-manager' ) ) );
		}
	}

	/**
	 * Save admin note for booking
	 *
	 * @since 1.0.76
	 */
	public function save_admin_note() {
		check_ajax_referer( 'macm_trial_bookings_admin', 'nonce' );

		if ( ! current_user_can( 'manage_macm_settings' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'martial-arts-club-manager' ) ) );
		}

		$booking_id = isset( $_POST['booking_id'] ) ? absint( wp_unslash( $_POST['booking_id'] ) ) : 0;
		$admin_note = isset( $_POST['admin_note'] ) ? sanitize_textarea_field( wp_unslash( $_POST['admin_note'] ) ) : '';

		if ( ! $booking_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid booking ID.', 'martial-arts-club-manager' ) ) );
		}

		global $wpdb;

		// Invalidate booking cache before update.
		wp_cache_delete( 'macm_trial_booking_' . $booking_id, 'macm' );

		$updated = $wpdb->update(
			$wpdb->prefix . 'macm_trial_bookings',
			array(
				'admin_note' => $admin_note,
			),
			array( 'id' => $booking_id ),
			array( '%s' ),
			array( '%d' )
		);

		if ( false !== $updated ) {
			wp_send_json_success( array( 'message' => __( 'Admin note saved successfully.', 'martial-arts-club-manager' ) ) );
		} else {
			wp_send_json_error( array( 'message' => __( 'Failed to save admin note.', 'martial-arts-club-manager' ) ) );
		}
	}

	/**
	 * Send email to booking
	 *
	 * @since 1.0.61
	 */
	public function send_booking_email() {
		check_ajax_referer( 'macm_trial_bookings_admin', 'nonce' );

		if ( ! current_user_can( 'manage_macm_settings' ) ) {
			wp_send_json_error( array( 'message' => __( 'Permission denied.', 'martial-arts-club-manager' ) ) );
		}

		$booking_id = isset( $_POST['booking_id'] ) ? absint( wp_unslash( $_POST['booking_id'] ) ) : 0;

		// Get email body with proper null/empty handling (PHP 8.1+ compatibility).
		$email_body = '';
		if ( isset( $_POST['email_body'] ) && ! empty( $_POST['email_body'] ) ) {
			$email_body = wp_kses_post( wp_unslash( $_POST['email_body'] ) );
			// wp_kses_post can still return null, ensure it's a string.
			$email_body = $email_body ?? '';
		}

		if ( ! $booking_id ) {
			wp_send_json_error( array( 'message' => __( 'Invalid booking ID.', 'martial-arts-club-manager' ) ) );
		}

		if ( empty( $email_body ) ) {
			wp_send_json_error( array( 'message' => __( 'Email body is required.', 'martial-arts-club-manager' ) ) );
		}

		// Get booking details with caching.
		global $wpdb;
		$cache_key = 'macm_trial_booking_' . $booking_id;
		$booking   = wp_cache_get( $cache_key, 'macm' );

		if ( false === $booking ) {
			$booking = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT * FROM {$wpdb->prefix}macm_trial_bookings WHERE id = %d",
					$booking_id
				)
			);

			if ( $booking ) {
				wp_cache_set( $cache_key, $booking, 'macm', 300 );
			}
		}

		if ( ! $booking ) {
			wp_send_json_error( array( 'message' => __( 'Booking not found.', 'martial-arts-club-manager' ) ) );
		}

		// Get gradient colors from settings.
		$gradient_start = get_option( 'macm_email_gradient_start', '#B11226' );
		$gradient_end   = get_option( 'macm_email_gradient_end', '#8F0E1E' );

		// Prepare email - ensure recipient email is valid.
		$to = sanitize_email( trim( $booking->email ) );
		if ( ! is_email( $to ) ) {
			wp_send_json_error( array( 'message' => __( 'Invalid recipient email address.', 'martial-arts-club-manager' ) ) );
		}

		/* translators: %s: site name */
		$subject = sprintf( __( 'Request of trial lesson - %s', 'martial-arts-club-manager' ), get_bloginfo( 'name' ) );
		// Use simple headers to match working trial booking emails - custom From headers can fail on some hosts.
		$headers = array( 'Content-Type: text/html; charset=UTF-8' );

		// Format email with template.
		$email_content = $this->format_email( $booking, $email_body, $gradient_start, $gradient_end );

		// Send email.
		$sent = wp_mail( $to, $subject, $email_content, $headers );

		if ( $sent ) {
			wp_send_json_success( array( 'message' => __( 'Email sent successfully.', 'martial-arts-club-manager' ) ) );
		} else {
			wp_send_json_error( array( 'message' => __( 'Failed to send email.', 'martial-arts-club-manager' ) ) );
		}
	}

	/**
	 * Format email with template
	 *
	 * @since 1.0.61
	 * @param object $booking       Booking object.
	 * @param string $body          Email body.
	 * @param string $gradient_start Gradient start color.
	 * @param string $gradient_end   Gradient end color.
	 * @return string Formatted email HTML.
	 */
	private function format_email( $booking, $body, $gradient_start, $gradient_end ) {
		// Ensure body is never null to prevent PHP 8.1+ deprecation warnings.
		$body = $body ?? '';

		$gradient_style = sprintf( 'background: linear-gradient(135deg, %s 0%%, %s 100%%)', esc_attr( $gradient_start ), esc_attr( $gradient_end ) );
		$site_name      = get_bloginfo( 'name' );
		$site_logo_html = $this->get_site_logo_html();

		$html = '<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; font-family: Arial, sans-serif; background-color: #F4F4F2;">
	<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background-color: #F4F4F2; padding: 20px 0;">
		<tr>
			<td align="center">
				<table role="presentation" cellpadding="0" cellspacing="0" width="600" style="background-color: #ffffff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
					<tr>
						<td style="' . $gradient_style . '; padding: 40px 30px; text-align: center; border-radius: 8px 8px 0 0;">
							' . $site_logo_html . '
							<h1 style="color: #ffffff; margin: 20px 0 0 0; font-size: 24px; font-weight: 600;">Trial Class Request</h1>
						</td>
					</tr>
					<tr>
						<td style="padding: 40px 30px;">
							<div style="font-size: 16px; color: #111827; line-height: 1.6;">
								' . wpautop( $body ) . '
							</div>
							<p style="margin-top: 30px; font-size: 15px; color: #6B7280;">
								Best regards,<br>
								<strong>' . esc_html( $site_name ) . '</strong>
							</p>
						</td>
					</tr>
					<tr>
						<td style="background-color: #F4F4F2; padding: 20px 30px; text-align: center; border-radius: 0 0 8px 8px; border-top: 1px solid #D1D5DB;">
							<p style="margin: 0; font-size: 13px; color: #6B7280;">
								' . esc_html__( 'You are receiving this because you requested a trial class.', 'martial-arts-club-manager' ) . '
							</p>
						</td>
					</tr>
				</table>
			</td>
		</tr>
	</table>
</body>
</html>';

		return $html;
	}

	/**
	 * Get site logo HTML
	 *
	 * @since 1.0.61
	 * @return string Logo HTML.
	 */
	private function get_site_logo_html() {
		$custom_logo_id = get_theme_mod( 'custom_logo' );

		if ( $custom_logo_id ) {
			$logo_url = wp_get_attachment_image_url( $custom_logo_id, 'medium' );
			if ( $logo_url ) {
				return '<img src="' . esc_url( $logo_url ) . '" alt="' . esc_attr( get_bloginfo( 'name' ) ) . '" style="max-width: 200px; height: auto; display: block; margin: 0 auto;" />';
			}
		}

		return '<div style="font-size: 32px; font-weight: 700; color: #ffffff; text-align: center;">' . esc_html( get_bloginfo( 'name' ) ) . '</div>';
	}

	/**
	 * Save settings
	 *
	 * @since 1.0.61
	 */
	public function save_settings() {
		if ( ! current_user_can( 'manage_macm_settings' ) ) {
			wp_die( esc_html__( 'Permission denied.', 'martial-arts-club-manager' ) );
		}

		check_admin_referer( 'macm_trial_booking_settings', 'macm_trial_booking_settings_nonce' );

		$success_message = isset( $_POST['macm_trial_booking_success_message'] ) ? wp_kses_post( wp_unslash( $_POST['macm_trial_booking_success_message'] ) ) : '';

		update_option( 'macm_trial_booking_success_message', $success_message );

		// Set transient for success message (expires in 30 seconds).
		set_transient( 'macm_trial_booking_settings_saved', true, 30 );

		wp_safe_redirect(
			add_query_arg(
				array(
					'page' => 'kcm-trial-bookings',
					'tab'  => 'settings',
				),
				admin_url( 'admin.php' )
			)
		);
		exit;
	}
}

// Initialize.
new MACM_Admin_Trial_Bookings();
