<?php
/**
 * License Expiration Reminders
 *
 * Handles automated email reminders for members with expiring licenses
 *
 * @package KarateClubManager
 * @since 1.0.18
 */

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

/**
 * License Reminders Class
 */
class MACM_License_Reminders {

	/**
	 * Cron hook name
	 */
	const CRON_HOOK = 'macm_check_license_expirations';

	/**
	 * Days before expiration to start sending reminders (30 days = 1 month)
	 */
	const REMINDER_START_DAYS = 30;

	/**
	 * Days after expiration to continue sending reminders
	 * Setting to 60 days to give plenty of time for renewal
	 */
	const REMINDER_AFTER_EXPIRATION_DAYS = 60;

	/**
	 * Initialize the class
	 */
	public function __construct() {
		// Schedule cron on plugin activation.
		add_action( 'init', array( $this, 'schedule_cron' ) );

		// Hook into cron event.
		add_action( self::CRON_HOOK, array( $this, 'check_expiring_licenses' ) );
	}

	/**
	 * Schedule the weekly cron job
	 *
	 * This method ensures the cron is scheduled with the correct 'weekly' interval.
	 * If the cron exists with a different interval, it will be rescheduled.
	 *
	 * @since 1.0.19
	 * @since 1.0.36 Added automatic rescheduling if interval is incorrect
	 */
	public function schedule_cron() {
		$scheduled = wp_next_scheduled( self::CRON_HOOK );

		if ( $scheduled ) {
			// Check if the schedule has the correct interval.
			$crons            = _get_cron_array();
			$current_schedule = null;

			foreach ( $crons as $timestamp => $cron ) {
				if ( isset( $cron[ self::CRON_HOOK ] ) ) {
					$event            = reset( $cron[ self::CRON_HOOK ] );
					$current_schedule = isset( $event['schedule'] ) ? $event['schedule'] : null;
					break;
				}
			}

			// If schedule is not 'weekly', reschedule it.
			if ( 'weekly' !== $current_schedule ) {
				wp_unschedule_event( $scheduled, self::CRON_HOOK );
				wp_schedule_event( time(), 'weekly', self::CRON_HOOK );
			}
		} else {
			// Not scheduled at all, create new schedule.
			wp_schedule_event( time(), 'weekly', self::CRON_HOOK );
		}
	}

