<?php
/**
 * Admin page: Mapowanie kontrahentów (contractor mappings)
 *
 * CRUD interfejs dla gksef_contractor_mappings.
 *
 * @package KSEF\WordPress\Admin
 */

namespace KSEF\WordPress\Admin;

// phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders, WordPress.DB.SlowDBQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.Security.NonceVerification -- Wlasne tabele gksef_*: wartosci przez $wpdb->prepare()/esc_like(), nazwy tabel z $wpdb->prefix, paginacja rzutowana (int); nonce weryfikowany w handlerze (check_ajax_referer/check_admin_referer).

use KSEF\WordPress\Purchase\Contractor_Mapper;

/**
 * Contractor_Mappings_Page
 *
 * Obsługuje:
 * - Wylistowanie mappingów
 * - Dodawanie nowych mappingów
 * - Edycja mappingów
 * - Usuwanie mappingów
 */
class Contractor_Mappings_Page {

	/**
	 * Renderuj stronę
	 *
	 * @return void
	 */
	public function render_page() {
		// Sprawdź uprawnienia
		if ( ! current_user_can( 'ksef_view_contractors' ) ) {
			wp_die( esc_html__( 'Brak uprawnień.', 'prostafaktura-ksef' ) );
		}

		// Pobierz akcję
		$action = isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '';

		// Obsłuż POST (dodaj/edytuj/usuń)
		if ( 'POST' === sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? '' ) ) ) {
			$this->handle_post();
		}

		if ( 'edit' === $action && isset( $_GET['nip'] ) ) {
			$this->render_edit_form( sanitize_text_field( wp_unslash( $_GET['nip'] ) ) );
		} else {
			$this->render_list();
		}
	}

	/**
	 * Renderuj listę mappingów
	 *
	 * @return void
	 */
	private function render_list() {
		$mappings = Contractor_Mapper::get_all();

		?>
		<div class="wrap">
			<h1><?php esc_html_e( 'KSEF - Mapowanie kontrahentów', 'prostafaktura-ksef' ); ?></h1>

			<p>
				<a href="?page=ksef-contractors&amp;action=add" class="button button-primary">
					<?php esc_html_e( '+ Dodaj mapowanie', 'prostafaktura-ksef' ); ?>
				</a>
			</p>

			<?php if ( empty( $mappings ) ) : ?>
				<p><?php esc_html_e( 'Brak mappingów. Dodaj pierwszego dostawcę.', 'prostafaktura-ksef' ); ?></p>
			<?php else : ?>
				<table class="wp-list-table widefat striped">
					<thead>
						<tr>
							<th><?php esc_html_e( 'NIP', 'prostafaktura-ksef' ); ?></th>
							<th><?php esc_html_e( 'Nazwa', 'prostafaktura-ksef' ); ?></th>
							<th><?php esc_html_e( 'Domyślna kategoria', 'prostafaktura-ksef' ); ?></th>
							<th><?php esc_html_e( 'Akcje', 'prostafaktura-ksef' ); ?></th>
						</tr>
					</thead>
					<tbody>
						<?php foreach ( $mappings as $mapping ) : ?>
							<tr>
								<td><strong><?php echo esc_html( $mapping['contractor_nip'] ); ?></strong></td>
								<td><?php echo esc_html( $mapping['contractor_name'] ); ?></td>
								<td>
									<code><?php echo esc_html( $mapping['default_category'] ); ?></code>
								</td>
								<td>
									<a href="?page=ksef-contractors&amp;action=edit&amp;nip=<?php echo esc_attr( $mapping['contractor_nip'] ); ?>" class="button button-small">
										<?php esc_html_e( 'Edytuj', 'prostafaktura-ksef' ); ?>
									</a>
									<a href="?page=ksef-contractors&amp;action=delete&amp;nip=<?php echo esc_attr( $mapping['contractor_nip'] ); ?>" class="button button-small" onclick="return confirm('<?php esc_attr_e( 'Na pewno usunąć?', 'prostafaktura-ksef' ); ?>')">
										<?php esc_html_e( 'Usuń', 'prostafaktura-ksef' ); ?>
									</a>
								</td>
							</tr>
						<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Renderuj formularz dodawania/edycji
	 *
	 * @param string $nip NIP (empty dla nowego).
	 * @return void
	 */
	private function render_edit_form( $nip ) {
		global $wpdb;

		$is_new = empty( $nip );
		$mapping = null;

		if ( ! $is_new ) {
			$mapping = $wpdb->get_row(
				$wpdb->prepare(
					"SELECT * FROM {$wpdb->prefix}gksef_contractor_mappings WHERE contractor_nip = %s",
					$nip
				),
				ARRAY_A
			);

			if ( ! $mapping ) {
				wp_die( esc_html__( 'Mapping not found.', 'prostafaktura-ksef' ) );
			}
		}

		?>
		<div class="wrap">
			<h1><?php echo $is_new ? esc_html__( 'Dodaj mapowanie', 'prostafaktura-ksef' ) : esc_html__( 'Edytuj mapowanie', 'prostafaktura-ksef' ); ?></h1>

			<form method="post" class="ksef-form">
				<?php wp_nonce_field( 'ksef_contractor_nonce' ); ?>
				<input type="hidden" name="action" value="<?php echo $is_new ? 'add' : 'edit'; ?>">
				<?php if ( ! $is_new ) : ?>
					<input type="hidden" name="original_nip" value="<?php echo esc_attr( $mapping['contractor_nip'] ); ?>">
				<?php endif; ?>

				<div class="form-group">
					<label for="contractor_nip"><?php esc_html_e( 'NIP', 'prostafaktura-ksef' ); ?></label>
					<input type="text" id="contractor_nip" name="contractor_nip" value="<?php echo esc_attr( $mapping['contractor_nip'] ?? '' ); ?>" placeholder="1234567890" maxlength="10" <?php disabled( ! $is_new ); ?> required>
					<p class="description"><?php esc_html_e( 'NIP dostawcy (10 cyfr). Po utworzeniu nie można zmienić.', 'prostafaktura-ksef' ); ?></p>
				</div>

				<div class="form-group">
					<label for="contractor_name"><?php esc_html_e( 'Nazwa dostawcy', 'prostafaktura-ksef' ); ?></label>
					<input type="text" id="contractor_name" name="contractor_name" value="<?php echo esc_attr( $mapping['contractor_name'] ?? '' ); ?>" maxlength="255" required>
					<p class="description"><?php esc_html_e( 'Pełna nazwa firmy.', 'prostafaktura-ksef' ); ?></p>
				</div>

				<div class="form-group">
					<label for="default_category"><?php esc_html_e( 'Domyślna kategoria wydatków', 'prostafaktura-ksef' ); ?></label>
					<select id="default_category" name="default_category" required>
						<option value=""></option>
						<option value="supplies" <?php selected( $mapping['default_category'] ?? '', 'supplies' ); ?>><?php esc_html_e( 'Materiały i surowce', 'prostafaktura-ksef' ); ?></option>
						<option value="services" <?php selected( $mapping['default_category'] ?? '', 'services' ); ?>><?php esc_html_e( 'Usługi', 'prostafaktura-ksef' ); ?></option>
						<option value="energy" <?php selected( $mapping['default_category'] ?? '', 'energy' ); ?>><?php esc_html_e( 'Energia', 'prostafaktura-ksef' ); ?></option>
						<option value="transport" <?php selected( $mapping['default_category'] ?? '', 'transport' ); ?>><?php esc_html_e( 'Transport', 'prostafaktura-ksef' ); ?></option>
						<option value="maintenance" <?php selected( $mapping['default_category'] ?? '', 'maintenance' ); ?>><?php esc_html_e( 'Serwis i konserwacja', 'prostafaktura-ksef' ); ?></option>
						<option value="other" <?php selected( $mapping['default_category'] ?? '', 'other' ); ?>><?php esc_html_e( 'Inne', 'prostafaktura-ksef' ); ?></option>
					</select>
					<p class="description"><?php esc_html_e( 'Kategoria wydatków do automatycznego przypisywania faktur od tego dostawcy.', 'prostafaktura-ksef' ); ?></p>
				</div>

				<div class="form-actions">
					<button type="submit" class="button button-primary">
						<?php echo $is_new ? esc_html__( 'Dodaj mapowanie', 'prostafaktura-ksef' ) : esc_html__( 'Zapisz zmiany', 'prostafaktura-ksef' ); ?>
					</button>
					<a href="?page=ksef-contractors" class="button">
						<?php esc_html_e( 'Anuluj', 'prostafaktura-ksef' ); ?>
					</a>
				</div>
			</form>
		</div>

		<?php ob_start(); ?>
			.ksef-form {
				max-width: 500px;
			}
			.form-group {
				margin-bottom: 20px;
			}
			.form-group label {
				display: block;
				margin-bottom: 8px;
				font-weight: bold;
			}
			.form-group input,
			.form-group select {
				width: 100%;
				padding: 10px;
				border: 1px solid #ddd;
				border-radius: 4px;
				font-size: 14px;
			}
			.form-group input:disabled {
				background: #f5f5f5;
				color: #666;
			}
			.description {
				color: #666;
				font-size: 12px;
				margin-top: 5px;
			}
			.form-actions {
				margin-top: 30px;
			}
			.form-actions button {
				margin-right: 10px;
			}
		<?php Modern_Shell::inline_style( 'ksef-contractor-mappings', ob_get_clean() ); ?>
		<?php
	}

	/**
	 * Obsłuż POST request
	 *
	 * @return void
	 */
	private function handle_post() {
		// Verify nonce
		if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'ksef_contractor_nonce' ) ) {
			wp_die( esc_html__( 'Security check failed.', 'prostafaktura-ksef' ) );
		}

		$action = isset( $_POST['action'] ) ? sanitize_text_field( wp_unslash( $_POST['action'] ) ) : '';

		if ( 'add' === $action ) {
			$this->handle_add();
		} elseif ( 'edit' === $action ) {
			$this->handle_update();
		} elseif ( 'delete' === $action ) {
			$this->handle_delete();
		}
	}

	/**
	 * Obsłuż dodawanie
	 *
	 * @return void
	 */
	private function handle_add() {
		$nip  = isset( $_POST['contractor_nip'] ) ? sanitize_text_field( wp_unslash( $_POST['contractor_nip'] ) ) : '';
		$name = isset( $_POST['contractor_name'] ) ? sanitize_text_field( wp_unslash( $_POST['contractor_name'] ) ) : '';
		$cat  = isset( $_POST['default_category'] ) ? sanitize_text_field( wp_unslash( $_POST['default_category'] ) ) : '';

		if ( empty( $nip ) || empty( $name ) || empty( $cat ) ) {
			wp_die( esc_html__( 'All fields are required.', 'prostafaktura-ksef' ) );
		}

		global $wpdb;

		// Sprawdź czy już istnieje
		$exists = $wpdb->get_var(
			$wpdb->prepare(
				"SELECT id FROM {$wpdb->prefix}gksef_contractor_mappings WHERE contractor_nip = %s",
				$nip
			)
		);

		if ( $exists ) {
			wp_die( esc_html__( 'This NIP already exists.', 'prostafaktura-ksef' ) );
		}

		$wpdb->insert(
			$wpdb->prefix . 'gksef_contractor_mappings',
			[
				'contractor_nip'   => $nip,
				'contractor_name'  => $name,
				'default_category' => $cat,
			]
		);

		wp_safe_remote_post( admin_url( 'admin.php?page=ksef-contractors' ), [ 'blocking' => false ] );
	}

	/**
	 * Obsłuż aktualizację
	 *
	 * @return void
	 */
	private function handle_update() {
		$nip  = isset( $_POST['original_nip'] ) ? sanitize_text_field( wp_unslash( $_POST['original_nip'] ) ) : '';
		$name = isset( $_POST['contractor_name'] ) ? sanitize_text_field( wp_unslash( $_POST['contractor_name'] ) ) : '';
		$cat  = isset( $_POST['default_category'] ) ? sanitize_text_field( wp_unslash( $_POST['default_category'] ) ) : '';

		if ( empty( $nip ) || empty( $name ) || empty( $cat ) ) {
			wp_die( esc_html__( 'All fields are required.', 'prostafaktura-ksef' ) );
		}

		Contractor_Mapper::update( $nip, [
			'name'               => $name,
			'default_category'   => $cat,
		] );

		wp_safe_remote_post( admin_url( 'admin.php?page=ksef-contractors' ), [ 'blocking' => false ] );
	}

	/**
	 * Obsłuż usuwanie
	 *
	 * @return void
	 */
	private function handle_delete() {
		$nip = isset( $_GET['nip'] ) ? sanitize_text_field( wp_unslash( $_GET['nip'] ) ) : '';

		if ( empty( $nip ) ) {
			wp_die( esc_html__( 'NIP is required.', 'prostafaktura-ksef' ) );
		}

		Contractor_Mapper::delete( $nip );

		wp_safe_remote_post( admin_url( 'admin.php?page=ksef-contractors' ), [ 'blocking' => false ] );
	}
}
