<?php
/**
 * Admin — import CSV codes AppSumo + statistiques.
 *
 * @package Avision
 */

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

/**
 * Sous-menu AVI Control Center.
 */
class Avision_AppSumo_Admin {

	const PAGE_SLUG = 'avi-appsumo-codes';

	/**
	 * @return void
	 */
	public static function init() {
		add_action( 'admin_menu', array( __CLASS__, 'register_menu' ), 30 );
	}

	/**
	 * @return void
	 */
	public static function register_menu() {
		if ( ! class_exists( 'Avision_Control_Center' ) ) {
			return;
		}
		add_submenu_page(
			Avision_Control_Center::PAGE_SLUG,
			__( 'Codes AppSumo', 'avision-dashboard' ),
			__( 'AppSumo', 'avision-dashboard' ),
			'manage_options',
			self::PAGE_SLUG,
			array( __CLASS__, 'render_page' )
		);
	}

	/**
	 * @return array<string, int>
	 */
	private static function get_stats(): array {
		global $wpdb;
		$table = $wpdb->prefix . 'avi_appsumo_codes';
		$out   = array(
			'total'    => 0,
			'claimed'  => 0,
			'unused'   => 0,
			'revoked'  => 0,
			'other'    => 0,
		);
		if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) {
			return $out;
		}
		$rows = $wpdb->get_results(
			"SELECT status, COUNT(*) AS n FROM `{$table}` GROUP BY status",
			ARRAY_A
		);
		if ( ! is_array( $rows ) ) {
			return $out;
		}
		foreach ( $rows as $r ) {
			$st = isset( $r['status'] ) ? (string) $r['status'] : '';
			$n  = isset( $r['n'] ) ? (int) $r['n'] : 0;
			$out['total'] += $n;
			if ( $st === 'claimed' ) {
				$out['claimed'] += $n;
			} elseif ( $st === 'unused' ) {
				$out['unused'] += $n;
			} elseif ( $st === 'revoked' ) {
				$out['revoked'] += $n;
			} else {
				$out['other'] += $n;
			}
		}
		return $out;
	}

	/**
	 * @return void
	 */
	public static function render_page() {
		if ( ! current_user_can( 'manage_options' ) ) {
			return;
		}
		$stats = self::get_stats();
		$nonce = wp_create_nonce( 'avision_appsumo_admin_nonce' );
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Codes AppSumo (LTD)', 'avision-dashboard' ); ?></h1>
			<p><?php esc_html_e( 'Importez un fichier CSV (code,plan_type). Une ligne d’en-tête optionnelle contenant « code » est ignorée.', 'avision-dashboard' ); ?></p>
			<ul style="list-style:disc;margin-left:20px;">
				<li><?php echo esc_html( sprintf( __( 'Total : %d', 'avision-dashboard' ), (int) $stats['total'] ) ); ?></li>
				<li><?php echo esc_html( sprintf( __( 'Utilisés (claimed) : %d', 'avision-dashboard' ), (int) $stats['claimed'] ) ); ?></li>
				<li><?php echo esc_html( sprintf( __( 'Restants (unused) : %d', 'avision-dashboard' ), (int) $stats['unused'] ) ); ?></li>
				<li><?php echo esc_html( sprintf( __( 'Révoqués : %d', 'avision-dashboard' ), (int) $stats['revoked'] ) ); ?></li>
			</ul>
			<hr />
			<h2><?php esc_html_e( 'Importer un CSV', 'avision-dashboard' ); ?></h2>
			<p>
				<input type="file" id="avi-appsumo-csv" accept=".csv,text/csv" />
				<button type="button" class="button button-primary" id="avi-appsumo-import-btn"><?php esc_html_e( 'Importer les codes', 'avision-dashboard' ); ?></button>
			</p>
			<pre id="avi-appsumo-import-result" style="background:#f6f7f7;padding:12px;max-width:640px;white-space:pre-wrap;"></pre>
		</div>
		<script>
		(function(){
			var btn = document.getElementById('avi-appsumo-import-btn');
			var inp = document.getElementById('avi-appsumo-csv');
			var out = document.getElementById('avi-appsumo-import-result');
			if (!btn || !inp) return;
			btn.addEventListener('click', function(){
				if (!inp.files || !inp.files[0]) { if (out) out.textContent = '<?php echo esc_js( __( 'Choisissez un fichier CSV.', 'avision-dashboard' ) ); ?>'; return; }
				var fd = new FormData();
				fd.append('action', 'avision_appsumo_import_csv');
				fd.append('nonce', '<?php echo esc_js( $nonce ); ?>');
				fd.append('csv_file', inp.files[0]);
				btn.disabled = true;
				if (out) out.textContent = '…';
				fetch(ajaxurl, { method: 'POST', body: fd, credentials: 'same-origin' })
					.then(function(r){ return r.json(); })
					.then(function(d){
						if (d.success && d.data) {
							if (out) out.textContent = 'OK — insérés: ' + d.data.inserted + ', doublons: ' + d.data.duplicates + ', erreurs: ' + d.data.errors;
							location.reload();
						} else {
							var c = (d.data && d.data.code) ? d.data.code : JSON.stringify(d);
							if (out) out.textContent = 'Erreur: ' + c;
						}
					})
					.catch(function(e){ if (out) out.textContent = 'network'; })
					.finally(function(){ btn.disabled = false; });
			});
		})();
		</script>
		<?php
	}
}
