<?php
/**
 * Admin: dashboard (documents + exports + calendar + checklist) and settings.
 * All actions nonce-protected, capability manage_woocommerce.
 *
 * @package FEPW
 */

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

/**
 * Class FEPW_Admin
 */
class FEPW_Admin {

	/**
	 * Singleton.
	 *
	 * @var FEPW_Admin|null
	 */
	private static $instance = null;

	/**
	 * Instance.
	 *
	 * @return FEPW_Admin
	 */
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Constructor.
	 */
	private function __construct() {
		add_action( 'admin_menu', array( $this, 'menu' ) );
		add_action( 'admin_post_fepw_save_settings', array( $this, 'save_settings' ) );
		add_filter( 'woocommerce_admin_order_actions', array( $this, 'order_row_action' ), 10, 2 );
		add_action( 'add_meta_boxes', array( $this, 'metabox' ) );
	}

	/**
	 * Menu.
	 */
	public function menu() {
		add_menu_page(
			__( 'Facture Électronique', 'buildsbyluke-facture-electronique-for-woocommerce' ),
			__( 'Facture Électronique', 'buildsbyluke-facture-electronique-for-woocommerce' ),
			'manage_woocommerce',
			'fepw',
			array( $this, 'render_dashboard' ),
			'dashicons-media-spreadsheet',
			56
		);
		add_submenu_page( 'fepw', __( 'Documents', 'buildsbyluke-facture-electronique-for-woocommerce' ), __( 'Documents', 'buildsbyluke-facture-electronique-for-woocommerce' ), 'manage_woocommerce', 'fepw', array( $this, 'render_dashboard' ) );
		add_submenu_page( 'fepw', __( 'Settings', 'buildsbyluke-facture-electronique-for-woocommerce' ), __( 'Settings', 'buildsbyluke-facture-electronique-for-woocommerce' ), 'manage_woocommerce', 'fepw-settings', array( $this, 'render_settings' ) );
	}

