<?php
/**
 * Admin page: Kontrahenci — baza kontrahentów z CRUD.
 *
 * Tabela: gksef_contractor_mappings (rozszerzona w v5 o pełen adres + dane kontaktowe).
 *
 * @package KSEF\WordPress\Admin
 */

declare(strict_types=1);

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).

class Contractors_Page {

	public function render_page(): void {
		if ( ! current_user_can( 'ksef_view_contractors' ) ) {
			wp_die( esc_html__( 'Brak uprawnień.', 'prostafaktura-ksef' ) );
		}

		global $wpdb;
		$table  = $wpdb->prefix . 'gksef_contractor_mappings';
		$action = isset( $_GET['action'] ) ? sanitize_text_field( wp_unslash( $_GET['action'] ) ) : '';
		$id     = intval( wp_unslash( $_GET['id'] ?? 0 ) );

		// Obsługa POST: zapis (dodaj / edytuj)
		if ( 'POST' === sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? '' ) ) && check_admin_referer( 'ksef_contractor_save' ) ) {
			$data = self::collect_post();
			if ( $id > 0 ) {
				$wpdb->update( $table, $data, [ 'id' => $id ] );
				$msg = 'updated';
			} else {
				$wpdb->insert( $table, $data );
				$id  = (int) $wpdb->insert_id;
				$msg = 'created';
			}
			// Świadome dodanie/zapis kontrahenta zdejmuje ewentualny nagrobek (sync może go znów uzupełniać).
			\KSEF\WordPress\V2\Contractors_Sync::remove_tombstone( (string) ( $data['contractor_nip'] ?? '' ), (string) ( $data['contractor_name'] ?? '' ) );
			// &t=… → unikalny URL, by przeglądarka nie pokazała zcache'owanej listy sprzed zmiany.
			wp_safe_redirect( admin_url( 'admin.php?page=ksef-contractors&msg=' . $msg . '&t=' . time() ) );
			exit;
		}

		// Usunięcie
		if ( 'delete' === $action && $id > 0 && check_admin_referer( 'ksef_contractor_del_' . $id ) ) {
			$gone = $wpdb->get_row( $wpdb->prepare( "SELECT contractor_nip, contractor_name FROM {$table} WHERE id = %d", $id ), ARRAY_A );
			$wpdb->delete( $table, [ 'id' => $id ], [ '%d' ] );
			// Nagrobek: synchronizacja faktur NIE odtworzy usuniętego kontrahenta.
			if ( $gone ) {
				\KSEF\WordPress\V2\Contractors_Sync::add_tombstone( (string) ( $gone['contractor_nip'] ?? '' ), (string) ( $gone['contractor_name'] ?? '' ) );
			}
			// &t=… → unikalny URL, by przeglądarka nie pokazała zcache'owanej listy sprzed usunięcia.
			wp_safe_redirect( admin_url( 'admin.php?page=ksef-contractors&msg=deleted&t=' . time() ) );
			exit;
		}

		$is_edit_form = ( 'edit' === $action || 'add' === $action );
		$mode_label   = ( 'add' === $action ) ? __( 'Nowy', 'prostafaktura-ksef' )
			: ( ( 'edit' === $action ) ? __( 'Edycja', 'prostafaktura-ksef' ) : __( 'Lista', 'prostafaktura-ksef' ) );

		Modern_Shell::open( 'kontrahenci', [
			'crumbs'   => [ __( 'Kontrahenci', 'prostafaktura-ksef' ), $mode_label ],
			'title'    => $is_edit_form ? ( 'add' === $action ? 'Nowy | kontrahent' : 'Edycja | kontrahenta' ) : 'Baza | kontrahentów',
			'subtitle' => $is_edit_form
				? __( 'Pełne dane B2B/B2C z polami KSeF: NIP, adres, kontakt, status weryfikacji.', 'prostafaktura-ksef' )
				: __( 'Wszystkie firmy i osoby, do których wystawiasz faktury. Dane z poprzednich faktur i deduplikacja po NIP.', 'prostafaktura-ksef' ),
		] );
		try {
			if ( $is_edit_form ) {
				self::render_edit_form( $id );
			} else {
				self::render_list();
			}
		} finally {
			Modern_Shell::close();
		}
	}

	private static function render_list(): void {
		global $wpdb;
		$table = $wpdb->prefix . 'gksef_contractor_mappings';

		$search    = isset( $_GET['s'] ) ? sanitize_text_field( wp_unslash( $_GET['s'] ) ) : '';
		$paged     = max( 1, intval( wp_unslash( $_GET['paged'] ?? 1 ) ) );
		$per_page  = 25;
		$offset    = ( $paged - 1 ) * $per_page;

		$where = '1=1';
		if ( '' !== $search ) {
			$like  = '%' . $wpdb->esc_like( $search ) . '%';
			$where = $wpdb->prepare( '(contractor_name LIKE %s OR contractor_nip LIKE %s OR city LIKE %s)', $like, $like, $like );
		}

		$total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE {$where}" );
		$rows  = $wpdb->get_results( "SELECT * FROM {$table} WHERE {$where} ORDER BY contractor_name ASC LIMIT {$per_page} OFFSET {$offset}", ARRAY_A );
		$rows  = is_array( $rows ) ? $rows : [];

		$msg = sanitize_text_field( wp_unslash( $_GET['msg'] ?? '' ) );
		?>
		<div class="ksef-contractors-page">
			<?php if ( $msg === 'created' ) : ?><div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Kontrahent dodany.', 'prostafaktura-ksef' ); ?></p></div><?php endif; ?>
			<?php if ( $msg === 'updated' ) : ?><div class="notice notice-success is-dismissible"><p><?php esc_html_e( 'Zapisano zmiany.', 'prostafaktura-ksef' ); ?></p></div><?php endif; ?>
			<?php if ( $msg === 'deleted' ) : ?><div class="notice notice-warning is-dismissible"><p><?php esc_html_e( 'Kontrahent usunięty.', 'prostafaktura-ksef' ); ?></p></div><?php endif; ?>

			<div class="list-toolbar">
				<form method="get" class="search-box">
					<input type="hidden" name="page" value="ksef-contractors">
					<div class="input-wrap">
						<input class="input with-icon" type="search" name="s" value="<?php echo esc_attr( $search ); ?>" placeholder="<?php esc_attr_e( 'Szukaj po nazwie, NIP lub mieście…', 'prostafaktura-ksef' ); ?>">
						<span class="lic"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg></span>
					</div>
				</form>
				<div style="margin-left:auto; display:flex; gap:6px;">
					<?php if ( $search !== '' ) : ?>
						<a href="<?php echo esc_url( admin_url( 'admin.php?page=ksef-contractors' ) ); ?>" class="btn btn-ghost btn-sm"><?php esc_html_e( 'Wyczyść', 'prostafaktura-ksef' ); ?></a>
					<?php endif; ?>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=ksef-contractors&action=add' ) ); ?>" class="btn btn-primary btn-sm">
						<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 5v14M5 12h14"/></svg>
						<?php esc_html_e( 'Dodaj kontrahenta', 'prostafaktura-ksef' ); ?>
					</a>
				</div>
			</div>

			<table class="wp-list-table widefat striped">
				<thead>
					<tr>
						<th><?php esc_html_e( 'Nazwa', 'prostafaktura-ksef' ); ?></th>
						<th><?php esc_html_e( 'Typ', 'prostafaktura-ksef' ); ?></th>
						<th><?php esc_html_e( 'NIP / Identyfikator', 'prostafaktura-ksef' ); ?></th>
						<th><?php esc_html_e( 'Miasto', 'prostafaktura-ksef' ); ?></th>
						<th><?php esc_html_e( 'Email / Telefon', 'prostafaktura-ksef' ); ?></th>
						<th><?php esc_html_e( 'Nr klienta', 'prostafaktura-ksef' ); ?></th>
						<th style="width:160px;"><?php esc_html_e( 'Akcje', 'prostafaktura-ksef' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php if ( empty( $rows ) ) : ?>
						<tr><td colspan="7" style="text-align:center;color:#888;padding:24px;"><?php esc_html_e( 'Brak kontrahentów. Dodaj pierwszego klikając "+ Dodaj kontrahenta".', 'prostafaktura-ksef' ); ?></td></tr>
					<?php else : foreach ( $rows as $r ) :
						$type_labels = [
							'pl_firm' => 'Firma PL',
							'b2c'     => 'Osoba prywatna',
							'ue'      => 'Firma UE',
							'non_ue'  => 'Firma spoza UE',
						];
						$bt = (string) ( $r['buyer_type'] ?? 'pl_firm' );
					?>
						<tr class="ksef-ctr-row" style="cursor:pointer;" data-edit="<?php echo esc_url( admin_url( 'admin.php?page=ksef-contractors&action=edit&id=' . (int) $r['id'] ) ); ?>">
							<td><strong><?php echo esc_html( (string) ( $r['contractor_name'] ?? '' ) ); ?></strong></td>
							<td><?php echo esc_html( $type_labels[ $bt ] ?? $bt ); ?></td>
							<td>
								<?php echo esc_html( (string) ( $r['contractor_nip'] ?? '' ) ); ?>
								<?php if ( ! empty( $r['vat_ue'] ) ) : ?><br><small>VAT-UE: <?php echo esc_html( (string) $r['vat_ue'] ); ?></small><?php endif; ?>
								<?php if ( ! empty( $r['nr_id'] ) ) : ?><br><small>NrID: <?php echo esc_html( (string) $r['nr_id'] ); ?></small><?php endif; ?>
							</td>
							<td><?php echo esc_html( (string) ( $r['city'] ?? '' ) ); ?></td>
							<td>
								<?php if ( ! empty( $r['email'] ) ) : ?><a href="mailto:<?php echo esc_attr( (string) $r['email'] ); ?>"><?php echo esc_html( (string) $r['email'] ); ?></a><br><?php endif; ?>
								<small><?php echo esc_html( (string) ( $r['phone'] ?? '' ) ); ?></small>
							</td>
							<td><?php echo esc_html( (string) ( $r['customer_no'] ?? '' ) ); ?></td>
							<td>
								<a href="<?php echo esc_url( admin_url( 'admin.php?page=ksef-contractors&action=edit&id=' . (int) $r['id'] ) ); ?>" class="button button-small"><?php esc_html_e( 'Edytuj', 'prostafaktura-ksef' ); ?></a>
								<a href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin.php?page=ksef-contractors&action=delete&id=' . (int) $r['id'] ), 'ksef_contractor_del_' . (int) $r['id'] ) ); ?>" class="button button-small" style="color:#a00;" onclick="return confirm('<?php esc_attr_e( 'Usunąć kontrahenta?', 'prostafaktura-ksef' ); ?>');"><?php esc_html_e( 'Usuń', 'prostafaktura-ksef' ); ?></a>
							</td>
						</tr>
					<?php endforeach; endif; ?>
				</tbody>
			</table>

			<?php
			$total_pages = max( 1, (int) ceil( $total / $per_page ) );
			if ( $total_pages > 1 ) :
				$pl = paginate_links( [
					'base'    => add_query_arg( 'paged', '%#%' ),
					'format'  => '',
					'current' => $paged,
					'total'   => $total_pages,
					'type'    => 'array',
				] );
				?>
				<div class="tablenav bottom"><div class="tablenav-pages"><?php echo wp_kses_post( implode( ' ', (array) $pl ) ); ?></div></div>
			<?php endif; ?>
		</div>
		<?php
		Modern_Shell::inline_style( 'ksef-contractors-list', '.ksef-ctr-row:hover{background:#f3f4f6 !important;}' );
		ob_start();
		?>
			// Kliknięcie w dowolne miejsce wiersza kontrahenta → ekran edycji
			// (pomijamy klik w link/przycisk, np. mailto / Edytuj / Usuń).
			document.querySelectorAll('.ksef-ctr-row').forEach(function(tr){
				tr.addEventListener('click', function(e){
					if (e.target.closest('a,button')) return;
					const url = tr.getAttribute('data-edit');
					if (url) window.location.href = url;
				});
			});
		<?php
		Modern_Shell::inline_script( 'ksef-contractors-list', ob_get_clean() );
	}

	private static function render_edit_form( int $id ): void {
		global $wpdb;
		$table = $wpdb->prefix . 'gksef_contractor_mappings';
		$row   = $id > 0
			? (array) $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$table} WHERE id = %d", $id ), ARRAY_A )
			: [];
		$is_new = $id === 0;
		$c_nip  = (string) ( $row['contractor_nip'] ?? '' );
		$c_name = (string) ( $row['contractor_name'] ?? '' );
		?>
		<div class="ksef-contractor-edit">
			<?php if ( ! $is_new ) : ?>
			<div class="ksef-ctab-nav">
				<button type="button" class="ksef-ctab is-active" data-tab="ogolne"><?php esc_html_e( 'Ogólne', 'prostafaktura-ksef' ); ?></button>
				<button type="button" class="ksef-ctab" data-tab="sprzedaz"><?php esc_html_e( 'Faktury sprzedaży', 'prostafaktura-ksef' ); ?></button>
			</div>
			<?php endif; ?>

			<div class="ksef-ctab-panel" data-panel="ogolne">
			<form method="post" style="max-width:900px;">
				<?php wp_nonce_field( 'ksef_contractor_save' ); ?>
				<div class="ksef-card">
					<table class="form-table">
						<tr>
							<th><label for="buyer_type"><?php esc_html_e( 'Typ', 'prostafaktura-ksef' ); ?> *</label></th>
							<td>
								<select name="buyer_type" id="buyer_type">
									<?php $bt = (string) ( $row['buyer_type'] ?? 'pl_firm' ); ?>
									<option value="pl_firm" <?php selected( $bt, 'pl_firm' ); ?>>Firma polska (NIP)</option>
									<option value="b2c"     <?php selected( $bt, 'b2c' ); ?>>Osoba prywatna (BrakID)</option>
									<option value="ue"      <?php selected( $bt, 'ue' ); ?>>Firma UE (VAT-UE)</option>
									<option value="non_ue"  <?php selected( $bt, 'non_ue' ); ?>>Firma spoza UE</option>
								</select>
							</td>
						</tr>
						<tr>
							<th><label for="contractor_name"><?php esc_html_e( 'Nazwa / Imię i nazwisko', 'prostafaktura-ksef' ); ?> *</label></th>
							<td><input type="text" name="contractor_name" id="contractor_name" value="<?php echo esc_attr( (string) ( $row['contractor_name'] ?? '' ) ); ?>" class="regular-text" required></td>
						</tr>
						<tr class="row-nip">
							<th><label for="contractor_nip"><?php esc_html_e( 'NIP', 'prostafaktura-ksef' ); ?></label></th>
							<td>
								<input type="text" name="contractor_nip" id="contractor_nip" value="<?php echo esc_attr( (string) ( $row['contractor_nip'] ?? '' ) ); ?>" maxlength="10" placeholder="0000000000">
							</td>
						</tr>
						<tr class="row-ue" style="display:none;">
							<th><?php esc_html_e( 'VAT-UE', 'prostafaktura-ksef' ); ?></th>
							<td><input type="text" name="vat_ue" value="<?php echo esc_attr( (string) ( $row['vat_ue'] ?? '' ) ); ?>" placeholder="DE123456789"></td>
						</tr>
						<tr class="row-nonue" style="display:none;">
							<th><?php esc_html_e( 'Nr identyfikatora (poza UE)', 'prostafaktura-ksef' ); ?></th>
							<td><input type="text" name="nr_id" value="<?php echo esc_attr( (string) ( $row['nr_id'] ?? '' ) ); ?>"></td>
						</tr>
						<tr>
							<th><label><?php esc_html_e( 'Kraj (kod 2 znaki)', 'prostafaktura-ksef' ); ?></label></th>
							<td><input type="text" name="country_code" value="<?php echo esc_attr( (string) ( $row['country_code'] ?? 'PL' ) ); ?>" maxlength="2" style="width:80px;"></td>
						</tr>
						<tr>
							<th><label><?php esc_html_e( 'Ulica i nr', 'prostafaktura-ksef' ); ?></label></th>
							<td>
								<input type="text" name="street" value="<?php echo esc_attr( (string) ( $row['street'] ?? '' ) ); ?>" placeholder="<?php esc_attr_e( 'Ulica', 'prostafaktura-ksef' ); ?>" style="width:60%;">
								<input type="text" name="street_number" value="<?php echo esc_attr( (string) ( $row['street_number'] ?? '' ) ); ?>" placeholder="<?php esc_attr_e( 'Nr', 'prostafaktura-ksef' ); ?>" style="width:25%;">
							</td>
						</tr>
						<tr>
							<th><label><?php esc_html_e( 'Kod / Miasto', 'prostafaktura-ksef' ); ?></label></th>
							<td>
								<input type="text" name="postal_code" value="<?php echo esc_attr( (string) ( $row['postal_code'] ?? '' ) ); ?>" placeholder="00-000" style="width:100px;">
								<input type="text" name="city" value="<?php echo esc_attr( (string) ( $row['city'] ?? '' ) ); ?>" placeholder="<?php esc_attr_e( 'Miasto', 'prostafaktura-ksef' ); ?>">
							</td>
						</tr>
						<tr>
							<th><label><?php esc_html_e( 'Email', 'prostafaktura-ksef' ); ?></label></th>
							<td><input type="email" name="email" value="<?php echo esc_attr( (string) ( $row['email'] ?? '' ) ); ?>" class="regular-text"></td>
						</tr>
						<tr>
							<th><label><?php esc_html_e( 'Telefon', 'prostafaktura-ksef' ); ?></label></th>
							<td><input type="text" name="phone" value="<?php echo esc_attr( (string) ( $row['phone'] ?? '' ) ); ?>" class="regular-text"></td>
						</tr>
						<tr>
							<th><label><?php esc_html_e( 'Nr klienta', 'prostafaktura-ksef' ); ?></label></th>
							<td><input type="text" name="customer_no" value="<?php echo esc_attr( (string) ( $row['customer_no'] ?? '' ) ); ?>" placeholder="np. K-00123"></td>
						</tr>
						<tr>
							<th><label><?php esc_html_e( 'Notatka wewnętrzna', 'prostafaktura-ksef' ); ?></label></th>
							<td><textarea name="notes" rows="3" class="large-text"><?php echo esc_textarea( (string) ( $row['notes'] ?? '' ) ); ?></textarea></td>
						</tr>
					</table>
				</div>
				<p class="submit">
					<button type="submit" class="button button-primary button-large"><?php echo $is_new ? esc_html__( 'Dodaj kontrahenta', 'prostafaktura-ksef' ) : esc_html__( 'Zapisz zmiany', 'prostafaktura-ksef' ); ?></button>
					<a href="<?php echo esc_url( admin_url( 'admin.php?page=ksef-contractors' ) ); ?>" class="button button-large"><?php esc_html_e( 'Anuluj', 'prostafaktura-ksef' ); ?></a>
				</p>
			</form>
			</div><!-- /panel ogolne -->

			<?php if ( ! $is_new ) : ?>
			<div class="ksef-ctab-panel" data-panel="sprzedaz" style="display:none;">
				<?php self::render_contractor_invoices( 'outgoing', $c_nip, $c_name ); ?>
			</div>

			<!-- Modal podglądu faktury -->
			<div id="ksef-ctr-modal" class="ksef-modal-overlay" style="display:none;position:fixed;inset:0;background:rgba(10,10,11,.55);z-index:9999;align-items:center;justify-content:center;">
				<div class="ksef-modal-card" style="background:#fff;border-radius:14px;width:92%;max-width:900px;max-height:88vh;overflow:auto;padding:22px 26px;position:relative;">
					<button type="button" id="ksef-ctr-modal-close" style="position:absolute;top:12px;right:14px;background:none;border:none;font-size:22px;cursor:pointer;color:#555;">&times;</button>
					<div id="ksef-ctr-modal-body" style="max-height:78vh;overflow:auto;"><p>Ładowanie…</p></div>
				</div>
			</div>
			<?php endif; ?>
		</div>

		<?php ob_start(); ?>
		.ksef-ctab-nav{ display:flex; gap:4px; border-bottom:1px solid var(--ink-6,#E7E5E1); margin-bottom:18px; flex-wrap:wrap; }
		.ksef-ctab{ background:none; border:none; padding:10px 16px; font-size:14px; font-weight:500; color:var(--ink-4,#777); cursor:pointer; border-bottom:2px solid transparent; margin-bottom:-1px; }
		.ksef-ctab:hover{ color:var(--ink,#0A0A0B); }
		.ksef-ctab.is-active{ color:var(--brand,#5B5BD6); border-bottom-color:var(--brand,#5B5BD6); }
		.ksef-ctr-period{ display:flex; gap:12px; align-items:flex-end; flex-wrap:wrap; background:#fff; border:1px solid var(--ink-6,#E7E5E1); border-radius:12px; padding:14px 16px; margin-bottom:14px; }
		.ksef-ctr-period label{ display:block; font-size:11px; color:var(--ink-4,#777); margin-bottom:4px; }
		.ksef-ctr-period input[type=date]{ padding:7px 10px; border:1px solid var(--ink-6,#E7E5E1); border-radius:8px; }
		.ksef-ctr-sum{ margin-left:auto; display:flex; gap:18px; align-items:center; }
		.ksef-ctr-sum .v{ font-size:18px; font-weight:700; color:var(--ink,#0A0A0B); }
		.ksef-ctr-sum .l{ font-size:11px; color:var(--ink-4,#777); text-transform:uppercase; letter-spacing:.05em; }
		.ksef-ctr-table{ width:100%; border-collapse:collapse; font-size:13px; background:#fff; border:1px solid var(--ink-6,#E7E5E1); border-radius:12px; overflow:hidden; }
		.ksef-ctr-table th{ background:var(--surface-2,#F7F5F0); text-align:left; padding:10px 12px; font-size:11px; text-transform:uppercase; letter-spacing:.05em; color:var(--ink-4,#777); }
		.ksef-ctr-table td{ padding:10px 12px; border-top:1px solid var(--ink-6,#EEEAE3); }
		.ksef-ctr-table td.amt{ text-align:right; font-variant-numeric:tabular-nums; font-weight:600; }
		.ksef-ctr-table tr.is-hidden{ display:none; }
		.ksef-ctr-empty{ padding:28px; text-align:center; color:var(--ink-4,#777); }
		@media (max-width:600px){ .ksef-ctr-table{ display:block; overflow-x:auto; white-space:nowrap; } .ksef-ctr-sum{ margin-left:0; flex-wrap:wrap; gap:12px; } }
		<?php Modern_Shell::inline_style( 'ksef-contractors-card', ob_get_clean() ); ob_start(); ?>
		(function(){
			const sel = document.getElementById('buyer_type');
			if (sel) {
				function toggle(){
					const v = sel.value;
					document.querySelector('.row-ue').style.display = v === 'ue' ? '' : 'none';
					document.querySelector('.row-nonue').style.display = v === 'non_ue' ? '' : 'none';
					document.querySelector('.row-nip').style.display = v === 'pl_firm' ? '' : 'none';
				}
				sel.addEventListener('change', toggle);
				toggle();
			}

			// Zakładki karty kontrahenta
			document.querySelectorAll('.ksef-ctab').forEach(function(btn){
				btn.addEventListener('click', function(){
					document.querySelectorAll('.ksef-ctab').forEach(b => b.classList.remove('is-active'));
					btn.classList.add('is-active');
					const tab = btn.getAttribute('data-tab');
					document.querySelectorAll('.ksef-ctab-panel').forEach(p => {
						p.style.display = ( p.getAttribute('data-panel') === tab ) ? '' : 'none';
					});
				});
			});

			// Filtr okresu + przeliczanie sum (per panel faktur)
			const fmt = n => Number(n||0).toLocaleString('pl-PL',{minimumFractionDigits:2,maximumFractionDigits:2});
			document.querySelectorAll('.ksef-ctr-invoices').forEach(function(box){
				const from = box.querySelector('.ctr-from');
				const to   = box.querySelector('.ctr-to');
				const rows = Array.from(box.querySelectorAll('tbody tr'));
				function recalc(){
					const f = from.value, t = to.value;
					let n=0, net=0, vat=0, gross=0;
					rows.forEach(tr => {
						const d = tr.getAttribute('data-date') || '';
						const show = (!f || d >= f) && (!t || d <= t);
						tr.classList.toggle('is-hidden', !show);
						if (show){ n++; net+=parseFloat(tr.dataset.net||0); vat+=parseFloat(tr.dataset.vat||0); gross+=parseFloat(tr.dataset.gross||0); }
					});
					box.querySelector('.sum-count').textContent = n;
					box.querySelector('.sum-net').textContent = fmt(net);
					box.querySelector('.sum-vat').textContent = fmt(vat);
					box.querySelector('.sum-gross').textContent = fmt(gross);
				}
				from.addEventListener('change', recalc);
				to.addEventListener('change', recalc);
				box.querySelectorAll('.ctr-quick').forEach(q => q.addEventListener('click', function(){
					from.value = q.getAttribute('data-from'); to.value = q.getAttribute('data-to'); recalc();
				}));
				recalc();
			});

			// Podgląd faktury = widok formularza (read-only) w nowej karcie — zachowuje
			// kontekst karty kontrahenta. type=incoming dla zakupu.
			const viewBase = <?php echo wp_json_encode( admin_url( 'admin.php?page=ksef-manual-invoice&action=view&id=' ) ); ?>;
			document.querySelectorAll('.ksef-ctr-preview').forEach(function(b){
				b.addEventListener('click', function(){
					const id = b.getAttribute('data-id'), type = b.getAttribute('data-type');
					const url = viewBase + id + ( type === 'incoming' ? '&type=incoming' : '' );
					window.open(url, '_blank');
				});
			});
		})();
		<?php Modern_Shell::inline_script( 'ksef-contractors-card', ob_get_clean() ); ?>
		<?php
	}

	/**
	 * Renderuje panel z fakturami danego kontrahenta (zakup/sprzedaż) — lista z
	 * podglądem + filtr okresu + raport sum (liczba, netto, VAT, brutto).
	 *
	 * @param string $type 'incoming' (zakup, kontrahent=sprzedawca) | 'outgoing' (sprzedaż, kontrahent=nabywca)
	 */
	private static function render_contractor_invoices( string $type, string $nip, string $name ): void {
		global $wpdb;
		$nip  = preg_replace( '/\D+/', '', $nip );
		$is_incoming = ( 'incoming' === $type );
		$table = $wpdb->prefix . ( $is_incoming ? 'gksef_incoming_invoices' : 'gksef_outgoing_invoices' );
		$nip_col  = $is_incoming ? 'seller_nip' : 'buyer_nip';
		$name_col = $is_incoming ? 'seller_name' : 'buyer_name';

		// Dopasowanie po NIP (gdy jest), inaczej po nazwie.
		if ( '' !== $nip ) {
			$where = $wpdb->prepare( "{$nip_col} = %s", $nip );
		} elseif ( '' !== $name ) {
			$where = $wpdb->prepare( "{$name_col} = %s", $name );
		} else {
			$where = '0=1';
		}
		// Kolumna daty różni się między tabelami: incoming ma issue_date,
		// outgoing trzyma datę wystawienia w submission_timestamp. created_at = fallback.
		$date_expr = $is_incoming
			? 'COALESCE(NULLIF(issue_date,\'0000-00-00\'), DATE(created_at))'
			: 'COALESCE(DATE(submission_timestamp), DATE(created_at))';
		$rows = $wpdb->get_results( // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter -- nazwy tabel z $wpdb->prefix, wartosci przez $wpdb->prepare().
			"SELECT id, invoice_number, {$date_expr} AS d, net_amount, vat_amount, gross_amount, currency, payment_status, ksef_reference_number
			 FROM {$table} WHERE {$where} ORDER BY d DESC, id DESC",
			ARRAY_A
		);
		$rows = is_array( $rows ) ? $rows : [];

		$today   = gmdate( 'Y-m-d' );
		$y_start = gmdate( 'Y-01-01' );
		$m_start = gmdate( 'Y-m-01' );
		?>
		<div class="ksef-ctr-invoices">
			<div class="ksef-ctr-period">
				<div>
					<label><?php esc_html_e( 'Od', 'prostafaktura-ksef' ); ?></label>
					<input type="date" class="ctr-from" value="">
				</div>
				<div>
					<label><?php esc_html_e( 'Do', 'prostafaktura-ksef' ); ?></label>
					<input type="date" class="ctr-to" value="">
				</div>
				<div style="display:flex;gap:6px;align-self:flex-end;">
					<button type="button" class="button ctr-quick" data-from="<?php echo esc_attr( $m_start ); ?>" data-to="<?php echo esc_attr( $today ); ?>"><?php esc_html_e( 'Ten miesiąc', 'prostafaktura-ksef' ); ?></button>
					<button type="button" class="button ctr-quick" data-from="<?php echo esc_attr( $y_start ); ?>" data-to="<?php echo esc_attr( $today ); ?>"><?php esc_html_e( 'Ten rok', 'prostafaktura-ksef' ); ?></button>
					<button type="button" class="button ctr-quick" data-from="" data-to=""><?php esc_html_e( 'Wszystko', 'prostafaktura-ksef' ); ?></button>
				</div>
				<div class="ksef-ctr-sum">
					<div><div class="l"><?php esc_html_e( 'Faktur', 'prostafaktura-ksef' ); ?></div><div class="v sum-count">0</div></div>
					<div><div class="l"><?php esc_html_e( 'Netto', 'prostafaktura-ksef' ); ?></div><div class="v sum-net">0,00</div></div>
					<div><div class="l">VAT</div><div class="v sum-vat">0,00</div></div>
					<div><div class="l"><?php esc_html_e( 'Brutto', 'prostafaktura-ksef' ); ?></div><div class="v sum-gross">0,00</div></div>
				</div>
			</div>

			<?php if ( empty( $rows ) ) : ?>
				<div class="ksef-ctr-empty">
					<?php echo $is_incoming
						? esc_html__( 'Brak faktur zakupu od tego kontrahenta.', 'prostafaktura-ksef' )
						: esc_html__( 'Brak faktur sprzedaży dla tego kontrahenta.', 'prostafaktura-ksef' ); ?>
				</div>
			<?php else : ?>
				<table class="ksef-ctr-table">
					<thead><tr>
						<th><?php esc_html_e( 'Data', 'prostafaktura-ksef' ); ?></th>
						<th><?php esc_html_e( 'Numer', 'prostafaktura-ksef' ); ?></th>
						<th style="text-align:right"><?php esc_html_e( 'Netto', 'prostafaktura-ksef' ); ?></th>
						<th style="text-align:right">VAT</th>
						<th style="text-align:right"><?php esc_html_e( 'Brutto', 'prostafaktura-ksef' ); ?></th>
						<th><?php esc_html_e( 'Płatność', 'prostafaktura-ksef' ); ?></th>
						<th>KSeF</th>
						<th></th>
					</tr></thead>
					<tbody>
					<?php foreach ( $rows as $r ) :
						$d = (string) ( $r['d'] ?? '' );
						$cur = (string) ( $r['currency'] ?: 'PLN' );
						$pstat = (string) ( $r['payment_status'] ?? '' );
						$pay_label = 'paid' === $pstat ? 'Opłacona' : ( 'partial' === $pstat ? 'Częściowo' : 'Do zapłaty' );
						$pay_cls   = 'paid' === $pstat ? 'paid' : ( 'partial' === $pstat ? 'draft' : '' );
					?>
						<tr data-date="<?php echo esc_attr( $d ); ?>" data-net="<?php echo esc_attr( (string) (float) $r['net_amount'] ); ?>" data-vat="<?php echo esc_attr( (string) (float) $r['vat_amount'] ); ?>" data-gross="<?php echo esc_attr( (string) (float) $r['gross_amount'] ); ?>">
							<td><?php echo esc_html( $d ); ?></td>
							<td><?php echo esc_html( (string) ( $r['invoice_number'] ?: ( '#' . $r['id'] ) ) ); ?></td>
							<td class="amt"><?php echo esc_html( number_format_i18n( (float) $r['net_amount'], 2 ) ); ?></td>
							<td class="amt"><?php echo esc_html( number_format_i18n( (float) $r['vat_amount'], 2 ) ); ?></td>
							<td class="amt"><?php echo esc_html( number_format_i18n( (float) $r['gross_amount'], 2 ) . ' ' . $cur ); ?></td>
							<td><span class="status-pill <?php echo esc_attr( $pay_cls ); ?>"><?php echo esc_html( $pay_label ); ?></span></td>
							<td><?php echo ! empty( $r['ksef_reference_number'] ) ? '<span class="status-pill paid">W KSeF</span>' : '<span class="status-pill">—</span>'; ?></td>
							<td><button type="button" class="button button-small ksef-ctr-preview" data-id="<?php echo (int) $r['id']; ?>" data-type="<?php echo esc_attr( $type ); ?>">👁 <?php esc_html_e( 'Podgląd', 'prostafaktura-ksef' ); ?></button></td>
						</tr>
					<?php endforeach; ?>
					</tbody>
				</table>
			<?php endif; ?>
		</div>
		<?php
	}

	private static function collect_post(): array {
		return [
			'buyer_type'      => sanitize_text_field( wp_unslash( $_POST['buyer_type'] ?? 'pl_firm' ) ),
			'contractor_name' => sanitize_text_field( wp_unslash( $_POST['contractor_name'] ?? '' ) ),
			'contractor_nip'  => preg_replace( '/\D+/', '', (string) sanitize_text_field( wp_unslash( $_POST['contractor_nip'] ?? '' ) ) ),
			'vat_ue'          => sanitize_text_field( wp_unslash( $_POST['vat_ue'] ?? '' ) ),
			'nr_id'           => sanitize_text_field( wp_unslash( $_POST['nr_id'] ?? '' ) ),
			'country_code'    => strtoupper( substr( sanitize_text_field( wp_unslash( $_POST['country_code'] ?? 'PL' ) ), 0, 2 ) ),
			'street'          => sanitize_text_field( wp_unslash( $_POST['street'] ?? '' ) ),
			'street_number'   => sanitize_text_field( wp_unslash( $_POST['street_number'] ?? '' ) ),
			'postal_code'     => sanitize_text_field( wp_unslash( $_POST['postal_code'] ?? '' ) ),
			'city'            => sanitize_text_field( wp_unslash( $_POST['city'] ?? '' ) ),
			'email'           => sanitize_email( wp_unslash( $_POST['email'] ?? '' ) ),
			'phone'           => sanitize_text_field( wp_unslash( $_POST['phone'] ?? '' ) ),
			'customer_no'     => sanitize_text_field( wp_unslash( $_POST['customer_no'] ?? '' ) ),
			'notes'           => sanitize_textarea_field( wp_unslash( $_POST['notes'] ?? '' ) ),
		];
	}
}
