<?php
/**
 * Members screen: list, add and edit members with their SEPA mandate.
 *
 * IBANs are shown masked everywhere. The full number exists only inside the
 * encrypted column and inside generated SEPA files.
 */

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

class BSTEW_Admin_Members {

	public static function init() {
		add_action( 'admin_post_bstew_save_member', array( __CLASS__, 'handle_save' ) );
		add_action( 'admin_post_bstew_delete_member', array( __CLASS__, 'handle_delete' ) );
		add_action( 'admin_post_bstew_statement', array( __CLASS__, 'handle_statement' ) );
	}

	public static function handle_save() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( 'forbidden' );
		}
		check_admin_referer( 'bstew_member' );

		$id   = isset( $_POST['member_id'] ) ? (int) $_POST['member_id'] : 0;
		$data = array_map( 'wp_unslash', $_POST ); // phpcs:ignore -- fields sanitized in save_member().

		$iban = strtoupper( preg_replace( '/\s+/', '', $data['iban'] ?? '' ) );
		if ( '' !== $iban && ! bstew_iban_valid( $iban ) ) {
			wp_safe_redirect( add_query_arg( array( 'page' => 'beitrag-steward', 'bstew_msg' => 'bad_iban' ), admin_url( 'admin.php' ) ) );
			exit;
		}

		BSTEW_Store::save_member( $data, $id );
		wp_safe_redirect( add_query_arg( array( 'page' => 'beitrag-steward', 'bstew_msg' => 'saved' ), admin_url( 'admin.php' ) ) );
		exit;
	}

	public static function handle_delete() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( 'forbidden' );
		}
		$id = isset( $_GET['id'] ) ? (int) $_GET['id'] : 0;
		check_admin_referer( 'bstew_delete_' . $id );
		BSTEW_Store::delete_member( $id );
		wp_safe_redirect( add_query_arg( array( 'page' => 'beitrag-steward', 'bstew_msg' => 'deleted' ), admin_url( 'admin.php' ) ) );
		exit;
	}

	public static function handle_statement() {
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_die( 'forbidden' );
		}
		$id = isset( $_GET['id'] ) ? (int) $_GET['id'] : 0;
		check_admin_referer( 'bstew_statement_' . $id );
		$member = BSTEW_Store::get_member( $id );
		if ( ! $member ) {
			wp_die( esc_html__( 'Member not found.', 'beitrag-steward' ) );
		}
		$year = gmdate( 'Y' );
		$file = BSTEW_Pdf::render_statement( $member, $year, number_format( (float) $member->amount, 2, ',', '.' ) );
		if ( '' === $file ) {
			wp_die( esc_html__( 'PDF could not be generated.', 'beitrag-steward' ) );
		}
		$path = trailingslashit( bstew_storage_dir() ) . $file;
		header( 'Content-Type: application/pdf' );
		header( 'Content-Disposition: attachment; filename="' . basename( $file ) . '"' );
		header( 'Content-Length: ' . filesize( $path ) );
		readfile( $path ); // phpcs:ignore
		exit;
	}

	public static function render() {
		$edit = null;
		if ( isset( $_GET['edit'] ) ) { // phpcs:ignore
			$edit = BSTEW_Store::get_member( (int) $_GET['edit'] ); // phpcs:ignore
		}
		$members = BSTEW_Store::all_members();
		$msg     = isset( $_GET['bstew_msg'] ) ? sanitize_key( $_GET['bstew_msg'] ) : ''; // phpcs:ignore
		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'Members', 'beitrag-steward' ); ?></h1>

			<?php if ( 'saved' === $msg ) : ?>
				<div class="notice notice-success"><p><?php esc_html_e( 'Member saved.', 'beitrag-steward' ); ?></p></div>
			<?php elseif ( 'deleted' === $msg ) : ?>
				<div class="notice notice-success"><p><?php esc_html_e( 'Member deleted.', 'beitrag-steward' ); ?></p></div>
			<?php elseif ( 'bad_iban' === $msg ) : ?>
				<div class="notice notice-error"><p><?php esc_html_e( 'That IBAN fails its check digits — the member was not saved. A single wrong IBAN makes the bank reject the whole collection.', 'beitrag-steward' ); ?></p></div>
			<?php endif; ?>

			<table class="widefat striped" style="max-width:1100px">
				<thead><tr>
					<th><?php esc_html_e( 'Name', 'beitrag-steward' ); ?></th>
					<th><?php esc_html_e( 'IBAN', 'beitrag-steward' ); ?></th>
					<th><?php esc_html_e( 'Mandate', 'beitrag-steward' ); ?></th>
					<th><?php esc_html_e( 'Sequence', 'beitrag-steward' ); ?></th>
					<th><?php esc_html_e( 'Fee', 'beitrag-steward' ); ?></th>
					<th><?php esc_html_e( 'Active', 'beitrag-steward' ); ?></th>
					<th></th>
				</tr></thead>
				<tbody>
				<?php if ( empty( $members ) ) : ?>
					<tr><td colspan="7"><?php esc_html_e( 'No members yet. Add the first one below.', 'beitrag-steward' ); ?></td></tr>
				<?php endif; ?>
				<?php foreach ( $members as $m ) : ?>
					<tr>
						<td><?php echo esc_html( $m->name ); ?><?php echo '' !== $m->member_no ? ' <span style="color:#777">(' . esc_html( $m->member_no ) . ')</span>' : ''; ?></td>
						<td><code><?php echo esc_html( $m->iban_last4 ? '•••• ' . $m->iban_last4 : '—' ); ?></code></td>
						<td><?php echo esc_html( $m->mandate_ref ?: '—' ); ?><?php echo $m->mandate_date ? ' <span style="color:#777">(' . esc_html( $m->mandate_date ) . ')</span>' : ''; ?></td>
						<td><?php echo esc_html( $m->sequence_type ); ?></td>
						<td><?php echo esc_html( number_format( (float) $m->amount, 2, ',', '.' ) ); ?> €</td>
						<td><?php echo $m->active ? '✓' : '—'; ?></td>
						<td>
							<a href="<?php echo esc_url( add_query_arg( array( 'page' => 'beitrag-steward', 'edit' => $m->id ), admin_url( 'admin.php' ) ) ); ?>"><?php esc_html_e( 'Edit', 'beitrag-steward' ); ?></a> ·
							<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=bstew_statement&id=' . $m->id ), 'bstew_statement_' . $m->id ) ); ?>"><?php esc_html_e( 'Statement PDF', 'beitrag-steward' ); ?></a> ·
							<a style="color:#b32d2e" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=bstew_delete_member&id=' . $m->id ), 'bstew_delete_' . $m->id ) ); ?>"><?php esc_html_e( 'Delete', 'beitrag-steward' ); ?></a>
						</td>
					</tr>
				<?php endforeach; ?>
				</tbody>
			</table>

			<h2 style="margin-top:32px"><?php echo $edit ? esc_html__( 'Edit member', 'beitrag-steward' ) : esc_html__( 'Add member', 'beitrag-steward' ); ?></h2>
			<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" style="max-width:760px">
				<?php wp_nonce_field( 'bstew_member' ); ?>
				<input type="hidden" name="action" value="bstew_save_member">
				<input type="hidden" name="member_id" value="<?php echo esc_attr( $edit->id ?? 0 ); ?>">
				<table class="form-table" role="presentation">
					<tr><th><?php esc_html_e( 'Name', 'beitrag-steward' ); ?></th>
						<td><input class="regular-text" name="name" required value="<?php echo esc_attr( $edit->name ?? '' ); ?>"></td></tr>
					<tr><th><?php esc_html_e( 'Member number', 'beitrag-steward' ); ?></th>
						<td><input style="width:10em" name="member_no" value="<?php echo esc_attr( $edit->member_no ?? '' ); ?>"></td></tr>
					<tr><th><?php esc_html_e( 'Email', 'beitrag-steward' ); ?></th>
						<td><input class="regular-text" type="email" name="email" value="<?php echo esc_attr( $edit->email ?? '' ); ?>"></td></tr>
					<tr><th><?php esc_html_e( 'Street and number', 'beitrag-steward' ); ?></th>
						<td><input class="regular-text" name="street" value="<?php echo esc_attr( $edit->street ?? '' ); ?>"></td></tr>
					<tr><th><?php esc_html_e( 'Postcode / City / Country', 'beitrag-steward' ); ?></th>
						<td>
							<input style="width:7em" name="postcode" value="<?php echo esc_attr( $edit->postcode ?? '' ); ?>">
							<input style="width:14em" name="city" required value="<?php echo esc_attr( $edit->city ?? '' ); ?>">
							<input style="width:3.5em" name="country" maxlength="2" value="<?php echo esc_attr( $edit->country ?? 'DE' ); ?>">
							<p class="description"><?php esc_html_e( 'City and country are mandatory: SEPA files need a structured address for every member from 15 November 2026.', 'beitrag-steward' ); ?></p>
						</td></tr>
					<tr><th><?php esc_html_e( 'IBAN', 'beitrag-steward' ); ?></th>
						<td><input class="regular-text code" name="iban" placeholder="<?php echo $edit && $edit->iban_last4 ? esc_attr( '•••• ' . $edit->iban_last4 . ' — ' . __( 'leave blank to keep', 'beitrag-steward' ) ) : ''; ?>">
						<p class="description"><?php esc_html_e( 'Stored encrypted. Shown masked everywhere.', 'beitrag-steward' ); ?></p></td></tr>
					<tr><th><?php esc_html_e( 'Mandate reference', 'beitrag-steward' ); ?></th>
						<td><input style="width:14em" class="code" name="mandate_ref" value="<?php echo esc_attr( $edit->mandate_ref ?? '' ); ?>">
						<p class="description"><?php esc_html_e( 'Your own reference for the signed SEPA mandate, e.g. M-2026-0001.', 'beitrag-steward' ); ?></p></td></tr>
					<tr><th><?php esc_html_e( 'Mandate signature date', 'beitrag-steward' ); ?></th>
						<td><input type="date" name="mandate_date" value="<?php echo esc_attr( $edit->mandate_date ?? '' ); ?>"></td></tr>
					<tr><th><?php esc_html_e( 'Sequence', 'beitrag-steward' ); ?></th>
						<td><select name="sequence_type">
							<?php foreach ( array( 'FRST', 'RCUR', 'OOFF', 'FNAL' ) as $seq ) : ?>
								<option value="<?php echo esc_attr( $seq ); ?>" <?php selected( ( $edit->sequence_type ?? 'FRST' ), $seq ); ?>><?php echo esc_html( $seq ); ?></option>
							<?php endforeach; ?>
						</select>
						<p class="description"><?php esc_html_e( 'FRST for the first collection under a mandate; the plugin switches it to RCUR automatically after the first run.', 'beitrag-steward' ); ?></p></td></tr>
					<tr><th><?php esc_html_e( 'Annual fee (EUR)', 'beitrag-steward' ); ?></th>
						<td><input style="width:7em" name="amount" value="<?php echo esc_attr( $edit->amount ?? bstew_get_options()['default_amount'] ); ?>"></td></tr>
					<tr><th><?php esc_html_e( 'Active', 'beitrag-steward' ); ?></th>
						<td><label><input type="checkbox" name="active" value="1" <?php checked( (bool) ( $edit->active ?? true ) ); ?>> <?php esc_html_e( 'Include in collection runs', 'beitrag-steward' ); ?></label></td></tr>
				</table>
				<?php submit_button( $edit ? __( 'Save member', 'beitrag-steward' ) : __( 'Add member', 'beitrag-steward' ) ); ?>
			</form>
		</div>
		<?php
	}
}

BSTEW_Admin_Members::init();
