<?php
/** Public shortcodes and booking form handler. */
namespace PlugozaEventTicketing\Frontend;

use PlugozaEventTicketing\Payment_Gateways;
use PlugozaEventTicketing\Repository;
use PlugozaEventTicketing\Ticket;

defined( 'ABSPATH' ) || exit;

final class Shortcodes {
	public function __construct() {
		add_action( 'wp_enqueue_scripts', array( $this, 'assets' ) );
		add_shortcode( 'plugoza_ett_event_list', array( $this, 'event_list' ) );
		add_shortcode( 'plugoza_ett_event_details', array( $this, 'event_details' ) );
		add_shortcode( 'plugoza_ett_event_booking', array( $this, 'booking_form' ) );
		add_shortcode( 'plugoza_ett_event_ticket', array( $this, 'event_ticket' ) );
		add_shortcode( 'plugoza_ett_event_booking_success', array( $this, 'booking_success' ) );
		add_shortcode( 'plugoza_ett_my_tickets', array( $this, 'my_tickets' ) );
		add_action( 'admin_post_nopriv_plugoza_ett_book', array( $this, 'book' ) );
		add_action( 'admin_post_plugoza_ett_book', array( $this, 'book' ) );
	}
	public function assets() {
		wp_enqueue_style( 'plugoza-event-ticketing-frontend', PLUGOZA_ETT_URL . 'assets/css/frontend.css', array(), PLUGOZA_ETT_VERSION );
		wp_enqueue_script( 'plugoza-event-ticketing-frontend', PLUGOZA_ETT_URL . 'assets/js/frontend.js', array(), PLUGOZA_ETT_VERSION, true );
		$settings = Payment_Gateways::settings();
		wp_localize_script( 'plugoza-event-ticketing-frontend', 'plugozaEventTicketing', array( 'manualMessage' => sanitize_textarea_field( $settings['free_registration']['instructions'] ?? '' ) ) );
	}
	public function event_list() {
		$events          = Repository::events( true );
		$booking_page_id = absint( get_option( 'plugoza_ett_booking_page_id', 0 ) );

		if ( ! $booking_page_id ) {
			$booking_page    = get_page_by_path( 'book-events' );
			$booking_page_id = $booking_page ? absint( $booking_page->ID ) : 0;
		}

		$output = '<div class="plugoza-ett-events">';
		foreach ( $events as $event ) {
			$url = add_query_arg( 'plugoza_ett_event', $event->id, $booking_page_id ? get_permalink( $booking_page_id ) : get_permalink() );
			$output .= '<article class="plugoza-ett-event"><h2>' . esc_html( $event->name ) . '</h2><p>' . esc_html( wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), strtotime( $event->start_date ) ) ) . '</p><p>' . esc_html( $event->venue ) . '</p><a class="plugoza-ett-button" href="' . esc_url( $url ) . '">' . esc_html__( 'Book now', 'plugoza-event-ticketing' ) . '</a></article>';
		}

		return $output . '</div>';
	}	public function event_details( $atts ) { $atts = shortcode_atts( array( 'id' => 0 ), $atts, 'event_details' ); $event = Repository::event( absint( $atts['id'] ) ); if ( ! $event || 'published' !== $event->status ) { return ''; } return '<article class="plugoza-ett-event-details"><h1>' . esc_html( $event->name ) . '</h1><div>' . wp_kses_post( wpautop( $event->description ) ) . '</div><p>' . esc_html( $event->venue ) . '</p></article>'; }
	public function event_ticket( $atts ) { $atts = shortcode_atts( array( 'id' => 0 ), $atts, 'event_ticket' ); return $this->render_booking_form_final( absint( $atts['id'] ) ); }
	public function booking_form( $atts ) {
		$atts     = shortcode_atts( array( 'event_id' => 0 ), $atts, 'event_booking' );
		$event_id = absint( $atts['event_id'] );

		if ( ! $event_id ) {
			$event_id = absint( $_GET['plugoza_ett_event'] ?? 0 ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- public read-only URL parameter.
		}

		$event = Repository::event( $event_id );

		if ( ! $event || 'published' !== $event->status ) {
			return '<p>' . esc_html__( 'This event is not available for booking.', 'plugoza-event-ticketing' ) . '</p>';
		}

		if ( ! Repository::tickets( $event_id, true ) ) {
			return '<p>' . esc_html__( 'There are no active tickets available for this event.', 'plugoza-event-ticketing' ) . '</p>';
		}

		if ( ! Payment_Gateways::available_methods( $event ) ) {
			return '<p>' . esc_html__( 'No payment method is currently enabled for this event. Please contact the event administrator.', 'plugoza-event-ticketing' ) . '</p>';
		}

		return $this->render_booking_form_final( $event_id );
	}
	private function bank_details( $bank ) { $lines = array_filter( array( $bank['bank_name'] ?? '', $bank['account_name'] ?? '', $bank['account_number'] ?? '', $bank['ifsc_swift'] ?? '', $bank['branch'] ?? '', $bank['upi_id'] ?? '', $bank['instructions'] ?? '' ) ); return implode( "\n", $lines ); }
	private function render_booking_form_final( $event_id ) { $event = Repository::event( $event_id ); if ( ! $event || 'published' !== $event->status ) { return ''; } $tickets = Repository::tickets( $event->id, true ); $methods = Payment_Gateways::available_methods( $event ); if ( ! $tickets || ! $methods ) { return '<p>' . esc_html__( 'Booking is not currently available for this event.', 'plugoza-event-ticketing' ) . '</p>'; } $currency = sanitize_text_field( get_option( 'plugoza_ett_settings', array() )['currency'] ?? 'USD' ); $links = Payment_Gateways::event_legal_links( $event->id ); ob_start();
?>
<div class="plugoza-ett-booking-layout"><aside class="plugoza-ett-event-about"><h2><?php echo esc_html( $event->name ); ?></h2><p><?php echo esc_html( wp_date( get_option( 'date_format' ), strtotime( $event->start_date ) ) ); ?></p><p><?php echo esc_html( $event->venue ); ?></p><?php echo wp_kses_post( wpautop( $event->description ) ); ?></aside><form class="plugoza-ett-booking-form" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"><input type="hidden" name="action" value="plugoza_ett_book"><input type="hidden" name="event_id" value="<?php echo esc_attr( $event->id ); ?>"><?php wp_nonce_field( 'plugoza_ett_book_' . $event->id ); ?><h2><?php esc_html_e( 'Book your tickets', 'plugoza-event-ticketing' ); ?></h2><div class="plugoza-ett-form-row"><p><label><?php esc_html_e( 'First name', 'plugoza-event-ticketing' ); ?><input required name="first_name"></label></p><p><label><?php esc_html_e( 'Last name', 'plugoza-event-ticketing' ); ?><input required name="last_name"></label></p></div><div class="plugoza-ett-form-row"><p><label><?php esc_html_e( 'Email', 'plugoza-event-ticketing' ); ?><input required type="email" name="email"></label></p><p><label><?php esc_html_e( 'Mobile number', 'plugoza-event-ticketing' ); ?><input name="mobile"></label></p></div><div class="plugoza-ett-form-row"><p><label><?php esc_html_e( 'Ticket type', 'plugoza-event-ticketing' ); ?><select class="plugoza-ett-ticket-select" name="ticket_id"><?php foreach ( $tickets as $ticket ) { echo '<option value="' . esc_attr( $ticket->id ) . '" data-price="' . esc_attr( $ticket->price ) . '">' . esc_html( $ticket->name . ' — ' . $ticket->price . ' ' . $currency ) . '</option>'; } ?></select></label></p><p><label><?php esc_html_e( 'Number of tickets', 'plugoza-event-ticketing' ); ?><input class="plugoza-ett-ticket-quantity" required min="1" type="number" name="quantity" value="1"></label></p></div><p class="plugoza-ett-total"><strong><?php esc_html_e( 'Total:', 'plugoza-event-ticketing' ); ?> <span>0.00 <?php echo esc_html( $currency ); ?></span></strong></p><fieldset><legend><?php esc_html_e( 'Payment method', 'plugoza-event-ticketing' ); ?></legend><?php foreach ( $methods as $i => $method ) { echo '<label><input required type="radio" name="payment_method" value="' . esc_attr( $method ) . '" ' . checked( 0, $i, false ) . '> ' . esc_html( 'bank_transfer' === $method ? __( 'Manual Bank Transfer', 'plugoza-event-ticketing' ) : __( 'Free Registration', 'plugoza-event-ticketing' ) ) . '</label><br>'; } ?></fieldset><p><label><input required type="checkbox" name="terms" value="1"> <a target="_blank" rel="noopener" href="<?php echo esc_url( $links['terms'] ); ?>"><?php esc_html_e( 'I accept the Terms & Conditions.', 'plugoza-event-ticketing' ); ?></a></label><br><label><input required type="checkbox" name="privacy" value="1"> <a target="_blank" rel="noopener" href="<?php echo esc_url( $links['privacy'] ); ?>"><?php esc_html_e( 'I accept the Privacy Policy.', 'plugoza-event-ticketing' ); ?></a></label><br><label><input required type="checkbox" name="refund" value="1"> <a target="_blank" rel="noopener" href="<?php echo esc_url( $links['refund'] ); ?>"><?php esc_html_e( 'I accept the Refund Policy.', 'plugoza-event-ticketing' ); ?></a></label></p><button class="plugoza-ett-button" type="submit"><?php esc_html_e( 'Book now', 'plugoza-event-ticketing' ); ?></button></form></div>
<?php
		$output = ob_get_clean();
		return $output;
	}
	public function booking_success() {
		$id      = absint( $_GET['booking_id'] ?? 0 );
		$key     = sanitize_text_field( wp_unslash( $_GET['key'] ?? '' ) );
		$success = 'success' === sanitize_key( wp_unslash( $_GET['plugoza_ett_booking'] ?? '' ) );
		$nonce   = sanitize_text_field( wp_unslash( $_GET['plugoza_ett_success_nonce'] ?? '' ) );

		if ( $success && ( ! $id || ! wp_verify_nonce( $nonce, 'plugoza_ett_booking_success_' . $id ) ) ) {
			return '<p>' . esc_html__( 'The booking confirmation link is no longer valid. Please check your email for the ticket.', 'plugoza-event-ticketing' ) . '</p>';
		}

		$output = '<div class="plugoza-ett-booking-success"><h2>' . esc_html__( 'Booking received', 'plugoza-event-ticketing' ) . '</h2>';
		$output .= '<p>' . esc_html__( 'Thank you. Your booking has been received successfully. Your ticket has also been sent to your email address.', 'plugoza-event-ticketing' ) . '</p>';

		if ( $success && $id && $key ) {
			$url     = add_query_arg( array( 'action' => 'plugoza_ett_download_ticket', 'booking_id' => $id, 'key' => rawurlencode( $key ), 'plugoza_ett_ticket_nonce' => wp_create_nonce( 'plugoza_ett_download_ticket_' . $id ) ), admin_url( 'admin-post.php' ) );
			$output .= '<p><a class="plugoza-ett-button" href="' . esc_url( $url ) . '">' . esc_html__( 'Download PDF Ticket', 'plugoza-event-ticketing' ) . '</a></p>';
		} elseif ( $success ) {
			$output .= '<p>' . esc_html__( 'Please check your email for the PDF ticket.', 'plugoza-event-ticketing' ) . '</p>';
		}

		return $output . '</div>';
	}
	public function book() {
		$event_id = absint( $_POST['event_id'] ?? 0 ); check_admin_referer( 'plugoza_ett_book_' . $event_id ); $event = Repository::event( $event_id ); $ticket_id = absint( $_POST['ticket_id'] ?? 0 ); $quantity = absint( $_POST['quantity'] ?? 0 ); $email = sanitize_email( wp_unslash( $_POST['email'] ?? '' ) );
		$method = sanitize_key( wp_unslash( $_POST['payment_method'] ?? '' ) ); $available = $event ? Payment_Gateways::available_methods( $event ) : array();
		global $wpdb; $ticket = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d AND event_id = %d AND status = %s', Repository::table( 'tickets' ), $ticket_id, $event_id, 'active' ) );
		if ( ! $event || 'published' !== $event->status || ! $ticket || ! $quantity || $quantity > $ticket->available_quantity || ! is_email( $email ) || ! in_array( $method, $available, true ) || empty( $_POST['terms'] ) || empty( $_POST['privacy'] ) || empty( $_POST['refund'] ) ) { wp_die( esc_html__( 'Unable to create the booking. Please check your details.', 'plugoza-event-ticketing' ) ); }
		$now = current_time( 'mysql', true ); $customer = $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE email = %s', Repository::table( 'customers' ), $email ) );
		if ( ! $customer ) { $wpdb->insert( Repository::table( 'customers' ), array( 'first_name' => sanitize_text_field( wp_unslash( $_POST['first_name'] ?? '' ) ), 'last_name' => sanitize_text_field( wp_unslash( $_POST['last_name'] ?? '' ) ), 'email' => $email, 'mobile' => sanitize_text_field( wp_unslash( $_POST['mobile'] ?? '' ) ), 'country' => strtoupper( sanitize_text_field( wp_unslash( $_POST['country'] ?? '' ) ) ), 'created_at' => $now, 'updated_at' => $now ) ); $customer = $wpdb->insert_id; }
		$wpdb->query( $wpdb->prepare( 'UPDATE %i SET available_quantity = available_quantity - %d WHERE id = %d AND available_quantity >= %d', Repository::table( 'tickets' ), $quantity, $ticket->id, $quantity ) );
		if ( 1 !== $wpdb->rows_affected ) { wp_die( esc_html__( 'That ticket has just sold out.', 'plugoza-event-ticketing' ) ); }
		$is_free = 'free_registration' === $method;
		$result = $wpdb->insert( Repository::table( 'bookings' ), array( 'booking_number' => 'PET-' . strtoupper( wp_generate_password( 10, false, false ) ), 'event_id' => $event_id, 'ticket_id' => $ticket->id, 'customer_id' => $customer, 'quantity' => $quantity, 'amount' => $ticket->price * $quantity, 'payment_method' => $method, 'payment_status' => $is_free ? 'paid' : 'pending', 'booking_status' => $is_free ? 'confirmed' : 'pending_payment', 'transaction_id' => sanitize_text_field( wp_unslash( $_POST['transaction_id'] ?? '' ) ), 'payment_note' => sanitize_textarea_field( wp_unslash( $_POST['payment_note'] ?? '' ) ), 'qr_code' => wp_generate_uuid4(), 'terms_accepted_at' => $now, 'privacy_accepted_at' => $now, 'refund_accepted_at' => $now, 'booking_date' => $now ) );
		if ( false === $result ) { wp_die( esc_html__( 'Your booking could not be saved. Please try again.', 'plugoza-event-ticketing' ) ); }
		$booking_id = absint( $wpdb->insert_id );
		Ticket::create( $booking_id );
		$success_page = get_page_by_path( 'booking-success' );
		$success_url  = $success_page ? get_permalink( $success_page->ID ) : ( wp_get_referer() ?: home_url( '/' ) );
		$token = $wpdb->get_var( $wpdb->prepare( 'SELECT qr_code FROM %i WHERE id = %d', Repository::table( 'bookings' ), $booking_id ) );
		wp_safe_redirect( add_query_arg( array( 'plugoza_ett_booking' => 'success', 'booking_id' => $booking_id, 'key' => rawurlencode( $token ), 'plugoza_ett_success_nonce' => wp_create_nonce( 'plugoza_ett_booking_success_' . $booking_id ) ), $success_url ) ); exit;
	}
	public function my_tickets() { if ( ! is_user_logged_in() ) { return '<p>' . esc_html__( 'Please log in to view your tickets.', 'plugoza-event-ticketing' ) . '</p>'; } $user = wp_get_current_user(); global $wpdb; $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT b.booking_number, b.qr_code, e.name FROM %i b JOIN %i c ON b.customer_id = c.id JOIN %i e ON b.event_id = e.id WHERE c.email = %s', Repository::table( 'bookings' ), Repository::table( 'customers' ), Repository::table( 'events' ), $user->user_email ) ); $output = '<ul class="plugoza-ett-tickets">'; foreach ( $rows as $row ) { $output .= '<li><strong>' . esc_html( $row->name ) . '</strong>: ' . esc_html( $row->booking_number ) . ' <span class="screen-reader-text">' . esc_html__( 'Check-in token:', 'plugoza-event-ticketing' ) . '</span>' . esc_html( $row->qr_code ) . '</li>'; } return $output . '</ul>'; }
}
