<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class BingoCR_Shortcode {

	public function register(): void {
		add_shortcode( 'bingocr_rental', array( $this, 'render' ) );
	}

	public function render( array $atts ): string {
		$settings = BingoCR_DB::get_settings();

		$atts = shortcode_atts( array(
			'show_locations'  => 'true',
			'show_categories' => 'true',
			'show_extras'     => 'true',
			'theme'           => $settings['theme'],
			'primary_color'   => $settings['primary_color'],
		), $atts, 'bingocr_rental' );

		// Hide extras in the booking widget when the premium class is absent (free build).
		if ( ! BingoCR_License::can( 'extras' ) ) {
			$atts['show_extras'] = 'false';
		}

		// Enqueue assets only when shortcode is used.
		$this->enqueue_assets( $atts, $settings );

		$theme_class = esc_attr( $atts['theme'] ) === 'dark' ? 'bingocr-theme-dark' : 'bingocr-theme-light';

		$html  = '<div id="bingocr-app" class="bingocr-widget ' . $theme_class . '"';
		$html .= ' data-show-locations="' . esc_attr( $atts['show_locations'] ) . '"';
		$html .= ' data-show-categories="' . esc_attr( $atts['show_categories'] ) . '"';
		$html .= ' data-show-extras="' . esc_attr( $atts['show_extras'] ) . '"';
		$html .= '>';
		$html .= '<div class="bingocr-loading">' . esc_html__( 'Loading…', 'bingocar' ) . '</div>';
		// Modal lives inside the widget so it inherits all CSS custom properties.
		$html .= $this->render_modal_template();
		$html .= '</div>';

		// Attribution is strictly opt-in for everyone (default off) — never forced.
		if ( ! empty( $settings['show_attribution'] ) ) {
			$html .= '<p class="bingocr-attribution">'
				. esc_html__( 'Powered by', 'bingocar' )
				. ' <a href="https://bingorentals.com" rel="nofollow noopener" target="_blank">BingoCR</a></p>';
		}

		return $html;
	}

	private function enqueue_assets( array $atts, array $settings ): void {
		wp_enqueue_style(
			'bingocr-public',
			BINGOCR_URL . 'public/css/bingocr-public.css',
			array(),
			BINGOCR_VERSION
		);

		wp_enqueue_script(
			'bingocr-public',
			BINGOCR_URL . 'public/js/bingocr-public.js',
			array(),
			BINGOCR_VERSION,
			true
		);

		// PayPal JS SDK — only when PayPal is enabled, Pro and configured.
		// BingoCR_PayPal is premium-only (absent in the free build), so guard it.
		$bingocr_paypal     = class_exists( 'BingoCR_PayPal' ) ? new BingoCR_PayPal() : null;
		$bingocr_paypal_on  = $bingocr_paypal ? $bingocr_paypal->is_ready() : false;
		if ( $bingocr_paypal_on ) {
			$bingocr_pp_url = add_query_arg(
				array(
					'client-id' => rawurlencode( $bingocr_paypal->client_id() ),
					'currency'  => rawurlencode( strtoupper( $settings['currency'] ?? 'EUR' ) ),
					'intent'    => 'capture',
				),
				'https://www.paypal.com/sdk/js'
			);
			// No version on purpose: PayPal's SDK rejects unknown query args (e.g. ?ver=),
			// which would stop it loading — so we must not let WP append a version string.
			wp_enqueue_script( 'bingocr-paypal-sdk', $bingocr_pp_url, array(), null, true ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- PayPal SDK breaks if a ?ver= query arg is appended.
		}

		$primary = sanitize_hex_color( $atts['primary_color'] ) ?: '#e63946';
		// Override the stylesheet's default — it must match the var the CSS reads (--bcr-primary).
		wp_add_inline_style(
			'bingocr-public',
			'.bingocr-widget { --bcr-primary: ' . esc_attr( $primary ) . '; }'
		);

		$lang = sanitize_text_field( $settings['language'] ?? 'en' );

		$ooh_enabled = BingoCR_License::can( 'out_of_hours' )
			&& ! empty( $settings['out_of_hours_enabled'] )
			&& (float) ( $settings['out_of_hours_fee'] ?? 0 ) > 0;

		wp_localize_script( 'bingocr-public', 'bingocrData', array(
			'termsText'        => wpautop( wp_kses_post( $settings['terms_conditions'] ?? '' ) ),
			'payments'         => array(
				'cash'   => ! empty( $settings['payment_cash'] ),
				'card'   => ! empty( $settings['payment_card'] ),
				'bank'   => ! empty( $settings['payment_bank'] ),
				'paypal' => $bingocr_paypal_on,
			),
			'paymentInstructions' => wpautop( wp_kses_post( $settings['payment_instructions'] ?? '' ) ),
			'outOfHours'       => array(
				'enabled' => $ooh_enabled,
				'fee'     => (float) ( $settings['out_of_hours_fee'] ?? 0 ),
				'start'   => sanitize_text_field( $settings['business_hours_start'] ?? '09:00' ),
				'end'     => sanitize_text_field( $settings['business_hours_end'] ?? '18:00' ),
			),
			'restUrl'          => esc_url_raw( rest_url( 'bingocr/v1/' ) ),
			'nonce'            => wp_create_nonce( 'wp_rest' ),
			'autoDetectLang'   => ! empty( $settings['auto_detect_language'] ),
			'lang'             => $lang,
			'currencySymbol'   => $settings['currency_symbol'],
			'currencyPosition' => $settings['currency_position'],
			'dateFormat'       => $settings['date_format'],
			'defaultDeposit'   => (float) ( $settings['default_deposit'] ?? 0 ),
			'i18n'             => self::get_i18n( $lang ),
			// Both tables, so auto-detect can switch the UI client-side.
			'i18nAll'          => array(
				'en' => self::get_i18n( 'en' ),
				'ro' => self::get_i18n( 'ro' ),
			),
			'features'         => array(
				'extras'    => BingoCR_License::can( 'extras' ),
				'discounts' => BingoCR_License::can( 'discounts' ),
			),
			'upgradeUrl'       => BingoCR_License::upgrade_url(),
			'isPro'            => BingoCR_License::is_pro(),
		) );
	}

	private function render_modal_template(): string {
		static $rendered = false;
		if ( $rendered ) {
			return '';
		}
		$rendered = true;

		ob_start();
		?>
		<div id="bcr-overlay" class="bcr-overlay" role="dialog" aria-modal="true" aria-labelledby="bcr-car-name">
			<div class="bcr-modal">

				<div class="bcr-modal-header">
					<div class="bcr-modal-car-strip">
						<img id="bcr-car-img" src="" alt="" class="bcr-modal-car-img" style="display:none">
						<div class="bcr-modal-car-info">
							<div class="bcr-modal-car-name" id="bcr-car-name"></div>
							<div class="bcr-modal-car-dates" id="bcr-car-dates"></div>
						</div>
					</div>
					<button type="button" class="bcr-modal-close" id="bcr-modal-close" aria-label="<?php esc_attr_e( 'Close', 'bingocar' ); ?>">&times;</button>
				</div>

				<!-- Order Summary — outside the scrollable body so it's always visible -->
				<div class="bcr-modal-summary">
					<div class="bcr-summary-label"><?php esc_html_e( 'Order Summary', 'bingocar' ); ?></div>
					<div class="bcr-bd">
						<div class="bcr-bd-row" id="bcr-bd-base-row">
							<span id="bcr-bd-base-label"></span>
							<span id="bcr-bd-base-amt"></span>
						</div>
						<div class="bcr-bd-row bcr-bd-rule" id="bcr-bd-period-row" style="display:none">
							<span id="bcr-bd-period-label"></span>
							<span id="bcr-bd-period-amt"></span>
						</div>
						<div id="bcr-bd-seasonal-rows"></div>
						<div id="bcr-bd-extras-rows"></div>
						<div class="bcr-bd-row bcr-bd-surcharge" id="bcr-bd-ooh-row" style="display:none">
							<span id="bcr-bd-ooh-label"></span>
							<span id="bcr-bd-ooh-amt"></span>
						</div>
						<div class="bcr-bd-row bcr-bd-saving" id="bcr-bd-discount-row" style="display:none">
							<span id="bcr-bd-discount-label"></span>
							<span id="bcr-bd-discount-amt"></span>
						</div>
						<div class="bcr-bd-total-row">
							<span><?php esc_html_e( 'Total', 'bingocar' ); ?></span>
							<span class="bcr-total-amt" id="bcr-bd-total-amt">&hellip;</span>
						</div>
						<div class="bcr-bd-row bcr-bd-deposit" id="bcr-bd-deposit-row" style="display:none">
							<span><?php esc_html_e( 'Security deposit (refundable)', 'bingocar' ); ?></span>
							<span id="bcr-bd-deposit-amt"></span>
						</div>
					</div>
				</div><!-- .bcr-modal-summary -->

				<div class="bcr-modal-body">

					<div class="bcr-mcard" id="bcr-extras-card" style="display:none">
						<div class="bcr-mcard-header"><?php esc_html_e( 'Optional Extras', 'bingocar' ); ?></div>
						<div class="bcr-mcard-body" id="bcr-extras-list"></div>
					</div>

					<div class="bcr-mcard" id="bcr-discount-card" style="display:none">
						<div class="bcr-mcard-header"><?php esc_html_e( 'Discount Code', 'bingocar' ); ?></div>
						<div class="bcr-mcard-body">
							<div class="bcr-discount-wrap">
								<label class="screen-reader-text" for="bcr-discount-input"><?php esc_html_e( 'Discount Code', 'bingocar' ); ?></label>
								<input type="text" id="bcr-discount-input" class="bcr-input" placeholder="CODE" autocomplete="off" style="text-transform:uppercase">
								<button type="button" id="bcr-apply-discount" class="bcr-btn bcr-btn-outline"><?php esc_html_e( 'Apply', 'bingocar' ); ?></button>
							</div>
							<div id="bcr-discount-msg" class="bcr-discount-msg"></div>
						</div>
					</div>

					<div class="bcr-mcard" id="bcr-payment-card" style="display:none">
						<div class="bcr-mcard-header"><?php esc_html_e( 'Payment Method', 'bingocar' ); ?></div>
						<div class="bcr-mcard-body">
							<div id="bcr-payment-list"></div>
							<div id="bcr-payment-instructions" class="bcr-payment-instructions" style="display:none"></div>
						</div>
					</div>

					<form id="bcr-booking-form" novalidate>
						<h5 class="bcr-form-section-title"><?php esc_html_e( 'Your Details', 'bingocar' ); ?></h5>
						<div class="bcr-form-grid">
							<div class="bcr-field">
								<label class="bcr-field-label" for="bcr-pickup-time"><?php esc_html_e( 'Pickup Time', 'bingocar' ); ?></label>
								<input type="time" id="bcr-pickup-time" name="pickup_time" value="10:00" class="bcr-input">
							</div>
							<div class="bcr-field">
								<label class="bcr-field-label" for="bcr-return-time"><?php esc_html_e( 'Return Time', 'bingocar' ); ?></label>
								<input type="time" id="bcr-return-time" name="return_time" value="10:00" class="bcr-input">
							</div>
							<div class="bcr-field">
								<label class="bcr-field-label" for="bcr-cust-name"><?php esc_html_e( 'Full Name', 'bingocar' ); ?> *</label>
								<input type="text" id="bcr-cust-name" name="customer_name" required class="bcr-input" autocomplete="name">
							</div>
							<div class="bcr-field">
								<label class="bcr-field-label" for="bcr-cust-email"><?php esc_html_e( 'Email', 'bingocar' ); ?> *</label>
								<input type="email" id="bcr-cust-email" name="customer_email" required class="bcr-input" autocomplete="email">
							</div>
							<div class="bcr-field">
								<label class="bcr-field-label" for="bcr-cust-phone"><?php esc_html_e( 'Phone', 'bingocar' ); ?></label>
								<input type="tel" id="bcr-cust-phone" name="customer_phone" class="bcr-input" autocomplete="tel">
							</div>
							<div class="bcr-field bcr-field-full">
								<label class="bcr-field-label" for="bcr-cust-notes"><?php esc_html_e( 'Notes (optional)', 'bingocar' ); ?></label>
								<textarea id="bcr-cust-notes" name="notes" rows="2" class="bcr-input"></textarea>
							</div>
						</div>
						<label class="bcr-terms-label" for="bcr-accept-terms">
							<input type="checkbox" id="bcr-accept-terms" required>
							<span><?php esc_html_e( 'I accept the', 'bingocar' ); ?> <a href="#" id="bcr-terms-link" class="bcr-terms-link"><?php esc_html_e( 'terms and conditions', 'bingocar' ); ?></a></span>
						</label>
					</form>

				</div><!-- .bcr-modal-body -->

				<div class="bcr-modal-footer">
					<p class="bcr-error" id="bcr-book-error" style="display:none"></p>
					<div id="bcr-paypal-buttons" class="bcr-paypal-buttons" style="display:none"></div>
					<div class="bcr-modal-footer-btns">
						<button type="button" class="bcr-btn" id="bcr-modal-cancel"><?php esc_html_e( 'Cancel', 'bingocar' ); ?></button>
						<button type="submit" form="bcr-booking-form" class="bcr-btn bcr-btn-primary bcr-btn-confirm"><?php esc_html_e( 'Confirm Booking', 'bingocar' ); ?></button>
					</div>
				</div>

			</div><!-- .bcr-modal -->
		</div><!-- #bcr-overlay -->
		<?php
		return ob_get_clean();
	}

	public static function get_i18n( string $lang ): array {
		$strings = array(
			'en' => array(
				'search_title'        => 'Find Your Car',
				'pickup_date'         => 'Pickup Date',
				'return_date'         => 'Return Date',
				'pickup_location'     => 'Pickup Location',
				'dropoff_location'    => 'Drop-off Location',
				'category'            => 'Category',
				'all_categories'      => 'All Categories',
				'search_btn'          => 'Search Available Cars',
				'book_btn'            => 'Book Now',
				'back_btn'            => '← Back',
				'available_cars'      => 'Available Cars',
				'no_cars'             => 'No cars available for the selected dates.',
				'booking_title'       => 'Complete Your Booking',
				'your_name'           => 'Your Name',
				'email'               => 'Email',
				'phone'               => 'Phone',
				'notes'               => 'Notes (optional)',
				'extras_title'        => 'Optional Extras',
				'per_day'             => '/day',
				'flat'                => 'flat',
				'discount_code'       => 'Discount Code',
				'apply'               => 'Apply',
				'total'               => 'Total',
				'days'                => 'days',
				'confirm_booking'     => 'Confirm Booking',
				'booking_confirmed'   => 'Booking Confirmed!',
				'booking_ref'         => 'Your reference number:',
				'confirmation_email'  => 'A confirmation email has been sent to',
				'error_dates'         => 'Please select valid pickup and return dates.',
				'error_return_before' => 'Return date must be after pickup date.',
				'error_past_date'     => 'Pickup date cannot be in the past.',
				'error_required'      => 'Please fill in all required fields.',
				'loading'             => 'Loading…',
				'seats'               => 'seats',
				'automatic'           => 'Automatic',
				'manual'              => 'Manual',
				'any_location'        => 'Any location',
				'deposit'             => 'Deposit',
				'price_per_day'       => '/day',
				'same_as_pickup'      => 'Same as pickup',
				'base_rental'         => 'Base rental',
				'seasonal_adj'        => 'Seasonal adjustment',
				'period_rule'         => 'Duration rule',
				'new_search'          => 'New Search',
				'your_details'        => 'Your Details',
				'order_summary'       => 'Order Summary',
				'close'               => 'Close',
				'cancel'              => 'Cancel',
				'accept_terms'        => 'I accept the terms and conditions',
				'error_terms'         => 'Please accept the terms and conditions.',
				'pickup_time'         => 'Pickup Time',
				'return_time'         => 'Return Time',
				'out_of_hours_fee'    => 'Out-of-hours fee',
				'outside_hours'       => 'outside business hours',
				'accept_terms_pre'    => 'I accept the',
				'terms_link'          => 'terms and conditions',
				'terms_title'         => 'Terms and Conditions',
				'filter_text'         => 'Search brand or model…',
				'all_transmissions'   => 'All transmissions',
				'sort_default'        => 'Sort by',
				'sort_price_asc'      => 'Price: low to high',
				'sort_price_desc'     => 'Price: high to low',
				'no_match'            => 'No cars match your filters.',
				'day'                 => 'day',
				'payment_method'      => 'Payment Method',
				'pay_cash'            => 'Cash on pickup',
				'pay_card'            => 'Card on pickup',
				'pay_bank'            => 'Bank transfer',
				'pay_paypal'          => 'Pay online with PayPal',
				'pay_error'           => 'The payment could not be completed. Please try again.',
			),
			'ro' => array(
				'search_title'        => 'Găsește Mașina Ta',
				'pickup_date'         => 'Data Preluare',
				'return_date'         => 'Data Returnare',
				'pickup_location'     => 'Locație Preluare',
				'dropoff_location'    => 'Locație Returnare',
				'category'            => 'Categorie',
				'all_categories'      => 'Toate Categoriile',
				'search_btn'          => 'Caută Mașini Disponibile',
				'book_btn'            => 'Rezervă Acum',
				'back_btn'            => '← Înapoi',
				'available_cars'      => 'Mașini Disponibile',
				'no_cars'             => 'Nu există mașini disponibile pentru datele selectate.',
				'booking_title'       => 'Completează Rezervarea',
				'your_name'           => 'Numele Tău',
				'email'               => 'Email',
				'phone'               => 'Telefon',
				'notes'               => 'Observații (opțional)',
				'extras_title'        => 'Opțiuni Suplimentare',
				'per_day'             => '/zi',
				'flat'                => 'fix',
				'discount_code'       => 'Cod Reducere',
				'apply'               => 'Aplică',
				'total'               => 'Total',
				'days'                => 'zile',
				'confirm_booking'     => 'Confirmă Rezervarea',
				'booking_confirmed'   => 'Rezervare Confirmată!',
				'booking_ref'         => 'Numărul tău de referință:',
				'confirmation_email'  => 'Un email de confirmare a fost trimis la',
				'error_dates'         => 'Selectați date valide de preluare și returnare.',
				'error_return_before' => 'Data returnării trebuie să fie după data preluării.',
				'error_past_date'     => 'Data preluării nu poate fi în trecut.',
				'error_required'      => 'Completați toate câmpurile obligatorii.',
				'loading'             => 'Se încarcă…',
				'seats'               => 'locuri',
				'automatic'           => 'Automată',
				'manual'              => 'Manuală',
				'any_location'        => 'Orice locație',
				'deposit'             => 'Garanție',
				'price_per_day'       => '/zi',
				'same_as_pickup'      => 'Aceeași locație',
				'base_rental'         => 'Chirie de bază',
				'seasonal_adj'        => 'Ajustare sezonieră',
				'period_rule'         => 'Regulă durată',
				'new_search'          => 'Căutare nouă',
				'your_details'        => 'Datele tale',
				'order_summary'       => 'Rezumat comandă',
				'close'               => 'Închide',
				'cancel'              => 'Anulează',
				'accept_terms'        => 'Accept termenii și condițiile',
				'error_terms'         => 'Vă rugăm să acceptați termenii și condițiile.',
				'pickup_time'         => 'Ora Preluare',
				'return_time'         => 'Ora Returnare',
				'out_of_hours_fee'    => 'Taxă în afara programului',
				'outside_hours'       => 'în afara programului',
				'accept_terms_pre'    => 'Accept',
				'terms_link'          => 'termenii și condițiile',
				'terms_title'         => 'Termeni și Condiții',
				'filter_text'         => 'Caută marcă sau model…',
				'all_transmissions'   => 'Toate transmisiile',
				'sort_default'        => 'Sortează',
				'sort_price_asc'      => 'Preț: crescător',
				'sort_price_desc'     => 'Preț: descrescător',
				'no_match'            => 'Nicio mașină nu corespunde filtrelor.',
				'day'                 => 'zi',
				'payment_method'      => 'Metodă de plată',
				'pay_cash'            => 'Numerar la preluare',
				'pay_card'            => 'Card la preluare',
				'pay_bank'            => 'Transfer bancar',
				'pay_paypal'          => 'Plătește online cu PayPal',
				'pay_error'           => 'Plata nu a putut fi finalizată. Te rugăm să încerci din nou.',
			),
		);

		return $strings[ $lang ] ?? $strings['en'];
	}
}