	/**
	 * Check for expiring licenses and send reminders
	 *
	 * Weekly check for licenses that:
	 * - Will expire within the next 30 days
	 * - Have expired within the last 60 days
	 *
	 * @since 1.0.19
	 * @since 1.0.38 Returns array with results
	 * @return array Array with 'found', 'sent', 'skipped' counts.
	 */
	public function check_expiring_licenses() {
		global $wpdb;

		$today      = wp_date( 'Y-m-d' );
		$start_date = wp_date( 'Y-m-d', strtotime( '-' . self::REMINDER_AFTER_EXPIRATION_DAYS . ' days' ) );
		$end_date   = wp_date( 'Y-m-d', strtotime( '+' . self::REMINDER_START_DAYS . ' days' ) );

		// Get members with licenses that need reminders.
		// Only get active members with licenses expiring soon or already expired.
		$members_needing_reminders = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT m.*, u.user_email, u.display_name
				FROM {$wpdb->prefix}macm_members m
				INNER JOIN {$wpdb->prefix}users u ON m.user_id = u.ID
				WHERE m.license_expiration BETWEEN %s AND %s
				AND m.license_number IS NOT NULL
				AND '' != m.license_number
				AND m.status = 'active'
				ORDER BY m.license_expiration ASC",
				$start_date,
				$end_date
			)
		);

		$sent_count    = 0;
		$skipped_count = 0;

		// Send reminder for each member (with tracking to prevent duplicates).
		foreach ( $members_needing_reminders as $member ) {
			// Check if we already sent a reminder this week.
			if ( $this->was_reminder_sent_this_week( $member->id ) ) {
				++$skipped_count;
				continue;
			}

			// Send the reminder.
			if ( $this->send_reminder( $member ) ) {
				// Track that we sent this reminder.
				$this->track_reminder_sent( $member->id );
				++$sent_count;
			}
		}

		return array(
			'found'   => count( $members_needing_reminders ),
			'sent'    => $sent_count,
			'skipped' => $skipped_count,
		);
	}

	/**
	 * Send license expiration reminder email
	 *
	 * @since 1.0.18
	 * @param object $member Member object with user_email.
	 * @return bool True if email sent, false otherwise.
	 */
	private function send_reminder( $member ) {
		// Get email template from settings.
		$subject_template = get_option( 'macm_license_reminder_subject', $this->get_default_subject() );
		$body_template    = get_option( 'macm_license_reminder_body', $this->get_default_body() );

		// If templates are empty strings, use defaults.
		if ( empty( $subject_template ) ) {
			$subject_template = $this->get_default_subject();
		}
		if ( empty( $body_template ) ) {
			$body_template = $this->get_default_body();
		}

		// Replace placeholders.
		$subject = $this->replace_placeholders( $subject_template, $member );
		$body    = $this->replace_placeholders( $body_template, $member );

		// Prepare email.
		$to      = $member->user_email;
		$headers = array( 'Content-Type: text/html; charset=UTF-8' );

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

		return $sent;
	}

	/**
	 * Replace placeholders in email template
	 *
	 * @since 1.0.18
	 * @since 1.0.41 Added site_logo placeholder
	 * @param string $template Email template with placeholders.
	 * @param object $member   Member object.
	 * @return string Template with replaced values.
	 */
	private function replace_placeholders( $template, $member ) {
		// Get user first and last name.
		$first_name     = get_user_meta( $member->user_id, 'first_name', true );
		$last_name      = get_user_meta( $member->user_id, 'last_name', true );
		$user_full_name = trim( $first_name . ' ' . $last_name );
		if ( empty( $user_full_name ) ) {
			$user_full_name = $member->display_name;
		}

		// Format expiration date.
		$expiration_formatted = date_i18n( get_option( 'date_format' ), strtotime( $member->license_expiration ) );

		// Calculate days until expiration.
		$today      = strtotime( 'today' );
		$expiration = strtotime( $member->license_expiration );
		$days_until = max( 0, floor( ( $expiration - $today ) / DAY_IN_SECONDS ) );

		// Get site logo.
		$site_logo_html = $this->get_site_logo_html();

		// Define placeholders.
		$placeholders = array(
			'{user_name}'             => $user_full_name,
			'{user_first_name}'       => $first_name,
			'{user_last_name}'        => $last_name,
			'{member_name}'           => $member->full_name,
			'{license_number}'        => $member->license_number,
			'{expiration_date}'       => $expiration_formatted,
			'{days_until_expiration}' => $days_until,
			'{site_name}'             => get_bloginfo( 'name' ),
			'{site_url}'              => home_url(),
			'{site_logo}'             => $site_logo_html,
		);

		// Replace all placeholders.
		$output = str_replace(
			array_keys( $placeholders ),
			array_values( $placeholders ),
			$template
		);

		return $output;
	}

	/**
	 * Get site logo HTML for email
	 *
	 * @since 1.0.41
	 * @return string HTML for site logo or empty string.
	 */
	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;" />';
			}
		}

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

	/**
	 * Get default email subject
	 *
	 * @since 1.0.18
	 * @return string Default subject template.
	 */
	private function get_default_subject() {
		return __( 'License Expiration Reminder - {member_name}', 'martial-arts-club-manager' );
	}

	/**
	 * Get default email body
	 *
	 * @since 1.0.18
	 * @since 1.0.41 Updated with professional HTML template
	 * @since 1.0.60 Added gradient color support from settings
	 * @return string Default body template.
	 */
	private function get_default_body() {
		// Get gradient colors from settings (same as bulk emails).
		$gradient_start = get_option( 'macm_email_gradient_start', '#B11226' );
		$gradient_end   = get_option( 'macm_email_gradient_end', '#8F0E1E' );
		$gradient_style = sprintf( 'background: linear-gradient(135deg, %s 0%%, %s 100%%)', esc_attr( $gradient_start ), esc_attr( $gradient_end ) );

		return '<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>' . esc_html__( 'License Expiration Reminder', 'martial-arts-club-manager' ) . '</title>
</head>
<body style="margin: 0; padding: 0; font-family: Arial, Helvetica, 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">
				<!-- Main Container -->
				<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);">

					<!-- Header with Logo -->
					<tr>
						<td style="' . $gradient_style . '; padding: 40px 30px; text-align: center; border-radius: 8px 8px 0 0;">
							{site_logo}
							<h1 style="color: #ffffff; margin: 20px 0 0 0; font-size: 24px; font-weight: 600;">' . esc_html__( 'License Expiration Reminder', 'martial-arts-club-manager' ) . '</h1>
						</td>
					</tr>

					<!-- Content -->
					<tr>
						<td style="padding: 40px 30px;">

							<!-- Greeting -->
							<p style="font-size: 16px; color: #111827; line-height: 1.6; margin: 0 0 20px 0;">
								' . esc_html__( 'Dear', 'martial-arts-club-manager' ) . ' <strong>{user_name}</strong>,
							</p>

							<!-- Main Message -->
							<p style="font-size: 16px; color: #111827; line-height: 1.6; margin: 0 0 25px 0;">
								' . esc_html__( 'This is a friendly reminder that the license for', 'martial-arts-club-manager' ) . ' <strong style="color: #B11226;">{member_name}</strong> ' . esc_html__( 'is due to expire soon.', 'martial-arts-club-manager' ) . '
							</p>

							<!-- License Details Card -->
							<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="background-color: #F4F4F2; border-radius: 6px; padding: 25px; margin: 0 0 25px 0;">
								<tr>
									<td>
										<h2 style="color: #B11226; font-size: 18px; margin: 0 0 15px 0; font-weight: 600;">' . esc_html__( 'License Details', 'martial-arts-club-manager' ) . '</h2>

										<table role="presentation" cellpadding="0" cellspacing="0" width="100%">
											<tr>
												<td style="padding: 8px 0; font-size: 15px; color: #6B7280;">
													<strong style="color: #111827;">' . esc_html__( 'Member:', 'martial-arts-club-manager' ) . '</strong>
												</td>
												<td style="padding: 8px 0; font-size: 15px; color: #111827; text-align: right;">
													{member_name}
												</td>
											</tr>
											<tr>
												<td style="padding: 8px 0; font-size: 15px; color: #6B7280; border-top: 1px solid #D1D5DB;">
													<strong style="color: #111827;">' . esc_html__( 'License Number:', 'martial-arts-club-manager' ) . '</strong>
												</td>
												<td style="padding: 8px 0; font-size: 15px; color: #111827; text-align: right; border-top: 1px solid #D1D5DB;">
													{license_number}
												</td>
											</tr>
											<tr>
												<td style="padding: 8px 0; font-size: 15px; color: #6B7280; border-top: 1px solid #D1D5DB;">
													<strong style="color: #111827;">' . esc_html__( 'Expiration Date:', 'martial-arts-club-manager' ) . '</strong>
												</td>
												<td style="padding: 8px 0; font-size: 15px; color: #d32f2f; text-align: right; font-weight: 600; border-top: 1px solid #D1D5DB;">
													{expiration_date}
												</td>
											</tr>
											<tr>
												<td style="padding: 8px 0; font-size: 15px; color: #6B7280; border-top: 1px solid #D1D5DB;">
													<strong style="color: #111827;">' . esc_html__( 'Days Until Expiration:', 'martial-arts-club-manager' ) . '</strong>
												</td>
												<td style="padding: 8px 0; font-size: 15px; color: #d32f2f; text-align: right; font-weight: 600; border-top: 1px solid #D1D5DB;">
													{days_until_expiration}
												</td>
											</tr>
										</table>
									</td>
								</tr>
							</table>

							<!-- Call to Action -->
							<table role="presentation" cellpadding="0" cellspacing="0" width="100%" style="margin: 0 0 25px 0;">
								<tr>
									<td style="background-color: #fff3cd; border-left: 4px solid #ffc107; padding: 15px 20px; border-radius: 4px;">
										<p style="margin: 0; font-size: 15px; color: #856404; line-height: 1.5;">
											<strong>' . esc_html__( 'Action Required:', 'martial-arts-club-manager' ) . '</strong><br>
											' . esc_html__( 'Please renew this license before it expires to ensure uninterrupted access to club activities.', 'martial-arts-club-manager' ) . '
										</p>
									</td>
								</tr>
							</table>

							<!-- Footer Message -->
							<p style="font-size: 15px; color: #6B7280; line-height: 1.6; margin: 0 0 20px 0;">
								' . esc_html__( 'If you have any questions or need assistance with the renewal process, please don\'t hesitate to contact us.', 'martial-arts-club-manager' ) . '
							</p>

							<!-- Signature -->
							<p style="font-size: 15px; color: #111827; line-height: 1.6; margin: 0;">
								' . esc_html__( 'Best regards,', 'martial-arts-club-manager' ) . '<br>
								<strong>{site_name}</strong><br>
								<a href="{site_url}" style="color: #B11226; text-decoration: none;">{site_url}</a>
							</p>

						</td>
					</tr>

					<!-- Footer -->
					<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; line-height: 1.5;">
								' . esc_html__( 'This is an automated reminder. Please do not reply to this email.', 'martial-arts-club-manager' ) . '<br>
								' . esc_html__( 'You are receiving this because you are registered with', 'martial-arts-club-manager' ) . ' {site_name}
							</p>
						</td>
					</tr>

				</table>
			</td>
		</tr>
	</table>
