/* global bingocrAdmin */
( function () {
	'use strict';

	var cfg  = window.bingocrAdmin || {};
	var REST = cfg.restUrl || '';
	var i18n = cfg.i18n    || {};

	// ── API helper ───────────────────────────────────────────────────────

	function api( path, method, body ) {
		var opts = {
			method:  method || 'GET',
			headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': cfg.nonce },
		};
		if ( body ) { opts.body = JSON.stringify( body ); }
		return fetch( REST + path, opts ).then( function ( r ) {
			if ( r.status === 204 ) { return null; }
			return r.json().then( function ( json ) {
				if ( ! r.ok ) {
					var err = new Error( json.message || i18n.error );
					err.code       = json.code        || '';
					err.upgradeUrl = json.upgrade_url || '';
					throw err;
				}
				return json;
			} );
		} );
	}

	// Show a message that may contain an upgrade link.
	function msgHtml( selector, err ) {
		var el = document.querySelector( selector );
		if ( ! el ) { return; }
		el.style.color = '#c0392b';
		if ( err.upgradeUrl ) {
			el.innerHTML = esc( err.message ) + ' <a href="' + esc( err.upgradeUrl ) + '" target="_blank" style="color:#c0392b;text-decoration:underline">' + esc( i18n.upgrade_pro ) + '</a>';
		} else {
			el.textContent = err.message;
		}
	}

	function esc( v ) {
		var d = document.createElement( 'div' );
		d.appendChild( document.createTextNode( String( v == null ? '' : v ) ) );
		return d.innerHTML;
	}

	function show( id ) { var e = document.getElementById( id ); if ( e ) e.style.display = ''; }
	function hide( id ) { var e = document.getElementById( id ); if ( e ) e.style.display = 'none'; }
	function msg( sel, text, ok ) {
		var e = document.querySelector( sel );
		if ( e ) {
			e.textContent  = text;
			e.style.color  = ok ? '#27ae60' : '#c0392b';
		}
	}

	// ── Dashboard stats ──────────────────────────────────────────────────

	if ( document.getElementById( 'bingocr-dashboard-stats' ) ) {
		api( 'admin/dashboard' ).then( function ( d ) {
			document.getElementById( 'stat-cars' ).textContent         = d.total_cars;
			document.getElementById( 'stat-reservations' ).textContent = d.total_reservations;
			document.getElementById( 'stat-pending' ).textContent      = d.pending;
			var sym = ( cfg.settings && cfg.settings.currency_symbol ) || '€';
			var pos = ( cfg.settings && cfg.settings.currency_position ) || 'before';
			var rev = parseFloat( d.revenue ).toFixed( 2 );
			document.getElementById( 'stat-revenue' ).textContent = pos === 'before' ? sym + rev : rev + sym;
		} ).catch( function () {} );
	}

	// ── Cars page ────────────────────────────────────────────────────────

	if ( document.getElementById( 'bingocr-cars-app' ) ) {
		var carsData = [];

		function renderCarsList() {
			var html = '';
			if ( ! carsData.length ) {
				html = '<p>' + esc( i18n.no_cars ) + '</p>';
			} else {
				html = '<table class="wp-list-table widefat fixed striped">';
				html += '<thead><tr><th>' + esc( i18n.photo ) + '</th><th>' + esc( i18n.vehicle ) + '</th><th>' + esc( i18n.category ) + '</th><th>' + esc( i18n.price_day ) + '</th><th>' + esc( i18n.qty ) + '</th><th>' + esc( i18n.status ) + '</th><th>' + esc( i18n.actions ) + '</th></tr></thead><tbody>';
				carsData.forEach( function ( car ) {
					var img = car.image_url
						? '<img src="' + esc( car.image_url ) + '" style="width:60px;height:40px;object-fit:cover;border-radius:3px">'
						: '—';
					html += '<tr data-id="' + esc( car.id ) + '">';
					html += '<td>' + img + '</td>';
					html += '<td><strong>' + esc( car.brand ) + ' ' + esc( car.model ) + '</strong> <small>(' + esc( car.year || '' ) + ')</small></td>';
					html += '<td>' + esc( car.category ) + '</td>';
					html += '<td>' + esc( car.price_per_day ) + '</td>';
					html += '<td>' + esc( car.quantity ) + '</td>';
					html += '<td><span class="bcr-status bcr-status-' + esc( car.status ) + '">' + esc( car.status ) + '</span></td>';
					html += '<td>';
					html += '<button class="button button-small bcr-edit-car" data-id="' + esc( car.id ) + '">' + esc( i18n.edit ) + '</button> ';
					html += '<button class="button button-small bcr-del-car" data-id="' + esc( car.id ) + '" style="color:#c0392b">' + esc( i18n.delete ) + '</button>';
					html += '</td></tr>';
				} );
				html += '</tbody></table>';
			}
			document.getElementById( 'bingocr-cars-list' ).innerHTML = html;
			bindCarActions();
		}

		function loadCars() {
			api( 'admin/cars' ).then( function ( data ) {
				carsData = data;
				renderCarsList();
			} );
		}

		function toggleDepositValue() {
			var type  = document.getElementById( 'car-deposit-type' ).value;
			var wrap  = document.getElementById( 'car-deposit-value-wrap' );
			var hint1 = document.getElementById( 'car-deposit-default-hint' );
			var hint2 = document.getElementById( 'car-deposit-value-hint' );
			if ( type === 'default' ) {
				wrap.style.display = 'none';
				if ( hint1 ) {
					var def = parseFloat( ( cfg.settings && cfg.settings.default_deposit ) || 0 );
					hint1.textContent = i18n.global_default + ' ' + def.toFixed( 2 );
				}
			} else {
				wrap.style.display = '';
				if ( hint1 ) { hint1.textContent = ''; }
				if ( hint2 ) {
					hint2.textContent = type === 'percentage' ? i18n.pct_hint : i18n.flat_hint;
				}
			}
		}

		document.getElementById( 'car-deposit-type' ).addEventListener( 'change', toggleDepositValue );

		function openCarForm( car ) {
			var form  = document.getElementById( 'bingocr-car-form' );
			var title = document.getElementById( 'bingocr-car-form-title' );
			title.textContent = car ? i18n.edit_car : i18n.add_car;
			document.getElementById( 'car-id' ).value = car ? car.id : '';

			var fields = [ 'brand', 'model', 'year', 'category', 'transmission', 'fuel_type', 'seats', 'price_per_day', 'quantity', 'status', 'description' ];
			fields.forEach( function ( f ) {
				var el = form.querySelector( '[name="' + f + '"]' );
				if ( el ) { el.value = car ? ( car[ f ] || '' ) : ''; }
			} );

			var dtEl = form.querySelector( '[name="deposit_type"]' );
			var dvEl = form.querySelector( '[name="deposit_value"]' );
			if ( dtEl ) { dtEl.value = car ? ( car.deposit_type || 'default' ) : 'default'; }
			if ( dvEl ) { dvEl.value = car ? ( car.deposit_value || '0' ) : '0'; }
			toggleDepositValue();

			var tiersSection = document.getElementById( 'bingocr-car-tiers-section' );
			var tiersHeader  = document.getElementById( 'bingocr-car-tiers-header' );
			if ( car ) {
				tiersSection.style.display = '';
				loadCarTiers( car.id );
			} else {
				tiersSection.style.display = 'none';
				tiersHeader.style.display  = 'none';
				document.getElementById( 'bingocr-car-tiers-body' ).innerHTML = '';
				carTiersCache = [];
			}

			var featEl = form.querySelector( '[name="features_raw"]' );
			if ( featEl ) {
				featEl.value = car && car.features ? ( Array.isArray( car.features ) ? car.features.join( ', ' ) : car.features ) : '';
			}

			document.getElementById( 'car-image-id' ).value  = car && car.image_id  ? car.image_id  : '';
			document.getElementById( 'car-image-url' ).value = car && car.image_url ? car.image_url : '';
			var preview = document.getElementById( 'car-image-preview' );
			if ( car && car.image_url ) {
				preview.src          = car.image_url;
				preview.style.display = 'inline-block';
			} else {
				preview.src           = '';
				preview.style.display = 'none';
			}

			document.querySelector( '.bingocr-form-message' ) && ( document.querySelector( '.bingocr-form-message' ).textContent = '' );
			show( 'bingocr-car-form-wrap' );
		}

		var carTiersCache = [];

		function loadCarTiers( carId ) {
			api( 'admin/period-pricing' ).then( function ( rules ) {
				carTiersCache = rules.filter( function ( r ) {
					return r.applies_to === 'car'
						&& String( r.car_id ) === String( carId )
						&& r.pricing_type === 'rate_per_day';
				} );
				var body   = document.getElementById( 'bingocr-car-tiers-body' );
				var header = document.getElementById( 'bingocr-car-tiers-header' );
				body.innerHTML = '';
				carTiersCache.forEach( function ( t ) { addCarTierRow( t ); } );
				header.style.display = carTiersCache.length ? '' : 'none';
			} );
		}

		function addCarTierRow( tier ) {
			var body   = document.getElementById( 'bingocr-car-tiers-body' );
			var header = document.getElementById( 'bingocr-car-tiers-header' );
			var sym    = ( cfg.settings && cfg.settings.currency_symbol ) || '';
			var div    = document.createElement( 'div' );
			div.className      = 'bcr-tier-row';
			div.dataset.tierId = tier ? ( tier.id || '' ) : '';
			div.innerHTML =
				'<div><label>' + esc( i18n.from_day ) + '</label><input type="number" class="bcr-tier-min small-text" min="1" value="' + esc( tier ? tier.min_days : 1 ) + '"></div>' +
				'<div><label>' + esc( i18n.to_day ) + '</label><input type="number" class="bcr-tier-max small-text" min="1" value="' + esc( tier ? tier.max_days : 7 ) + '"></div>' +
				'<div><label>' + esc( sym ) + '/day</label><input type="number" class="bcr-tier-rate small-text" step="0.01" min="0" value="' + esc( tier ? parseFloat( tier.price_per_day ).toFixed( 2 ) : '0.00' ) + '"></div>' +
				'<div style="padding-bottom:1px"><button type="button" class="button" style="padding:0 8px;min-height:28px;line-height:1" title="' + esc( i18n.remove_tier ) + '">&times;</button></div>';
			div.querySelector( 'button' ).addEventListener( 'click', function () {
				div.remove();
				if ( ! document.querySelectorAll( '#bingocr-car-tiers-body .bcr-tier-row' ).length ) {
					header.style.display = 'none';
				}
			} );
			header.style.display = '';
			body.appendChild( div );
		}

		function saveCarTiers( carId ) {
			// Scope to the body — the column-labels header also has .bcr-tier-row.
			var rows    = document.querySelectorAll( '#bingocr-car-tiers-body .bcr-tier-row' );
			var desired = Array.from( rows ).map( function ( row ) {
				return {
					id:            row.dataset.tierId || null,
					min_days:      parseInt( row.querySelector( '.bcr-tier-min' ).value ) || 1,
					max_days:      parseInt( row.querySelector( '.bcr-tier-max' ).value ) || 7,
					price_per_day: parseFloat( row.querySelector( '.bcr-tier-rate' ).value ) || 0,
				};
			} );

			var desiredIds  = desired.filter( function ( d ) { return d.id; } ).map( function ( d ) { return String( d.id ); } );
			var deleteProms = carTiersCache
				.filter( function ( t ) { return ! desiredIds.includes( String( t.id ) ); } )
				.map( function ( t ) { return api( 'admin/period-pricing/' + t.id, 'DELETE' ); } );

			var saveProms = desired.map( function ( t ) {
				var payload = {
					name:          'Car #' + carId + ' (' + t.min_days + '–' + t.max_days + 'd)',
					pricing_type:  'rate_per_day',
					min_days:      t.min_days,
					max_days:      t.max_days,
					price_per_day: t.price_per_day,
					fixed_price:   0,
					applies_to:    'car',
					car_id:        carId,
					priority:      10,
					status:        'active',
				};
				return t.id
					? api( 'admin/period-pricing/' + t.id, 'PUT', payload )
					: api( 'admin/period-pricing', 'POST', payload );
			} );

			return Promise.all( deleteProms.concat( saveProms ) );
		}

		document.getElementById( 'bingocr-add-tier' ).addEventListener( 'click', function () {
			addCarTierRow( null );
		} );

		function bindCarActions() {
			document.querySelectorAll( '.bcr-edit-car' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					var car = carsData.find( function ( c ) { return c.id == btn.dataset.id; } );
					openCarForm( car );
				} );
			} );
			document.querySelectorAll( '.bcr-del-car' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					if ( ! window.confirm( i18n.confirm_delete ) ) { return; }
					api( 'admin/cars/' + btn.dataset.id, 'DELETE' ).then( loadCars );
				} );
			} );
		}

		document.getElementById( 'bingocr-add-car' ).addEventListener( 'click', function () {
			openCarForm( null );
		} );
		document.getElementById( 'bingocr-cancel-car' ).addEventListener( 'click', function () {
			hide( 'bingocr-car-form-wrap' );
		} );

		// WP Media uploader.
		document.getElementById( 'bingocr-select-image' ).addEventListener( 'click', function () {
			if ( ! window.wp || ! window.wp.media ) { return; }
			var frame = window.wp.media( {
				title:    i18n.select_image,
				button:   { text: i18n.use_image },
				multiple: false,
				library:  { type: 'image' },
			} );
			frame.on( 'select', function () {
				var att = frame.state().get( 'selection' ).first().toJSON();
				document.getElementById( 'car-image-id' ).value  = att.id;
				document.getElementById( 'car-image-url' ).value = att.url;
				var prev = document.getElementById( 'car-image-preview' );
				prev.src           = att.url;
				prev.style.display = 'inline-block';
			} );
			frame.open();
		} );

		document.getElementById( 'bingocr-car-form' ).addEventListener( 'submit', function ( e ) {
			e.preventDefault();
			var form    = e.target;
			var id      = document.getElementById( 'car-id' ).value;
			var featRaw = form.querySelector( '[name="features_raw"]' ).value;
			var data    = {
				brand:         form.querySelector( '[name="brand"]' ).value,
				model:         form.querySelector( '[name="model"]' ).value,
				year:          parseInt( form.querySelector( '[name="year"]' ).value ) || null,
				category:      form.querySelector( '[name="category"]' ).value,
				transmission:  form.querySelector( '[name="transmission"]' ).value,
				fuel_type:     form.querySelector( '[name="fuel_type"]' ).value,
				seats:         parseInt( form.querySelector( '[name="seats"]' ).value ) || 5,
				price_per_day: parseFloat( form.querySelector( '[name="price_per_day"]' ).value ) || 0,
				quantity:      parseInt( form.querySelector( '[name="quantity"]' ).value ) || 1,
				status:        form.querySelector( '[name="status"]' ).value,
				description:   form.querySelector( '[name="description"]' ).value,
				deposit_type:  form.querySelector( '[name="deposit_type"]' ).value,
				deposit_value: parseFloat( form.querySelector( '[name="deposit_value"]' ).value ) || 0,
				image_id:      parseInt( document.getElementById( 'car-image-id' ).value ) || null,
				image_url:     document.getElementById( 'car-image-url' ).value,
				features:      featRaw ? featRaw.split( ',' ).map( function ( s ) { return s.trim(); } ).filter( Boolean ) : [],
			};
			var call = id ? api( 'admin/cars/' + id, 'PUT', data ) : api( 'admin/cars', 'POST', data );
			call.then( function ( savedCar ) {
				var savedId = parseInt( savedCar ? ( savedCar.id || id ) : id );
				return saveCarTiers( savedId );
			} ).then( function () {
				hide( 'bingocr-car-form-wrap' );
				loadCars();
			} ).catch( function ( err ) {
				msgHtml( '#bingocr-car-form .bingocr-form-message', err );
			} );
		} );

		loadCars();
	}

	// ── Reservations page ────────────────────────────────────────────────

	if ( document.getElementById( 'bingocr-reservations-list' ) ) {
		var currentResId = null;

		function loadReservations() {
			var status = document.getElementById( 'bingocr-res-filter' ).value;
			var search = document.getElementById( 'bingocr-res-search' ).value;
			var qs     = 'status=' + encodeURIComponent( status ) + '&search=' + encodeURIComponent( search );
			api( 'admin/reservations?' + qs ).then( renderReservations );
		}

		function renderReservations( list ) {
			var html = '<table class="wp-list-table widefat fixed striped">';
			html += '<thead><tr><th>' + esc( i18n.ref ) + '</th><th>' + esc( i18n.customer ) + '</th><th>' + esc( i18n.vehicle ) + '</th><th>' + esc( i18n.pickup ) + '</th><th>' + esc( i18n.return ) + '</th><th>' + esc( i18n.total ) + '</th><th>' + esc( i18n.status ) + '</th><th></th></tr></thead><tbody>';
			if ( ! list.length ) {
				html = '<p>' + esc( i18n.no_reservations ) + '</p>';
				document.getElementById( 'bingocr-reservations-list' ).innerHTML = html;
				return;
			}
			list.forEach( function ( r ) {
				html += '<tr>';
				html += '<td><strong>' + esc( r.reservation_number ) + '</strong></td>';
				html += '<td>' + esc( r.customer_name ) + '<br><small>' + esc( r.customer_email ) + '</small></td>';
				html += '<td>' + esc( r.brand + ' ' + r.model ) + '</td>';
				html += '<td>' + esc( r.pickup_date ) + '</td>';
				html += '<td>' + esc( r.return_date ) + '</td>';
				html += '<td>' + esc( r.total_price ) + '</td>';
				html += '<td><span class="bcr-status bcr-status-' + esc( r.status ) + '">' + esc( r.status ) + '</span>';
				if ( r.payment_status === 'paid' ) {
					html += ' <span class="bcr-status bcr-status-available">' + esc( i18n.paid ) + '</span>';
				}
				html += '</td>';
				html += '<td><button class="button button-small bcr-view-res" data-id="' + esc( r.id ) + '" data-status="' + esc( r.status ) + '">' + esc( i18n.view ) + '</button></td>';
				html += '</tr>';
			} );
			html += '</tbody></table>';
			document.getElementById( 'bingocr-reservations-list' ).innerHTML = html;

			document.querySelectorAll( '.bcr-view-res' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					currentResId = btn.dataset.id;
					document.getElementById( 'bingocr-res-status-select' ).value = btn.dataset.status;
					var tr = btn.closest( 'tr' );
					var detail = '<table class="widefat">';
					tr.querySelectorAll( 'td' ).forEach( function ( td, i ) {
						if ( i < 6 ) { detail += '<tr><td>' + esc( [ i18n.reference, i18n.customer, i18n.vehicle, i18n.pickup, i18n.return, i18n.total ][ i ] ) + '</td><td>' + td.innerHTML + '</td></tr>'; }
					} );
					detail += '</table><div id="bingocr-res-payment"></div>';
					document.getElementById( 'bingocr-res-detail' ).innerHTML = detail;
					show( 'bingocr-res-modal-wrap' );
					loadReservationPayment( currentResId );
				} );
			} );
		}

		function loadReservationPayment( id ) {
			var wrap = document.getElementById( 'bingocr-res-payment' );
			if ( wrap ) { wrap.innerHTML = ''; }
			api( 'admin/reservations/' + id + '/payment' ).then( function ( p ) {
				if ( ! p || ! wrap ) { return; }
				var sym  = ( cfg.settings && cfg.settings.currency_symbol ) || '';
				var rows = '';
				function row( label, value ) {
					if ( value === null || value === undefined || value === '' ) { return; }
					rows += '<tr><td>' + esc( label ) + '</td><td>' + esc( value ) + '</td></tr>';
				}
				row( i18n.pay_method, ( i18n[ 'pay_' + p.method ] || p.method ) );
				row( i18n.pay_status, ( p.status === 'completed' ? i18n.paid : p.status ) );
				if ( p.amount )   { row( i18n.pay_amount, sym + parseFloat( p.amount ).toFixed( 2 ) ); }
				if ( p.fee )      { row( i18n.pay_fee, sym + parseFloat( p.fee ).toFixed( 2 ) ); }
				if ( p.net )      { row( i18n.pay_net, sym + parseFloat( p.net ).toFixed( 2 ) ); }
				row( i18n.pay_txn, p.capture_id );
				row( i18n.pay_order, p.order_id );
				row( i18n.pay_payer, p.payer_email );
				row( i18n.pay_date, p.completed_at );
				wrap.innerHTML =
					'<h3 style="margin:16px 0 6px;font-size:13px;text-transform:uppercase;letter-spacing:.06em;color:#6b7280">' +
					esc( i18n.payment_details ) + '</h3>' +
					'<table class="widefat">' + rows + '</table>';
			} ).catch( function () {} );
		}

		document.getElementById( 'bingocr-res-save' ).addEventListener( 'click', function () {
			if ( ! currentResId ) { return; }
			var status = document.getElementById( 'bingocr-res-status-select' ).value;
			api( 'admin/reservations/' + currentResId, 'PUT', { status: status } ).then( function () {
				hide( 'bingocr-res-modal-wrap' );
				loadReservations();
			} );
		} );

		document.getElementById( 'bingocr-res-close' ).addEventListener( 'click', function () {
			hide( 'bingocr-res-modal-wrap' );
		} );
		document.getElementById( 'bingocr-res-refresh' ).addEventListener( 'click', loadReservations );

		var searchTimer;
		document.getElementById( 'bingocr-res-search' ).addEventListener( 'input', function () {
			clearTimeout( searchTimer );
			searchTimer = setTimeout( loadReservations, 400 );
		} );
		document.getElementById( 'bingocr-res-filter' ).addEventListener( 'change', loadReservations );

		loadReservations();
	}

	// ── Locations page ───────────────────────────────────────────────────

	if ( document.getElementById( 'bingocr-locations-list' ) ) {
		var locsData = [];

		function loadLocations() {
			api( 'admin/locations' ).then( function ( data ) {
				locsData = data;
				renderLocations();
			} );
		}

		function renderLocations() {
			var html = '<table class="wp-list-table widefat fixed striped"><thead><tr><th>' + esc( i18n.name ) + '</th><th>' + esc( i18n.city ) + '</th><th>' + esc( i18n.phone ) + '</th><th>' + esc( i18n.hours ) + '</th><th>' + esc( i18n.status ) + '</th><th></th></tr></thead><tbody>';
			locsData.forEach( function ( loc ) {
				html += '<tr><td>' + esc( loc.name ) + '</td><td>' + esc( loc.city ) + '</td><td>' + esc( loc.phone ) + '</td><td>' + esc( loc.opening_hours ) + '</td>';
				html += '<td>' + esc( loc.status ) + '</td>';
				html += '<td><button class="button button-small bcr-edit-loc" data-id="' + esc( loc.id ) + '">' + esc( i18n.edit ) + '</button> <button class="button button-small bcr-del-loc" data-id="' + esc( loc.id ) + '" style="color:#c0392b">' + esc( i18n.delete ) + '</button></td></tr>';
			} );
			html += '</tbody></table>';
			document.getElementById( 'bingocr-locations-list' ).innerHTML = html;
			document.querySelectorAll( '.bcr-edit-loc' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					var loc = locsData.find( function ( l ) { return l.id == btn.dataset.id; } );
					openLocForm( loc );
				} );
			} );
			document.querySelectorAll( '.bcr-del-loc' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					if ( ! window.confirm( i18n.confirm_delete ) ) { return; }
					api( 'admin/locations/' + btn.dataset.id, 'DELETE' ).then( loadLocations );
				} );
			} );
		}

		function openLocForm( loc ) {
			document.getElementById( 'loc-id' ).value = loc ? loc.id : '';
			document.getElementById( 'bingocr-loc-form-title' ).textContent = loc ? i18n.edit_location : i18n.add_location;
			[ 'name', 'address', 'city', 'phone', 'email', 'opening_hours', 'status' ].forEach( function ( f ) {
				var el = document.querySelector( '#bingocr-location-form [name="' + f + '"]' );
				if ( el ) { el.value = loc ? ( loc[ f ] || '' ) : ( f === 'status' ? 'active' : '' ); }
			} );
			show( 'bingocr-location-form-wrap' );
		}

		document.getElementById( 'bingocr-add-location' ).addEventListener( 'click', function () { openLocForm( null ); } );
		document.getElementById( 'bingocr-cancel-location' ).addEventListener( 'click', function () { hide( 'bingocr-location-form-wrap' ); } );

		document.getElementById( 'bingocr-location-form' ).addEventListener( 'submit', function ( e ) {
			e.preventDefault();
			var form = e.target;
			var id   = document.getElementById( 'loc-id' ).value;
			var data = {};
			[ 'name', 'address', 'city', 'phone', 'email', 'opening_hours', 'status' ].forEach( function ( f ) {
				data[ f ] = form.querySelector( '[name="' + f + '"]' ).value;
			} );
			var call = id ? api( 'admin/locations/' + id, 'PUT', data ) : api( 'admin/locations', 'POST', data );
			call.then( function () { hide( 'bingocr-location-form-wrap' ); loadLocations(); } )
				.catch( function ( err ) { msgHtml( '#bingocr-location-form .bingocr-form-message', err ); } );
		} );

		loadLocations();
	}

	// ── Extras page ──────────────────────────────────────────────────────

	if ( document.getElementById( 'bingocr-extras-list' ) ) {
		var extrasData = [];

		function loadExtras() {
			api( 'admin/extras' ).then( function ( data ) { extrasData = data; renderExtras(); } );
		}

		function renderExtras() {
			var html = '<table class="wp-list-table widefat fixed striped"><thead><tr><th>' + esc( i18n.name ) + '</th><th>' + esc( i18n.price ) + '</th><th>' + esc( i18n.type ) + '</th><th>' + esc( i18n.status ) + '</th><th></th></tr></thead><tbody>';
			extrasData.forEach( function ( x ) {
				html += '<tr><td>' + esc( x.name ) + '</td><td>' + esc( x.price ) + '</td><td>' + esc( x.price_type ) + '</td><td>' + esc( x.status ) + '</td>';
				html += '<td><button class="button button-small bcr-edit-extra" data-id="' + esc( x.id ) + '">' + esc( i18n.edit ) + '</button> <button class="button button-small bcr-del-extra" data-id="' + esc( x.id ) + '" style="color:#c0392b">' + esc( i18n.delete ) + '</button></td></tr>';
			} );
			html += '</tbody></table>';
			document.getElementById( 'bingocr-extras-list' ).innerHTML = html;
			document.querySelectorAll( '.bcr-edit-extra' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					var x = extrasData.find( function ( e ) { return e.id == btn.dataset.id; } );
					openExtraForm( x );
				} );
			} );
			document.querySelectorAll( '.bcr-del-extra' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					if ( ! window.confirm( i18n.confirm_delete ) ) { return; }
					api( 'admin/extras/' + btn.dataset.id, 'DELETE' ).then( loadExtras );
				} );
			} );
		}

		function openExtraForm( x ) {
			document.getElementById( 'extra-id' ).value = x ? x.id : '';
			document.getElementById( 'bingocr-extra-form-title' ).textContent = x ? i18n.edit_extra : i18n.add_extra;
			[ 'name', 'description', 'price', 'price_type', 'status' ].forEach( function ( f ) {
				var el = document.querySelector( '#bingocr-extra-form [name="' + f + '"]' );
				if ( el ) { el.value = x ? ( x[ f ] || '' ) : ( f === 'status' ? 'active' : f === 'price_type' ? 'per_day' : '' ); }
			} );
			show( 'bingocr-extra-form-wrap' );
		}

		document.getElementById( 'bingocr-add-extra' ).addEventListener( 'click', function () { openExtraForm( null ); } );
		document.getElementById( 'bingocr-cancel-extra' ).addEventListener( 'click', function () { hide( 'bingocr-extra-form-wrap' ); } );

		document.getElementById( 'bingocr-extra-form' ).addEventListener( 'submit', function ( e ) {
			e.preventDefault();
			var form = e.target;
			var id   = document.getElementById( 'extra-id' ).value;
			var data = {};
			[ 'name', 'description', 'price_type', 'status' ].forEach( function ( f ) {
				data[ f ] = form.querySelector( '[name="' + f + '"]' ).value;
			} );
			data.price = parseFloat( form.querySelector( '[name="price"]' ).value ) || 0;
			var call = id ? api( 'admin/extras/' + id, 'PUT', data ) : api( 'admin/extras', 'POST', data );
			call.then( function () { hide( 'bingocr-extra-form-wrap' ); loadExtras(); } )
				.catch( function ( err ) { msgHtml( '#bingocr-extra-form .bingocr-form-message', err ); } );
		} );

		loadExtras();
	}

	// ── Pricing page ─────────────────────────────────────────────────────

	if ( document.getElementById( 'bingocr-seasonal-list' ) ) {
		var seasonalData = [];
		var periodData   = [];

		// ── Seasonal ──────────────────────────────────────────────────────

		function loadSeasonal() {
			api( 'admin/seasonal-prices' ).then( function ( data ) {
				seasonalData = data;
				renderSeasonal();
			} );
		}

		function renderSeasonal() {
			var wrap = document.getElementById( 'bingocr-seasonal-list' );
			if ( ! seasonalData.length ) {
				wrap.innerHTML = '<p class="bingocr-empty">' + esc( i18n.no_seasonal ) + '</p>';
				return;
			}
			var html = '<table class="bingocr-table"><thead><tr>';
			html += '<th>' + esc( i18n.name ) + '</th><th>' + esc( i18n.period ) + '</th><th>' + esc( i18n.modifier ) + '</th><th>' + esc( i18n.applies_to ) + '</th><th>' + esc( i18n.priority ) + '</th><th>' + esc( i18n.status ) + '</th><th></th>';
			html += '</tr></thead><tbody>';
			seasonalData.forEach( function ( s ) {
				var mod  = parseFloat( s.modifier );
				var cls  = mod > 0 ? 'bcr-modifier-up' : ( mod < 0 ? 'bcr-modifier-down' : 'bcr-modifier-zero' );
				var str  = ( mod > 0 ? '+' : '' ) + mod.toFixed( 2 ) + '%';
				var apl  = s.applies_to === 'category' ? esc( i18n.category_prefix ) + ' ' + esc( s.category ) : esc( i18n.all_cars );
				html += '<tr>';
				html += '<td><strong>' + esc( s.name ) + '</strong></td>';
				html += '<td>' + esc( s.start_date ) + ' &rarr; ' + esc( s.end_date ) + '</td>';
				html += '<td><span class="' + cls + '">' + str + '</span></td>';
				html += '<td>' + apl + '</td>';
				html += '<td>' + esc( s.priority ) + '</td>';
				html += '<td><span class="bcr-status bcr-status-' + esc( s.status ) + '">' + esc( s.status ) + '</span></td>';
				html += '<td><button class="button button-small bcr-edit-seasonal" data-id="' + esc( s.id ) + '">' + esc( i18n.edit ) + '</button> ';
				html += '<button class="button button-small bcr-del-seasonal" data-id="' + esc( s.id ) + '" style="color:#c0392b">' + esc( i18n.delete ) + '</button></td>';
				html += '</tr>';
			} );
			html += '</tbody></table>';
			wrap.innerHTML = html;

			document.querySelectorAll( '.bcr-edit-seasonal' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					var s = seasonalData.find( function ( x ) { return x.id == btn.dataset.id; } );
					openSeasonalForm( s );
				} );
			} );
			document.querySelectorAll( '.bcr-del-seasonal' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					if ( ! window.confirm( i18n.confirm_delete ) ) { return; }
					api( 'admin/seasonal-prices/' + btn.dataset.id, 'DELETE' ).then( loadSeasonal );
				} );
			} );
		}

		function openSeasonalForm( s ) {
			document.getElementById( 'seasonal-id' ).value = s ? s.id : '';
			document.getElementById( 'bingocr-seasonal-form-title' ).textContent = s ? i18n.edit_season : i18n.add_season;
			var form = document.getElementById( 'bingocr-seasonal-form' );
			[ 'name', 'start_date', 'end_date', 'modifier', 'applies_to', 'category', 'priority', 'status' ].forEach( function ( f ) {
				var el = form.querySelector( '[name="' + f + '"]' );
				if ( el ) { el.value = s ? ( s[ f ] != null ? s[ f ] : '' ) : ( f === 'status' ? 'active' : f === 'applies_to' ? 'all' : f === 'modifier' || f === 'priority' ? '0' : '' ); }
			} );
			toggleSeasonalCategory();
			form.querySelector( '.bingocr-form-message' ).textContent = '';
			show( 'bingocr-seasonal-form-wrap' );
		}

		function toggleSeasonalCategory() {
			var val = document.getElementById( 'seasonal-applies-to' ).value;
			document.getElementById( 'seasonal-category-wrap' ).style.display = val === 'category' ? '' : 'none';
		}

		document.getElementById( 'seasonal-applies-to' ).addEventListener( 'change', toggleSeasonalCategory );
		document.getElementById( 'bingocr-add-seasonal' ).addEventListener( 'click', function () { openSeasonalForm( null ); } );
		document.getElementById( 'bingocr-cancel-seasonal' ).addEventListener( 'click', function () { hide( 'bingocr-seasonal-form-wrap' ); } );

		document.getElementById( 'bingocr-seasonal-form' ).addEventListener( 'submit', function ( e ) {
			e.preventDefault();
			var form = e.target;
			var id   = document.getElementById( 'seasonal-id' ).value;
			var data = {};
			[ 'name', 'start_date', 'end_date', 'applies_to', 'category', 'status' ].forEach( function ( f ) {
				data[ f ] = form.querySelector( '[name="' + f + '"]' ).value;
			} );
			data.modifier  = parseFloat( form.querySelector( '[name="modifier"]' ).value ) || 0;
			data.priority  = parseInt( form.querySelector( '[name="priority"]' ).value ) || 0;
			var call = id
				? api( 'admin/seasonal-prices/' + id, 'PUT', data )
				: api( 'admin/seasonal-prices', 'POST', data );
			call.then( function () { hide( 'bingocr-seasonal-form-wrap' ); loadSeasonal(); } )
				.catch( function ( err ) { msgHtml( '#bingocr-seasonal-form .bingocr-form-message', err ); } );
		} );

		// ── Period pricing ────────────────────────────────────────────────

		function loadPeriod() {
			api( 'admin/period-pricing' ).then( function ( data ) {
				periodData = data;
				renderPeriod();
			} );
		}

		function renderPeriod() {
			var wrap = document.getElementById( 'bingocr-period-list' );
			if ( ! periodData.length ) {
				wrap.innerHTML = '<p class="bingocr-empty">' + esc( i18n.no_period ) + '</p>';
				return;
			}
			var html = '<table class="bingocr-table"><thead><tr>';
			html += '<th>' + esc( i18n.name ) + '</th><th>' + esc( i18n.day_range ) + '</th><th>' + esc( i18n.type ) + '</th><th>' + esc( i18n.price ) + '</th><th>' + esc( i18n.applies_to ) + '</th><th>' + esc( i18n.priority ) + '</th><th>' + esc( i18n.status ) + '</th><th></th>';
			html += '</tr></thead><tbody>';
			var sym = ( cfg.settings && cfg.settings.currency_symbol ) || '';
			periodData.forEach( function ( p ) {
				var typeStr  = p.pricing_type === 'fixed_total' ? esc( i18n.fixed_total ) : esc( i18n.rate_day );
				var priceStr = p.pricing_type === 'fixed_total'
					? sym + parseFloat( p.fixed_price ).toFixed( 2 )
					: sym + parseFloat( p.price_per_day ).toFixed( 2 ) + i18n.per_day;
				var apl = p.applies_to === 'category' ? esc( i18n.category_prefix ) + ' ' + esc( p.category )
					: ( p.applies_to === 'car' ? esc( i18n.car_hash ) + esc( p.car_id ) : esc( i18n.all_cars ) );
				html += '<tr>';
				html += '<td><strong>' + esc( p.name ) + '</strong></td>';
				html += '<td>' + esc( p.min_days ) + '–' + esc( p.max_days ) + ' ' + esc( i18n.days ) + '</td>';
				html += '<td>' + typeStr + '</td>';
				html += '<td>' + esc( priceStr ) + '</td>';
				html += '<td>' + apl + '</td>';
				html += '<td>' + esc( p.priority ) + '</td>';
				html += '<td><span class="bcr-status bcr-status-' + esc( p.status ) + '">' + esc( p.status ) + '</span></td>';
				html += '<td><button class="button button-small bcr-edit-period" data-id="' + esc( p.id ) + '">' + esc( i18n.edit ) + '</button> ';
				html += '<button class="button button-small bcr-del-period" data-id="' + esc( p.id ) + '" style="color:#c0392b">' + esc( i18n.delete ) + '</button></td>';
				html += '</tr>';
			} );
			html += '</tbody></table>';
			wrap.innerHTML = html;

			document.querySelectorAll( '.bcr-edit-period' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					var p = periodData.find( function ( x ) { return x.id == btn.dataset.id; } );
					openPeriodForm( p );
				} );
			} );
			document.querySelectorAll( '.bcr-del-period' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					if ( ! window.confirm( i18n.confirm_delete ) ) { return; }
					api( 'admin/period-pricing/' + btn.dataset.id, 'DELETE' ).then( loadPeriod );
				} );
			} );
		}

		function openPeriodForm( p ) {
			document.getElementById( 'period-id' ).value = p ? p.id : '';
			document.getElementById( 'bingocr-period-form-title' ).textContent = p ? i18n.edit_period : i18n.add_period;
			var form = document.getElementById( 'bingocr-period-form' );
			[ 'name', 'min_days', 'max_days', 'fixed_price', 'price_per_day', 'applies_to', 'category', 'priority', 'status' ].forEach( function ( f ) {
				var el = form.querySelector( '[name="' + f + '"]' );
				if ( el ) { el.value = p ? ( p[ f ] != null ? p[ f ] : '' ) : ( f === 'status' ? 'active' : f === 'applies_to' ? 'all' : f === 'min_days' ? '3' : f === 'max_days' ? '7' : '0' ); }
			} );
			var typeVal = p ? p.pricing_type : 'rate_per_day';
			form.querySelectorAll( '[name="pricing_type"]' ).forEach( function ( r ) { r.checked = r.value === typeVal; } );
			togglePeriodType();
			togglePeriodScope();
			form.querySelector( '.bingocr-form-message' ).textContent = '';

			// Populate car dropdown.
			if ( ! document.getElementById( 'period-car-select' ).options.length || document.getElementById( 'period-car-select' ).options[0].value === '' ) {
				api( 'admin/cars' ).then( function ( cars ) {
					var sel  = document.getElementById( 'period-car-select' );
					sel.innerHTML = '<option value="">— select —</option>';
					cars.forEach( function ( c ) {
						var opt  = document.createElement( 'option' );
						opt.value = c.id;
						opt.textContent = c.brand + ' ' + c.model + ( c.year ? ' (' + c.year + ')' : '' );
						if ( p && p.car_id == c.id ) { opt.selected = true; }
						sel.appendChild( opt );
					} );
				} );
			}
			show( 'bingocr-period-form-wrap' );
		}

		function togglePeriodType() {
			var form = document.getElementById( 'bingocr-period-form' );
			var type = form.querySelector( '[name="pricing_type"]:checked' ).value;
			document.getElementById( 'period-day-rate-wrap' ).style.display = type === 'rate_per_day' ? '' : 'none';
			document.getElementById( 'period-fixed-wrap' ).style.display    = type === 'fixed_total'  ? '' : 'none';
		}

		function togglePeriodScope() {
			var val = document.getElementById( 'period-applies-to' ).value;
			document.getElementById( 'period-category-wrap' ).style.display = val === 'category' ? '' : 'none';
			document.getElementById( 'period-car-wrap' ).style.display      = val === 'car'      ? '' : 'none';
		}

		document.getElementById( 'bingocr-period-form' ).querySelectorAll( '[name="pricing_type"]' ).forEach( function ( r ) {
			r.addEventListener( 'change', togglePeriodType );
		} );
		document.getElementById( 'period-applies-to' ).addEventListener( 'change', togglePeriodScope );
		document.getElementById( 'bingocr-add-period' ).addEventListener( 'click', function () { openPeriodForm( null ); } );
		document.getElementById( 'bingocr-cancel-period' ).addEventListener( 'click', function () { hide( 'bingocr-period-form-wrap' ); } );

		document.getElementById( 'bingocr-period-form' ).addEventListener( 'submit', function ( e ) {
			e.preventDefault();
			var form = e.target;
			var id   = document.getElementById( 'period-id' ).value;
			var data = {
				name:         form.querySelector( '[name="name"]' ).value,
				pricing_type: form.querySelector( '[name="pricing_type"]:checked' ).value,
				min_days:     parseInt( form.querySelector( '[name="min_days"]' ).value ) || 1,
				max_days:     parseInt( form.querySelector( '[name="max_days"]' ).value ) || 7,
				fixed_price:  parseFloat( form.querySelector( '[name="fixed_price"]' ).value ) || 0,
				price_per_day: parseFloat( form.querySelector( '[name="price_per_day"]' ).value ) || 0,
				applies_to:   form.querySelector( '[name="applies_to"]' ).value,
				category:     form.querySelector( '[name="category"]' ).value,
				car_id:       parseInt( form.querySelector( '[name="car_id"]' ).value ) || null,
				priority:     parseInt( form.querySelector( '[name="priority"]' ).value ) || 0,
				status:       form.querySelector( '[name="status"]' ).value,
			};
			var call = id
				? api( 'admin/period-pricing/' + id, 'PUT', data )
				: api( 'admin/period-pricing', 'POST', data );
			call.then( function () { hide( 'bingocr-period-form-wrap' ); loadPeriod(); } )
				.catch( function ( err ) { msgHtml( '#bingocr-period-form .bingocr-form-message', err ); } );
		} );

		loadSeasonal();
		loadPeriod();
	}

	// ── Discounts (on Pricing page) ──────────────────────────────────────

	if ( document.getElementById( 'bingocr-discounts-list' ) ) {
		var discountsData = [];

		function loadDiscounts() {
			api( 'admin/discounts' ).then( function ( data ) {
				discountsData = data;
				renderDiscounts();
			} );
		}

		function renderDiscounts() {
			var wrap = document.getElementById( 'bingocr-discounts-list' );
			if ( ! discountsData.length ) {
				wrap.innerHTML = '<p class="bingocr-empty">' + esc( i18n.no_discounts ) + '</p>';
				return;
			}
			var html = '<table class="bingocr-table"><thead><tr>';
			html += '<th>' + esc( i18n.code ) + '</th><th>' + esc( i18n.type ) + '</th><th>' + esc( i18n.value ) + '</th><th>' + esc( i18n.min_days ) + '</th><th>' + esc( i18n.uses ) + '</th><th>' + esc( i18n.expires ) + '</th><th>' + esc( i18n.status ) + '</th><th></th>';
			html += '</tr></thead><tbody>';
			discountsData.forEach( function ( d ) {
				var sym  = ( cfg.settings && cfg.settings.currency_symbol ) || '';
				var val  = d.type === 'percentage'
					? parseFloat( d.value ).toFixed( 2 ) + '%'
					: sym + parseFloat( d.value ).toFixed( 2 );
				var uses = d.max_uses ? ( esc( d.used_count ) + ' / ' + esc( d.max_uses ) ) : ( esc( d.used_count ) + ' / ∞' );
				html += '<tr>';
				html += '<td><strong>' + esc( d.code ) + '</strong></td>';
				html += '<td>' + esc( d.type ) + '</td>';
				html += '<td>' + esc( val ) + '</td>';
				html += '<td>' + esc( d.min_days ) + '</td>';
				html += '<td>' + uses + '</td>';
				html += '<td>' + ( d.expires_at ? esc( d.expires_at ) : '—' ) + '</td>';
				html += '<td><span class="bcr-status bcr-status-' + esc( d.status ) + '">' + esc( d.status ) + '</span></td>';
				html += '<td>';
				html += '<button class="button button-small bcr-edit-discount" data-id="' + esc( d.id ) + '">' + esc( i18n.edit ) + '</button> ';
				html += '<button class="button button-small bcr-del-discount" data-id="' + esc( d.id ) + '" style="color:#c0392b">' + esc( i18n.delete ) + '</button>';
				html += '</td></tr>';
			} );
			html += '</tbody></table>';
			wrap.innerHTML = html;

			document.querySelectorAll( '.bcr-edit-discount' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					var d = discountsData.find( function ( x ) { return x.id == btn.dataset.id; } );
					openDiscountForm( d );
				} );
			} );
			document.querySelectorAll( '.bcr-del-discount' ).forEach( function ( btn ) {
				btn.addEventListener( 'click', function () {
					if ( ! window.confirm( i18n.confirm_delete ) ) { return; }
					api( 'admin/discounts/' + btn.dataset.id, 'DELETE' ).then( loadDiscounts );
				} );
			} );
		}

		function openDiscountForm( d ) {
			document.getElementById( 'discount-id' ).value = d ? d.id : '';
			document.getElementById( 'bingocr-discount-form-title' ).textContent = d ? i18n.edit_discount : i18n.add_discount;
			var form = document.getElementById( 'bingocr-discount-form' );
			[ 'code', 'type', 'value', 'min_days', 'status' ].forEach( function ( f ) {
				var el = form.querySelector( '[name="' + f + '"]' );
				if ( el ) {
					el.value = d ? ( d[ f ] != null ? d[ f ] : '' )
						: ( f === 'status' ? 'active' : f === 'type' ? 'percentage' : f === 'min_days' ? '1' : f === 'value' ? '0' : '' );
				}
			} );
			var maxEl = form.querySelector( '[name="max_uses"]' );
			if ( maxEl ) { maxEl.value = d && d.max_uses ? d.max_uses : ''; }
			var expEl = form.querySelector( '[name="expires_at"]' );
			if ( expEl ) { expEl.value = d && d.expires_at ? d.expires_at : ''; }
			form.querySelector( '.bingocr-form-message' ).textContent = '';
			show( 'bingocr-discount-form-wrap' );
		}

		document.getElementById( 'bingocr-add-discount' ).addEventListener( 'click', function () { openDiscountForm( null ); } );
		document.getElementById( 'bingocr-cancel-discount' ).addEventListener( 'click', function () { hide( 'bingocr-discount-form-wrap' ); } );

		document.getElementById( 'bingocr-discount-form' ).addEventListener( 'submit', function ( e ) {
			e.preventDefault();
			var form = e.target;
			var id   = document.getElementById( 'discount-id' ).value;
			var data = {
				code:       form.querySelector( '[name="code"]' ).value.toUpperCase(),
				type:       form.querySelector( '[name="type"]' ).value,
				value:      parseFloat( form.querySelector( '[name="value"]' ).value ) || 0,
				min_days:   parseInt( form.querySelector( '[name="min_days"]' ).value ) || 1,
				max_uses:   parseInt( form.querySelector( '[name="max_uses"]' ).value ) || null,
				expires_at: form.querySelector( '[name="expires_at"]' ).value || null,
				status:     form.querySelector( '[name="status"]' ).value,
			};
			var call = id
				? api( 'admin/discounts/' + id, 'PUT', data )
				: api( 'admin/discounts', 'POST', data );
			call.then( function () { hide( 'bingocr-discount-form-wrap' ); loadDiscounts(); } )
				.catch( function ( err ) { msgHtml( '#bingocr-discount-form .bingocr-form-message', err ); } );
		} );

		loadDiscounts();
	}

	// ── Settings page ────────────────────────────────────────────────────

	if ( document.getElementById( 'bingocr-settings-form' ) ) {
		document.getElementById( 'bingocr-settings-form' ).addEventListener( 'submit', function ( e ) {
			e.preventDefault();
			var form = e.target;
			var data = {};
			form.querySelectorAll( 'input, select, textarea' ).forEach( function ( el ) {
				if ( ! el.name ) { return; }
				if ( el.type === 'checkbox' ) {
					data[ el.name ] = el.checked;
				} else {
					data[ el.name ] = el.value;
				}
			} );
			api( 'admin/settings', 'POST', data ).then( function () {
				show( 'bingocr-settings-saved' );
				setTimeout( function () { hide( 'bingocr-settings-saved' ); }, 3000 );
			} ).catch( function ( err ) {
				msg( '#bingocr-settings-form .bingocr-form-message', err.message, false );
			} );
		} );
	}

	// ── Payment page ─────────────────────────────────────────────────────
	// Same admin/settings endpoint and whitelist — disabled (Pro-locked) fields
	// are skipped by the browser, so they keep their stored value.

	if ( document.getElementById( 'bingocr-payment-form' ) ) {
		document.getElementById( 'bingocr-payment-form' ).addEventListener( 'submit', function ( e ) {
			e.preventDefault();
			var form = e.target;
			var data = {};
			form.querySelectorAll( 'input, select, textarea' ).forEach( function ( el ) {
				if ( ! el.name || el.disabled ) { return; }
				data[ el.name ] = el.type === 'checkbox' ? el.checked : el.value;
			} );
			api( 'admin/settings', 'POST', data ).then( function () {
				show( 'bingocr-payment-saved' );
				setTimeout( function () { hide( 'bingocr-payment-saved' ); }, 3000 );
			} ).catch( function ( err ) {
				msg( '#bingocr-payment-form .bingocr-form-message', err.message, false );
			} );
		} );
	}

} )();
