<?php
/**
 * Sprint 11 — emails Brevo : colonnes profil re-engagement + hook niveaux.
 *
 * @package Avision
 */

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

/**
 * Colonnes optionnelles sur avi_saas_profiles pour le CRON re-engagement.
 *
 * @return void
 */
function avi_s11_email_profile_columns_migrate(): void {
	if ( ! isset( $GLOBALS['wpdb'] ) || ! is_object( $GLOBALS['wpdb'] ) ) {
		return;
	}
	if ( get_option( 'avi_s11_profile_email_cols_v1', '' ) === '1' ) {
		return;
	}
	global $wpdb;
	$profiles = $wpdb->prefix . 'avi_saas_profiles';
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $profiles ) ) !== $profiles ) {
		return;
	}
	$cols = array(
		'last_login_at'     => "ADD COLUMN `last_login_at` DATETIME NULL COMMENT 'Dernière activité connue (optionnel)'",
		'reengage_sent_at'  => "ADD COLUMN `reengage_sent_at` DATETIME NULL COMMENT 'Dernier email re-engagement Brevo'",
	);
	foreach ( $cols as $name => $ddl ) {
		if ( $wpdb->get_var( $wpdb->prepare( "SHOW COLUMNS FROM `{$profiles}` LIKE %s", $name ) ) !== $name ) {
			// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
			$wpdb->query( "ALTER TABLE `{$profiles}` {$ddl}" );
		}
	}
	update_option( 'avi_s11_profile_email_cols_v1', '1', false );
}

/**
 * Envoie l’email Brevo associé à la validation d’un niveau clé (3,4,12,15,18,20,21).
 *
 * @param int $user_id   ID WordPress (cf. class-ajax-router handle_validate_level).
 * @param int $new_level Niveau validé.
 * @return void
 */
function avi_send_level_email( int $user_id, int $new_level ): void {
	if ( $user_id <= 0 || ! class_exists( '\Avision\Avision_Email_Manager' ) ) {
		return;
	}
	$level_map = array(
		3  => \Avision\Avision_Email_Manager::TYPE_LEVEL_3,
		4  => \Avision\Avision_Email_Manager::TYPE_LEVEL_4_GUARDIAN,
		12 => \Avision\Avision_Email_Manager::TYPE_LEVEL_12,
		15 => \Avision\Avision_Email_Manager::TYPE_LEVEL_15,
		18 => \Avision\Avision_Email_Manager::TYPE_LEVEL_18,
		20 => \Avision\Avision_Email_Manager::TYPE_LEVEL_20,
		21 => \Avision\Avision_Email_Manager::TYPE_LEVEL_21,
	);
	$type = $level_map[ $new_level ] ?? null;
	if ( ! $type ) {
		return;
	}
	$user = function_exists( 'get_userdata' ) ? get_userdata( $user_id ) : null;
	global $wpdb;
	$profile = $wpdb->get_row(
		$wpdb->prepare(
			"SELECT business_name, score FROM {$wpdb->prefix}avi_saas_profiles WHERE user_id = %d",
			$user_id
		),
		ARRAY_A
	);
	\Avision\Avision_Email_Manager::send_avi_email(
		$user_id,
		$type,
		array(
			'recipient_email' => $user && ! empty( $user->user_email ) ? (string) $user->user_email : '',
			'user_name'       => $user ? (string) $user->display_name : '',
			'level'           => $new_level,
			'dashboard_url'   => trailingslashit( home_url( '/premium-dashboard/' ) ),
			'business_name'   => $profile ? ( $profile['business_name'] ?? '' ) : '',
			'score'           => $profile ? (string) ( $profile['score'] ?? 0 ) : '0',
		)
	);
	if ( function_exists( 'error_log' ) ) {
		error_log( '[AVI-EMAIL] Niveau ' . $new_level . ' email envoyé user=' . $user_id );
	}
}

add_action( 'plugins_loaded', 'avi_s11_email_profile_columns_migrate', 8 );
add_action( 'avi_level_validated', 'avi_send_level_email', 25, 2 );

/**
 * Email Brevo — association approuvée (appel admin / workflow).
 *
 * @param int $nonprofit_id Ligne `avi_nonprofit_orgs.id`.
 * @return void
 */