</body>
</html>';
	}

	/**
	 * Get available placeholders
	 *
	 * @since 1.0.18
	 * @since 1.0.41 Added site_logo placeholder
	 * @return array Array of placeholder => description.
	 */
	public static function get_available_placeholders() {
		return array(
			'{user_name}'             => __( 'User full name (first + last name)', 'martial-arts-club-manager' ),
			'{user_first_name}'       => __( 'User first name', 'martial-arts-club-manager' ),
			'{user_last_name}'        => __( 'User last name', 'martial-arts-club-manager' ),
			'{member_name}'           => __( 'Member full name', 'martial-arts-club-manager' ),
			'{license_number}'        => __( 'License number', 'martial-arts-club-manager' ),
			'{expiration_date}'       => __( 'License expiration date (formatted)', 'martial-arts-club-manager' ),
			'{days_until_expiration}' => __( 'Number of days until expiration', 'martial-arts-club-manager' ),
			'{site_name}'             => __( 'Your website name', 'martial-arts-club-manager' ),
			'{site_url}'              => __( 'Your website URL', 'martial-arts-club-manager' ),
			'{site_logo}'             => __( 'Your website logo (automatically added from Customizer)', 'martial-arts-club-manager' ),
		);
	}

	/**
	 * Check if a reminder was sent to this member in the last 7 days
	 *
	 * @since 1.0.19
	 * @param int $member_id Member ID.
	 * @return bool True if reminder was sent this week, false otherwise.
	 */
	private function was_reminder_sent_this_week( $member_id ) {
		$transient_key = 'macm_reminder_sent_' . $member_id;
		$last_sent     = get_transient( $transient_key );

		// If transient exists, a reminder was sent within the last 7 days.
		return false !== $last_sent;
	}

	/**
	 * Track that a reminder was sent to this member
	 *
	 * @since 1.0.19
	 * @param int $member_id Member ID.
	 */
	private function track_reminder_sent( $member_id ) {
		$transient_key = 'macm_reminder_sent_' . $member_id;
		// Store the current timestamp for 7 days.
		set_transient( $transient_key, time(), 7 * DAY_IN_SECONDS );
	}

	/**
	 * Unschedule cron on plugin deactivation
	 *
	 * @since 1.0.18
	 */
	public static function unschedule_cron() {
		$timestamp = wp_next_scheduled( self::CRON_HOOK );
		if ( $timestamp ) {
			wp_unschedule_event( $timestamp, self::CRON_HOOK );
		}
	}
}

// Initialize - PREMIUM feature.
// This block will be removed from the free version by Freemius.
if ( function_exists( 'macm_fs' ) && macm_fs()->is__premium_only() ) {
	if ( macm_fs()->can_use_premium_code() ) {
		new MACM_License_Reminders();
	}
}
