<?php
/**
 * Admin — Founding Sponsors (Ko-fi).
 *
 * @package Avision
 */

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

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

	const PAGE_SLUG = 'avi-founding-sponsors';

	/**
	 * @return void
	 */
	public static function init() {
		add_action( 'admin_menu', array( __CLASS__, 'register_menu' ), 30 );
		add_action( 'wp_ajax_avision_add_founding_sponsor', array( __CLASS__, 'ajax_add' ) );
		add_action( 'wp_ajax_avision_update_founding_sponsor', array( __CLASS__, 'ajax_update' ) );
		add_action( 'wp_ajax_avision_delete_founding_sponsor', array( __CLASS__, 'ajax_delete' ) );
		add_action( 'wp_ajax_avision_toggle_founding_sponsor', array( __CLASS__, 'ajax_toggle' ) );
	}

	/**
	 * @return void
	 */
	public static function register_menu() {
		if ( ! class_exists( 'Avision_Control_Center' ) ) {
			return;
		}
		add_submenu_page(
			Avision_Control_Center::PAGE_SLUG,
			'Founding Sponsors',
			'🏆 Founding Sponsors',
			'manage_options',
			self::PAGE_SLUG,
			array( __CLASS__, 'render_page' )
		);
	}

	/**
	 * @return string
	 */
	private static function table_name() {
		global $wpdb;
		return $wpdb->prefix . 'avi_founding_sponsors';
	}

	/**
	 * @return void
	 */
	public static function render_page() {
		global $wpdb;
		$table = self::table_name();

		$total    = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table}" );
		$active   = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE active = 1" );
		$founding = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE tier = 'founding_member'" );
		$raised   = (int) $wpdb->get_var( "SELECT SUM(amount) FROM {$table} WHERE active = 1" );

		$sponsors = $wpdb->get_results(
			"SELECT * FROM {$table} ORDER BY display_order ASC, created_at DESC"
		);

		$tier_labels = array(
			'founding_member' => '🏆 Founding Member',
			'elite_sponsor'   => '💎 Elite Sponsor',
			'growth_partner'  => '🌱 Growth Partner',
			'early_backer'    => '⚡ Early Backer',
			'supporter'       => '☕ Supporter',
		);
		$tier_colors = array(
			'founding_member' => '#F5A623',
			'elite_sponsor'   => '#4A90D9',
			'growth_partner'  => '#27AE60',
			'early_backer'    => '#E67E22',
			'supporter'       => '#95A5A6',
		);

		$kpis = array(
			array(
				'label' => 'Total Sponsors',
				'value' => (string) $total,
				'icon'  => '👥',
			),
			array(
				'label' => 'Active',
				'value' => (string) $active,
				'icon'  => '✅',
			),
			array(
				'label' => 'Founding Members',
				'value' => (string) $founding,
				'icon'  => '🏆',
			),
			array(
				'label' => 'Total Raised',
				'value' => '$' . $raised,
				'icon'  => '💰',
			),
		);
		?>
		<div class="wrap afs-admin-wrap">
		<h1 style="color:#0A1628;font-weight:700;">🏆 Founding Sponsors</h1>

		<div class="afs-kpi-row" style="display:grid;grid-template-columns:repeat(4,1fr);gap:16px;margin:20px 0 30px;">
			<?php foreach ( $kpis as $k ) : ?>
			<div style="background:#0A1628;color:#fff;border-radius:12px;padding:20px;text-align:center;">
				<div style="font-size:1.8rem;"><?php echo esc_html( $k['icon'] ); ?></div>
				<div style="font-size:1.6rem;font-weight:700;color:#F5A623;margin:8px 0 4px;">
					<?php echo esc_html( $k['value'] ); ?>
				</div>
				<div style="font-size:0.85rem;color:#B0BEC5;"><?php echo esc_html( $k['label'] ); ?></div>
			</div>
			<?php endforeach; ?>
		</div>

		<div style="background:#fff;border-radius:12px;padding:24px;margin-bottom:30px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
			<h2 style="margin-top:0;color:#0A1628;">Add Sponsor</h2>
			<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;">
				<div>
					<label for="afs-name">Name *</label><br>
					<input type="text" id="afs-name" style="width:100%;padding:8px;margin-top:4px;">
				</div>
				<div>
					<label for="afs-tier">Tier *</label><br>
					<select id="afs-tier" style="width:100%;padding:8px;margin-top:4px;">
						<?php foreach ( $tier_labels as $tier_key => $tier_label ) : ?>
						<option value="<?php echo esc_attr( $tier_key ); ?>"><?php echo esc_html( $tier_label ); ?></option>
						<?php endforeach; ?>
					</select>
				</div>
				<div>
					<label for="afs-amount">Amount ($) *</label><br>
					<input type="number" id="afs-amount" min="0" style="width:100%;padding:8px;margin-top:4px;">
				</div>
				<div>
					<label for="afs-country">Country</label><br>
					<input type="text" id="afs-country" style="width:100%;padding:8px;margin-top:4px;">
				</div>
				<div>
					<label for="afs-email">Ko-fi Email (private)</label><br>
					<input type="email" id="afs-email" style="width:100%;padding:8px;margin-top:4px;">
				</div>
				<div>
					<label for="afs-order">Display Order</label><br>
					<input type="number" id="afs-order" value="0" min="0" style="width:100%;padding:8px;margin-top:4px;">
				</div>
			</div>
			<div style="margin-top:16px;">
				<button type="button" id="afs-add-btn" style="background:#F5A623;color:#0A1628;border:none;padding:10px 24px;border-radius:8px;font-weight:700;cursor:pointer;font-size:0.95rem;">
					+ Add Sponsor
				</button>
				<span id="afs-add-msg" style="margin-left:12px;font-weight:600;"></span>
			</div>
		</div>

		<div style="background:#fff;border-radius:12px;padding:24px;box-shadow:0 2px 8px rgba(0,0,0,0.06);">
			<h2 style="margin-top:0;color:#0A1628;">Sponsors (<?php echo (int) $total; ?>)</h2>
			<table class="wp-list-table widefat fixed striped" style="border-radius:8px;overflow:hidden;">
				<thead>
					<tr>
						<th>Name</th>
						<th>Tier</th>
						<th>Amount</th>
						<th>Country</th>
						<th>Order</th>
						<th>Active</th>
						<th>Actions</th>
					</tr>
				</thead>
				<tbody>
				<?php if ( empty( $sponsors ) ) : ?>
					<tr>
						<td colspan="7" style="text-align:center;padding:30px;color:#7A8A9A;">
							No sponsors yet — be the first! 🏆
						</td>
					</tr>
				<?php else : ?>
					<?php
					foreach ( $sponsors as $sp ) {
						$tc = isset( $tier_colors[ $sp->tier ] ) ? $tier_colors[ $sp->tier ] : '#95A5A6';
						$tl = isset( $tier_labels[ $sp->tier ] ) ? $tier_labels[ $sp->tier ] : (string) $sp->tier;
						?>
					<tr id="afs-row-<?php echo (int) $sp->id; ?>">
						<td style="font-weight:600;"><?php echo esc_html( $sp->name ); ?></td>
						<td>
							<span style="background:<?php echo esc_attr( $tc ); ?>22;color:<?php echo esc_attr( $tc ); ?>;padding:3px 10px;border-radius:12px;font-size:0.8rem;font-weight:600;">
								<?php echo esc_html( $tl ); ?>
							</span>
						</td>
						<td>$<?php echo (int) $sp->amount; ?></td>
						<td><?php echo esc_html( $sp->country ? $sp->country : '—' ); ?></td>
						<td><?php echo (int) $sp->display_order; ?></td>
						<td>
							<span style="color:<?php echo $sp->active ? '#27AE60' : '#E74C3C'; ?>;font-weight:700;">
								<?php echo $sp->active ? '✅' : '❌'; ?>
							</span>
						</td>
						<td>
							<button type="button" class="afs-toggle-btn" data-id="<?php echo (int) $sp->id; ?>" data-active="<?php echo (int) $sp->active; ?>" style="margin-right:6px;cursor:pointer;padding:4px 10px;border-radius:6px;border:1px solid #ddd;background:#f9f9f9;">
								<?php echo $sp->active ? 'Deactivate' : 'Activate'; ?>
							</button>
							<button type="button" class="afs-delete-btn" data-id="<?php echo (int) $sp->id; ?>" style="cursor:pointer;padding:4px 10px;border-radius:6px;border:1px solid #E74C3C;background:#FEF0F0;color:#E74C3C;">
								Delete
							</button>
						</td>
					</tr>
						<?php
					}
					?>
				<?php endif; ?>
				</tbody>
			</table>
		</div>

		</div>

		<script>
		jQuery(document).ready(function($) {
			var nonce = '<?php echo esc_js( wp_create_nonce( 'avision_admin_nonce' ) ); ?>';

			$('#afs-add-btn').on('click', function() {
				var name = $('#afs-name').val().trim();
				var amount = $('#afs-amount').val();
				if (!name || !amount) {
					$('#afs-add-msg').css('color','#E74C3C').text('Name and amount are required.');
					return;
				}
				$.post(ajaxurl, {
					action: 'avision_add_founding_sponsor',
					nonce: nonce,
					name: name,
					tier: $('#afs-tier').val(),
					amount: amount,
					country: $('#afs-country').val(),
					kofi_email: $('#afs-email').val(),
					display_order: $('#afs-order').val()
				}, function(r) {
					if (r.success) {
						$('#afs-add-msg').css('color','#27AE60').text('✅ Sponsor added!');
						setTimeout(function(){ location.reload(); }, 1000);
					} else {
						$('#afs-add-msg').css('color','#E74C3C').text('Error: ' + r.data);
					}
				});
			});

			$(document).on('click', '.afs-toggle-btn', function() {
				var id = $(this).data('id');
				var active = $(this).data('active');
				$.post(ajaxurl, {
					action: 'avision_toggle_founding_sponsor',
					nonce: nonce,
					id: id,
					active: active ? 0 : 1
				}, function(r) {
					if (r.success) { location.reload(); }
				});
			});

			$(document).on('click', '.afs-delete-btn', function() {
				if (!confirm('Delete this sponsor?')) return;
				var id = $(this).data('id');
				$.post(ajaxurl, {
					action: 'avision_delete_founding_sponsor',
					nonce: nonce,
					id: id
				}, function(r) {
					if (r.success) {
						$('#afs-row-' + id).fadeOut();
					}
				});
			});
		});
		</script>
		<?php
	}

	/**
	 * @return void
	 */
	public static function ajax_add() {
		check_ajax_referer( 'avision_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Unauthorized' );
		}
		global $wpdb;
		$table = self::table_name();
		$valid_tiers = array(
			'founding_member',
			'elite_sponsor',
			'growth_partner',
			'early_backer',
			'supporter',
		);
		$tier = isset( $_POST['tier'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['tier'] ) ) : '';
		if ( ! in_array( $tier, $valid_tiers, true ) ) {
			wp_send_json_error( 'Invalid tier' );
		}
		$inserted = $wpdb->insert(
			$table,
			array(
				'name'          => isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['name'] ) ) : '',
				'tier'          => $tier,
				'amount'        => isset( $_POST['amount'] ) ? absint( wp_unslash( $_POST['amount'] ) ) : 0,
				'country'       => isset( $_POST['country'] ) ? sanitize_text_field( wp_unslash( (string) $_POST['country'] ) ) : '',
				'kofi_email'    => isset( $_POST['kofi_email'] ) ? sanitize_email( wp_unslash( (string) $_POST['kofi_email'] ) ) : '',
				'display_order' => isset( $_POST['display_order'] ) ? absint( wp_unslash( $_POST['display_order'] ) ) : 0,
				'active'        => 1,
			),
			array( '%s', '%s', '%d', '%s', '%s', '%d', '%d' )
		);
		if ( $inserted ) {
			wp_send_json_success( 'added' );
		}
		wp_send_json_error( 'DB error' );
	}

	/**
	 * @return void
	 */
	public static function ajax_update() {
		check_ajax_referer( 'avision_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Unauthorized' );
		}
		wp_send_json_error( 'Not implemented' );
	}

	/**
	 * @return void
	 */
	public static function ajax_toggle() {
		check_ajax_referer( 'avision_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Unauthorized' );
		}
		global $wpdb;
		$table = self::table_name();
		$wpdb->update(
			$table,
			array( 'active' => isset( $_POST['active'] ) ? absint( wp_unslash( $_POST['active'] ) ) : 0 ),
			array( 'id' => isset( $_POST['id'] ) ? absint( wp_unslash( $_POST['id'] ) ) : 0 ),
			array( '%d' ),
			array( '%d' )
		);
		wp_send_json_success( 'toggled' );
	}

	/**
	 * @return void
	 */
	public static function ajax_delete() {
		check_ajax_referer( 'avision_admin_nonce', 'nonce' );
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( 'Unauthorized' );
		}
		global $wpdb;
		$table = self::table_name();
		$wpdb->delete(
			$table,
			array( 'id' => isset( $_POST['id'] ) ? absint( wp_unslash( $_POST['id'] ) ) : 0 ),
			array( '%d' )
		);
		wp_send_json_success( 'deleted' );
	}
}

Avision_Founding_Sponsors_Admin::init();