	/**
	 * Readiness checklist items.
	 *
	 * @return array[] {label, done, hint}
	 */
	private function checklist() {
		$s = get_option( 'fepw_settings', array() );
		global $wpdb;
		$has_doc = (bool) $wpdb->get_var( "SELECT id FROM {$wpdb->prefix}fepw_documents LIMIT 1" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery -- own table.
		$eur     = 'EUR' === get_woocommerce_currency();
		$siren   = isset( $s['seller_siren'] ) ? $s['seller_siren'] : '';
		$tva     = isset( $s['seller_tva'] ) ? $s['seller_tva'] : '';
		return array(
			array( __( 'Seller identity complete (SIREN, VAT number, legal mentions)', 'buildsbyluke-facture-electronique-for-woocommerce' ), '' !== $siren && '' !== $tva, __( 'Fill it in Settings — required on every e-invoice.', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
			array( __( 'Plateforme Agréée chosen (deadline: 1 Sept 2026 to be able to RECEIVE)', 'buildsbyluke-facture-electronique-for-woocommerce' ), ! empty( $s['pa_chosen'] ), __( 'Pick a PA with your accountant, then tick this in Settings. This plugin is not a PA.', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
			array( __( 'B2B checkout fields live (SIREN captured on business orders)', 'buildsbyluke-facture-electronique-for-woocommerce' ), true, __( 'Enabled automatically on both classic and block checkout.', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
			array( __( 'Store currency is EUR', 'buildsbyluke-facture-electronique-for-woocommerce' ), $eur, __( 'French e-invoicing amounts must be in EUR. Multi-currency is not supported in v1.', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
			array( __( 'First test invoice generated and checked with your PA / the FNFE validator', 'buildsbyluke-facture-electronique-for-woocommerce' ), $has_doc, __( 'Generate one from any order, download the Factur-X, validate it.', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
			array( __( 'From 1 Sept 2027: B2B invoices ISSUED via your PA + e-reporting transmitted', 'buildsbyluke-facture-electronique-for-woocommerce' ), false, __( 'Use the export package (or the Pro automated pipe) when the issuance wave starts.', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
		);
	}

	/**
	 * Pro upsell — shown ONLY on this plugin's own dashboard, and only to users
	 * who cannot already use premium code (guideline 11: upsells belong on the
	 * plugin's own settings page; guideline 5/9: the features below are
	 * genuinely absent from the free build — their code is stripped from the
	 * wp.org zip — never locked-away free features). No site-wide nags — the
	 * SDK's trial notice stays disabled.
	 */
	private function render_upsell() {
		if ( ! function_exists( 'fepw_fs' ) || fepw_fs()->can_use_premium_code() ) {
			return;
		}
		$fs          = fepw_fs();
		$upgrade_url = method_exists( $fs, 'get_upgrade_url' ) ? $fs->get_upgrade_url() : admin_url( 'admin.php?page=fepw-pricing' );
		$trial_url   = '';
		if ( method_exists( $fs, 'is_trial_utilized' ) && ! $fs->is_trial_utilized() && method_exists( $fs, 'get_trial_url' ) ) {
			$trial_url = $fs->get_trial_url();
		}
		$features = array(
			__( 'Automated push of every invoice to your Plateforme Agréée (generic REST connector — works with any PA ingest API).', 'buildsbyluke-facture-electronique-for-woocommerce' ),
			__( 'Transmission log with HTTP status and errors — your audit trail.', 'buildsbyluke-facture-electronique-for-woocommerce' ),
		);
		echo '<div style="max-width:860px;margin:16px 0;padding:16px 20px;border:1px solid #c3c4c7;border-left:4px solid #2271b1;background:#fff;">';
		echo '<h2 style="margin-top:0;">' . esc_html__( 'Connect your PA with Facture Électronique Pro', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</h2>';
		echo '<p style="color:#50575e;max-width:640px;">' . esc_html__( 'The free plugin generates your e-invoices (manually and automatically on order completion) and exports them. Pro adds the automated transmission to your Plateforme Agréée:', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</p>';
		echo '<ul style="list-style:disc;margin:0 0 12px 20px;color:#1d2327;">';
		foreach ( $features as $feature ) {
			echo '<li style="margin-bottom:6px;">' . esc_html( $feature ) . '</li>';
		}
		echo '</ul>';
		if ( '' !== $trial_url ) {
			echo '<a href="' . esc_url( $trial_url ) . '" class="button button-primary button-hero" style="margin-right:8px;">' . esc_html__( 'Start 14-day free trial — no card', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</a>';
		}
		echo '<a href="' . esc_url( $upgrade_url ) . '" class="button button-hero">' . esc_html__( 'See plans', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</a>';
		echo '</div>';
	}

	/**
	 * Contextual reminder (this plugin's own screens only): automatic
	 * generation is on but waiting for the seller identity. The pause is a
	 * data prerequisite — documents are numbered immutably, so generating them
	 * with an empty seller block would create unfixable legal records.
	 */
	private function autogen_pending_notice() {
		$s     = get_option( 'fepw_settings', array() );
		$auto  = ! isset( $s['auto_generate'] ) || 1 === (int) $s['auto_generate'];
		$siren = isset( $s['seller_siren'] ) ? $s['seller_siren'] : '';
		if ( $auto && '' === $siren ) {
			echo '<div class="notice notice-warning"><p>' . esc_html__( 'Automatic invoice generation is on but paused: fill in your seller identity (SIREN) in Settings first. Invoices are numbered immutably, so the plugin will not issue them with an incomplete seller block.', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</p></div>';
		}
	}

	/**
	 * Dashboard: checklist, calendar, documents, exports.
	 */
	public function render_dashboard() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to view this page.', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		}
		$docs = FEPW_Documents::get_documents();
		$cal  = FEPW_Export::calendar();
		$from = wp_date( 'Y-m-01' );
		$to   = wp_date( 'Y-m-d' );
		echo '<div class="wrap"><h1>' . esc_html__( 'Facture Électronique — Documents & Compliance', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</h1>';
		if ( isset( $_GET['fepw_error'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only.
			echo '<div class="notice notice-error"><p>' . esc_html( sanitize_text_field( wp_unslash( $_GET['fepw_error'] ) ) ) . '</p></div>'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		}
		$this->autogen_pending_notice();

		$this->render_upsell();

		echo '<h2>' . esc_html__( 'Readiness checklist (réforme 2026-2027)', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</h2><ul style="max-width:860px">';
		foreach ( $this->checklist() as $item ) {
			printf(
				'<li style="margin-bottom:8px;">%s <strong>%s</strong><br /><span style="color:#646970">%s</span></li>',
				$item[1] ? '<span style="color:#00a32a">✔</span>' : '<span style="color:#d63638">✘</span>',
				esc_html( $item[0] ),
				esc_html( $item[2] )
			);
		}
		echo '</ul>';

		echo '<h2>' . esc_html__( 'E-reporting calendar (B2C)', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</h2>';
		echo '<p>' . esc_html( $cal['label'] ) . ' ' . esc_html__( 'Next transmissions:', 'buildsbyluke-facture-electronique-for-woocommerce' ) . ' <strong>' . esc_html( implode( ' · ', $cal['dates'] ) ) . '</strong></p>';

		$zip_url = wp_nonce_url( admin_url( 'admin-post.php?action=fepw_export_zip&from=' . $from . '&to=' . $to ), 'fepw_export' );
		$csv_url = wp_nonce_url( admin_url( 'admin-post.php?action=fepw_ereporting_csv&from=' . $from . '&to=' . $to ), 'fepw_ereporting' );
		echo '<p><a href="' . esc_url( $zip_url ) . '" class="button button-primary">' . esc_html__( 'Download PA export package (this month)', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</a> ';
		echo '<a href="' . esc_url( $csv_url ) . '" class="button">' . esc_html__( 'Download e-reporting extract (this month)', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</a></p>';

		echo '<h2>' . esc_html__( 'Documents', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</h2>';
		if ( empty( $docs ) ) {
			echo '<p>' . esc_html__( 'No documents yet. Open a WooCommerce order and use the "Facture Électronique" box, or the invoice action in the orders list.', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</p>';
		} else {
			echo '<table class="widefat striped"><thead><tr><th>' . esc_html__( 'Number', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</th><th>' . esc_html__( 'Type', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</th><th>' . esc_html__( 'Order', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</th><th>' . esc_html__( 'Date', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</th><th>' . esc_html__( 'Total (incl. VAT)', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</th><th>' . esc_html__( 'Downloads', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</th></tr></thead><tbody>';
			foreach ( $docs as $doc ) {
				$links = array();
				foreach ( array( 'facturx' => 'Factur-X', 'cii' => 'CII', 'ubl' => 'UBL', 'pdf' => 'PDF' ) as $kind => $label ) {
					$url     = wp_nonce_url( admin_url( 'admin-post.php?action=fepw_download&number=' . rawurlencode( $doc['doc_number'] ) . '&kind=' . $kind ), 'fepw_download' );
					$links[] = '<a href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a>';
				}
				printf(
					'<tr><td><strong>%s</strong></td><td>%s</td><td><a href="%s">#%d</a></td><td>%s</td><td>%s €</td><td>%s</td></tr>',
					esc_html( $doc['doc_number'] ),
					'credit_note' === $doc['doc_type'] ? esc_html__( 'Credit note', 'buildsbyluke-facture-electronique-for-woocommerce' ) : esc_html__( 'Invoice', 'buildsbyluke-facture-electronique-for-woocommerce' ),
					esc_url( admin_url( 'post.php?post=' . (int) $doc['order_id'] . '&action=edit' ) ),
					(int) $doc['order_id'],
					esc_html( get_date_from_gmt( $doc['issued_at'], get_option( 'date_format' ) ) ),
					esc_html( number_format( (float) $doc['total_ttc'], 2, ',', ' ' ) ),
					wp_kses_post( implode( ' · ', $links ) )
				);
			}
			echo '</tbody></table>';
		}

		echo '<p style="margin-top:24px;color:#646970;max-width:860px;font-size:12px;">' . esc_html__( 'This plugin is not a Plateforme Agréée and does not provide tax, legal or accounting advice (ne constitue pas un conseil fiscal, juridique ou comptable). The merchant remains responsible for issued invoices; legal transmission is performed by your PA.', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</p></div>';
	}

	/**
	 * Settings screen.
	 */
	public function render_settings() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to view this page.', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		}
		$s = get_option( 'fepw_settings', array() );
		$g = function ( $k, $d = '' ) use ( $s ) {
			return isset( $s[ $k ] ) ? $s[ $k ] : $d;
		};
		echo '<div class="wrap"><h1>' . esc_html__( 'Facture Électronique — Settings', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</h1>';
		if ( isset( $_GET['updated'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only flag.
			echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved.', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</p></div>';
		}
		$this->autogen_pending_notice();
		echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '">';
		wp_nonce_field( 'fepw_settings' );
		echo '<input type="hidden" name="action" value="fepw_save_settings" />';

		$text = function ( $key, $label, $desc = '' ) use ( $g ) {
			printf(
				'<tr><th scope="row"><label for="fepw-%1$s">%2$s</label></th><td><input type="text" class="regular-text" id="fepw-%1$s" name="%1$s" value="%3$s" />%4$s</td></tr>',
				esc_attr( $key ),
				esc_html( $label ),
				esc_attr( $g( $key ) ),
				$desc ? '<p class="description">' . esc_html( $desc ) . '</p>' : ''
			);
		};

		echo '<h2>' . esc_html__( 'Seller identity (appears on every e-invoice)', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</h2><table class="form-table">';
		$text( 'seller_siren', __( 'SIREN (9 digits)', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		$text( 'seller_tva', __( 'TVA intracommunautaire (FRxx…)', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		$text( 'seller_legal_form', __( 'Legal form (SARL, SAS, EI…)', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		$text( 'seller_rcs', __( 'RCS (e.g. RCS Paris 123 456 789)', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		$text( 'seller_capital', __( 'Share capital (e.g. 10 000 €)', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		echo '</table><h2>' . esc_html__( 'Invoicing', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</h2><table class="form-table">';
		$text( 'number_format', __( 'Invoice number format', 'buildsbyluke-facture-electronique-for-woocommerce' ), __( 'Tokens: {YYYY} {YY} {SEQ:5}. Sequence is atomic and gap-free per year.', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		$text( 'credit_format', __( 'Credit note number format', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		$text( 'due_days', __( 'Payment terms (days)', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		printf(
			'<tr><th scope="row">%s</th><td><label><input type="checkbox" name="auto_generate" value="1" %s /> %s</label></td></tr>',
			esc_html__( 'Automatic generation', 'buildsbyluke-facture-electronique-for-woocommerce' ),
			checked( $g( 'auto_generate', 1 ), 1, false ),
			esc_html__( 'Generate the e-invoice automatically when an order is completed (needs the seller identity above to be filled in).', 'buildsbyluke-facture-electronique-for-woocommerce' )
		);
		printf(
			'<tr><th scope="row">%s</th><td><select name="operation_category">%s</select></td></tr>',
			esc_html__( 'Category of operation (new mandatory mention)', 'buildsbyluke-facture-electronique-for-woocommerce' ),
			wp_kses(
				implode(
					'',
					array_map(
						function ( $pair ) use ( $g ) {
							return '<option value="' . esc_attr( $pair[0] ) . '"' . selected( $g( 'operation_category', 'goods' ), $pair[0], false ) . '>' . esc_html( $pair[1] ) . '</option>';
						},
						array(
							array( 'goods', __( 'Delivery of goods (livraison de biens)', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
							array( 'services', __( 'Services (prestation de services)', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
							array( 'mixed', __( 'Mixed (biens et services)', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
						)
					)
				),
				array( 'option' => array( 'value' => true, 'selected' => true ) )
			)
		);
		printf(
			'<tr><th scope="row">%s</th><td><label><input type="checkbox" name="option_debits" value="1" %s /> %s</label></td></tr>',
			esc_html__( 'TVA sur les débits', 'buildsbyluke-facture-electronique-for-woocommerce' ),
			checked( $g( 'option_debits', 0 ), 1, false ),
			esc_html__( 'The business has opted for VAT on debits (adds the mandatory mention).', 'buildsbyluke-facture-electronique-for-woocommerce' )
		);
		printf(
			'<tr><th scope="row">%s</th><td><select name="vat_regime">%s</select><p class="description">%s</p></td></tr>',
			esc_html__( 'VAT regime (e-reporting cadence)', 'buildsbyluke-facture-electronique-for-woocommerce' ),
			wp_kses(
				implode(
					'',
					array_map(
						function ( $pair ) use ( $g ) {
							return '<option value="' . esc_attr( $pair[0] ) . '"' . selected( $g( 'vat_regime', 'reel_normal' ), $pair[0], false ) . '>' . esc_html( $pair[1] ) . '</option>';
						},
						array(
							array( 'reel_normal', __( 'Réel normal (3× / month)', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
							array( 'simplifie', __( 'Réel simplifié (monthly)', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
							array( 'franchise', __( 'Franchise en base (every 2 months)', 'buildsbyluke-facture-electronique-for-woocommerce' ) ),
						)
					)
				),
				array( 'option' => array( 'value' => true, 'selected' => true ) )
			),
			esc_html__( 'Ask your accountant if unsure — it only affects the reminder calendar.', 'buildsbyluke-facture-electronique-for-woocommerce' )
		);
		printf(
			'<tr><th scope="row">%s</th><td><label><input type="checkbox" name="require_siren_b2b" value="1" %s /> %s</label></td></tr>',
			esc_html__( 'Require SIREN for business orders', 'buildsbyluke-facture-electronique-for-woocommerce' ),
			checked( $g( 'require_siren_b2b', 1 ), 1, false ),
			esc_html__( 'Recommended: buyer SIREN is mandatory on domestic B2B e-invoices.', 'buildsbyluke-facture-electronique-for-woocommerce' )
		);
		printf(
			'<tr><th scope="row">%s</th><td><label><input type="checkbox" name="pa_chosen" value="1" %s /> %s</label></td></tr>',
			esc_html__( 'Plateforme Agréée chosen', 'buildsbyluke-facture-electronique-for-woocommerce' ),
			checked( $g( 'pa_chosen', 0 ), 1, false ),
			esc_html__( 'Tick once your business has registered with a PA (readiness checklist item).', 'buildsbyluke-facture-electronique-for-woocommerce' )
		);
		echo '</table>';
		submit_button( __( 'Save Settings', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		echo '</form></div>';
	}

	/**
	 * Save settings.
	 */
	public function save_settings() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			wp_die( esc_html__( 'You do not have permission to do this.', 'buildsbyluke-facture-electronique-for-woocommerce' ) );
		}
		check_admin_referer( 'fepw_settings' );
		$s = get_option( 'fepw_settings', array() );

		$siren = isset( $_POST['seller_siren'] ) ? preg_replace( '/\D/', '', sanitize_text_field( wp_unslash( $_POST['seller_siren'] ) ) ) : '';
		$s['seller_siren']       = ( '' === $siren || FEPW_Checkout::is_valid_siren( $siren ) ) ? $siren : ( isset( $s['seller_siren'] ) ? $s['seller_siren'] : '' );
		$s['seller_tva']         = isset( $_POST['seller_tva'] ) ? strtoupper( preg_replace( '/[^A-Za-z0-9]/', '', sanitize_text_field( wp_unslash( $_POST['seller_tva'] ) ) ) ) : '';
		$s['seller_legal_form']  = isset( $_POST['seller_legal_form'] ) ? sanitize_text_field( wp_unslash( $_POST['seller_legal_form'] ) ) : '';
		$s['seller_rcs']         = isset( $_POST['seller_rcs'] ) ? sanitize_text_field( wp_unslash( $_POST['seller_rcs'] ) ) : '';
		$s['seller_capital']     = isset( $_POST['seller_capital'] ) ? sanitize_text_field( wp_unslash( $_POST['seller_capital'] ) ) : '';
		$s['number_format']      = isset( $_POST['number_format'] ) && '' !== trim( sanitize_text_field( wp_unslash( $_POST['number_format'] ) ) ) ? sanitize_text_field( wp_unslash( $_POST['number_format'] ) ) : 'FA-{YYYY}-{SEQ:5}';
		$s['credit_format']      = isset( $_POST['credit_format'] ) && '' !== trim( sanitize_text_field( wp_unslash( $_POST['credit_format'] ) ) ) ? sanitize_text_field( wp_unslash( $_POST['credit_format'] ) ) : 'AV-{YYYY}-{SEQ:5}';
		$s['due_days']           = isset( $_POST['due_days'] ) ? max( 0, min( 120, absint( wp_unslash( $_POST['due_days'] ) ) ) ) : 30;
		$op_cat                  = isset( $_POST['operation_category'] ) ? sanitize_key( wp_unslash( $_POST['operation_category'] ) ) : '';
		$s['operation_category'] = in_array( $op_cat, array( 'goods', 'services', 'mixed' ), true ) ? $op_cat : 'goods';
		$regime                  = isset( $_POST['vat_regime'] ) ? sanitize_key( wp_unslash( $_POST['vat_regime'] ) ) : '';
		$s['vat_regime']         = in_array( $regime, array( 'reel_normal', 'simplifie', 'franchise' ), true ) ? $regime : 'reel_normal';
		$s['auto_generate']      = empty( $_POST['auto_generate'] ) ? 0 : 1;
		$s['option_debits']      = empty( $_POST['option_debits'] ) ? 0 : 1;
		$s['require_siren_b2b']  = empty( $_POST['require_siren_b2b'] ) ? 0 : 1;
		$s['pa_chosen']          = empty( $_POST['pa_chosen'] ) ? 0 : 1;

		update_option( 'fepw_settings', $s );
		wp_safe_redirect( add_query_arg( array( 'page' => 'fepw-settings', 'updated' => 1 ), admin_url( 'admin.php' ) ) );
		exit;
	}

	/**
	 * Orders-list row action: generate invoice.
	 *
	 * @param array    $actions Actions.
	 * @param WC_Order $order   Order.
	 * @return array
	 */
	public function order_row_action( $actions, $order ) {
		$actions['fepw'] = array(
			'url'    => wp_nonce_url( admin_url( 'admin-post.php?action=fepw_generate&order_id=' . $order->get_id() ), 'fepw_generate' ),
			'name'   => __( 'E-invoice', 'buildsbyluke-facture-electronique-for-woocommerce' ),
			'action' => 'fepw',
		);
		return $actions;
	}

	/**
	 * Order metabox (classic + HPOS screens).
	 */
	public function metabox() {
		foreach ( array( 'shop_order', 'woocommerce_page_wc-orders' ) as $screen ) {
			add_meta_box(
				'fepw_box',
				__( 'Facture Électronique', 'buildsbyluke-facture-electronique-for-woocommerce' ),
				array( $this, 'render_metabox' ),
				$screen,
				'side'
			);
		}
	}

	/**
	 * Metabox content.
	 *
	 * @param mixed $post_or_order Post or order object.
	 */
	public function render_metabox( $post_or_order ) {
		$order = $post_or_order instanceof WC_Order ? $post_or_order : wc_get_order( $post_or_order->ID );
		if ( ! $order ) {
			return;
		}
		$docs = array_filter(
			FEPW_Documents::get_documents(),
			function ( $d ) use ( $order ) {
				return (int) $d['order_id'] === $order->get_id();
			}
		);
		if ( empty( $docs ) ) {
			$url = wp_nonce_url( admin_url( 'admin-post.php?action=fepw_generate&order_id=' . $order->get_id() ), 'fepw_generate' );
			echo '<p><a href="' . esc_url( $url ) . '" class="button button-primary">' . esc_html__( 'Generate e-invoice', 'buildsbyluke-facture-electronique-for-woocommerce' ) . '</a></p>';
			return;
		}
		foreach ( $docs as $doc ) {
			echo '<p><strong>' . esc_html( $doc['doc_number'] ) . '</strong> (' . esc_html( $doc['doc_type'] ) . ')<br />';
			$links = array();
			foreach ( array( 'facturx' => 'Factur-X', 'cii' => 'CII', 'ubl' => 'UBL', 'pdf' => 'PDF' ) as $kind => $label ) {
				$url     = wp_nonce_url( admin_url( 'admin-post.php?action=fepw_download&number=' . rawurlencode( $doc['doc_number'] ) . '&kind=' . $kind ), 'fepw_download' );
				$links[] = '<a href="' . esc_url( $url ) . '">' . esc_html( $label ) . '</a>';
			}
			echo wp_kses_post( implode( ' · ', $links ) ) . '</p>';
		}
	}
}