function avi_send_nonprofit_approved_email( int $nonprofit_id ): void {
	global $wpdb;
	$nonprofit_id = (int) $nonprofit_id;
	if ( $nonprofit_id <= 0 || ! class_exists( '\Avision\Avision_Email_Manager' ) ) {
		return;
	}
	$table = $wpdb->prefix . 'avi_nonprofit_orgs';
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
		return;
	}
	$org = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM `{$table}` WHERE id = %d", $nonprofit_id ), ARRAY_A );
	if ( ! is_array( $org ) ) {
		return;
	}
	$org_email = '';
	if ( isset( $org['email'] ) && is_email( (string) $org['email'] ) ) {
		$org_email = sanitize_email( (string) $org['email'] );
	}
	if ( $org_email === '' ) {
		return;
	}
	$org_name = isset( $org['org_name'] ) ? (string) $org['org_name'] : ( isset( $org['name'] ) ? (string) $org['name'] : '' );
	$contact  = isset( $org['contact_name'] ) ? (string) $org['contact_name'] : $org_name;
	$ref      = isset( $org['referral_code'] ) ? (string) $org['referral_code'] : '';
	$payout   = isset( $org['payout_method'] ) ? (string) $org['payout_method'] : 'bank transfer';
	$wp_user  = get_user_by( 'email', $org_email );
	$user_id  = ( $wp_user instanceof \WP_User ) ? (int) $wp_user->ID : 0;
	\Avision\Avision_Email_Manager::send_avi_email(
		$user_id,
		\Avision\Avision_Email_Manager::TYPE_NONPROFIT_APPROVED,
		array(
			'recipient_email' => $org_email,
			'contact_name'    => $contact,
			'org_name'        => $org_name !== '' ? $org_name : $contact,
			'referral_code'   => $ref,
			'payout_method'   => $payout,
			'dashboard_url'   => trailingslashit( home_url( '/dashboard/' ) ),
		)
	);
}

/**
 * Rapport mensuel dons — email interne Brevo.
 *
 * @param array<string,mixed> $data Paramètres template (clés UPPER_SNAKE ou snake pour mapping).
 * @return void
 */
function avi_send_donation_monthly_email( array $data ): void {
	if ( ! class_exists( '\Avision\Avision_Email_Manager' ) ) {
		return;
	}
	$internal = 'contact@avision.org';
	\Avision\Avision_Email_Manager::send_avi_email(
		0,
		\Avision\Avision_Email_Manager::TYPE_DONATION_MONTHLY,
		array_merge(
			$data,
			array( 'recipient_email' => $internal )
		)
	);
}

/**
 * Avertissement conformité association (CRON trimestriel).
 *
 * @param int $nonprofit_id Ligne `avi_nonprofit_orgs.id`.
 * @return void
 */
function avi_send_nonprofit_warning_email( int $nonprofit_id ): void {
	global $wpdb;
	$nonprofit_id = (int) $nonprofit_id;
	if ( $nonprofit_id <= 0 || ! class_exists( '\Avision\Avision_Email_Manager' ) ) {
		return;
	}
	$table = $wpdb->prefix . 'avi_nonprofit_orgs';
	if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
		return;
	}
	$org = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM `{$table}` WHERE id = %d", $nonprofit_id ), ARRAY_A );
	if ( ! is_array( $org ) ) {
		return;
	}
	$org_email = isset( $org['email'] ) && is_email( (string) $org['email'] ) ? sanitize_email( (string) $org['email'] ) : '';
	if ( $org_email === '' ) {
		return;
	}
	$org_name        = isset( $org['org_name'] ) ? (string) $org['org_name'] : ( isset( $org['name'] ) ? (string) $org['name'] : '' );
	$active_members  = isset( $org['active_referrals'] ) ? (string) $org['active_referrals'] : ( isset( $org['active_members'] ) ? (string) $org['active_members'] : '0' );
	$wp_user         = get_user_by( 'email', $org_email );
	$user_id         = ( $wp_user instanceof \WP_User ) ? (int) $wp_user->ID : 0;
	\Avision\Avision_Email_Manager::send_avi_email(
		$user_id,
		\Avision\Avision_Email_Manager::TYPE_NONPROFIT_WARNING,
		array(
			'recipient_email' => $org_email,
			'contact_name'    => $org_name,
			'org_name'        => $org_name,
			'active_members'  => $active_members,
			'deadline'        => gmdate( 'F j, Y', strtotime( '+30 days' ) ),
		)
	);
}

/**
 * Confirmation désinscription marketing (après enregistrement feedback).
 *
 * @param int $user_id ID WordPress.
 * @return bool
 */
function avi_s11_send_unsubscribe_confirm_email( int $user_id ): bool {
	$user_id = (int) $user_id;
	if ( $user_id <= 0 || ! class_exists( '\Avision\Avision_Email_Manager' ) ) {
		return false;
	}
	$ud = get_userdata( $user_id );
	if ( ! $ud instanceof \WP_User ) {
		return false;
	}
	return \Avision\Avision_Email_Manager::send_avi_email(
		$user_id,
		\Avision\Avision_Email_Manager::TYPE_UNSUBSCRIBE_CONFIRM,
		array(
			'user_name'       => (string) $ud->display_name,
			'dashboard_url'   => trailingslashit( home_url( '/premium-dashboard/' ) ),
			'resubscribe_url' => trailingslashit( home_url( '/dashboard/?resubscribe=1' ) ),
		)
	);
}
