<?php
namespace PlugozaEventTicketing\Database;
defined( 'ABSPATH' ) || exit;

/** Creates and upgrades Plugoza Event Ticketing tables. */
final class Installer {
	public static function activate() { self::install(); self::enable_manual_pay(); self::create_required_pages(); flush_rewrite_rules(); }
	public static function maybe_upgrade() { if ( PLUGOZA_ETT_VERSION !== get_option( 'plugoza_ett_version' ) ) { self::install(); } }
	public static function install() {
		global $wpdb;
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';
		$charset = $wpdb->get_charset_collate(); $p = $wpdb->prefix;
		$sql = array(
		"CREATE TABLE {$p}plugoza_ett_organizers (id bigint(20) unsigned NOT NULL AUTO_INCREMENT, name varchar(190) NOT NULL, email varchar(100) NOT NULL DEFAULT '', phone varchar(50) NOT NULL DEFAULT '', created_at datetime NOT NULL, PRIMARY KEY (id), KEY email (email)) $charset;",
		"CREATE TABLE {$p}plugoza_ett_events (id bigint(20) unsigned NOT NULL AUTO_INCREMENT, name varchar(190) NOT NULL, slug varchar(190) NOT NULL, organizer_id bigint(20) unsigned NOT NULL DEFAULT 0, category varchar(100) NOT NULL DEFAULT '', event_type varchar(20) NOT NULL DEFAULT 'physical', banner_url text NOT NULL, description longtext NOT NULL, venue varchar(190) NOT NULL DEFAULT '', address text NOT NULL, city varchar(100) NOT NULL DEFAULT '', country varchar(2) NOT NULL DEFAULT '', meeting_url text NOT NULL, start_date datetime NOT NULL, end_date datetime NOT NULL, timezone varchar(64) NOT NULL, status varchar(20) NOT NULL DEFAULT 'draft', payment_methods text NOT NULL, created_at datetime NOT NULL, updated_at datetime NOT NULL, PRIMARY KEY (id), UNIQUE KEY slug (slug), KEY status_start (status,start_date)) $charset;",
		"CREATE TABLE {$p}plugoza_ett_tickets (id bigint(20) unsigned NOT NULL AUTO_INCREMENT, event_id bigint(20) unsigned NOT NULL, name varchar(190) NOT NULL, price decimal(12,2) NOT NULL DEFAULT 0, quantity int(11) unsigned NOT NULL, available_quantity int(11) unsigned NOT NULL, sale_start datetime NULL, sale_end datetime NULL, status varchar(20) NOT NULL DEFAULT 'active', created_at datetime NOT NULL, PRIMARY KEY (id), KEY event_status (event_id,status)) $charset;",
		"CREATE TABLE {$p}plugoza_ett_customers (id bigint(20) unsigned NOT NULL AUTO_INCREMENT, first_name varchar(100) NOT NULL, last_name varchar(100) NOT NULL, email varchar(100) NOT NULL, mobile varchar(50) NOT NULL DEFAULT '', country varchar(2) NOT NULL DEFAULT '', created_at datetime NOT NULL, updated_at datetime NOT NULL, PRIMARY KEY (id), UNIQUE KEY email (email)) $charset;",
		"CREATE TABLE {$p}plugoza_ett_bookings (id bigint(20) unsigned NOT NULL AUTO_INCREMENT, booking_number varchar(40) NOT NULL, event_id bigint(20) unsigned NOT NULL, ticket_id bigint(20) unsigned NOT NULL, customer_id bigint(20) unsigned NOT NULL, quantity int(11) unsigned NOT NULL, amount decimal(12,2) NOT NULL, payment_method varchar(30) NOT NULL DEFAULT '', payment_status varchar(20) NOT NULL DEFAULT 'pending', booking_status varchar(20) NOT NULL DEFAULT 'confirmed', transaction_id varchar(190) NOT NULL DEFAULT '', payment_note text NOT NULL, qr_code varchar(64) NOT NULL, terms_accepted_at datetime NOT NULL, privacy_accepted_at datetime NOT NULL, refund_accepted_at datetime NOT NULL, booking_date datetime NOT NULL, PRIMARY KEY (id), UNIQUE KEY booking_number (booking_number), UNIQUE KEY qr_code (qr_code), KEY event_id (event_id), KEY customer_id (customer_id)) $charset;",
		"CREATE TABLE {$p}plugoza_ett_checkins (id bigint(20) unsigned NOT NULL AUTO_INCREMENT, booking_id bigint(20) unsigned NOT NULL, checked_in tinyint(1) NOT NULL DEFAULT 0, checked_in_at datetime NULL, user_id bigint(20) unsigned NOT NULL DEFAULT 0, PRIMARY KEY (id), UNIQUE KEY booking_id (booking_id)) $charset;"
		);
		foreach ( $sql as $statement ) { dbDelta( $statement ); }
		self::ensure_booking_columns();
		add_option( 'plugoza_ett_settings', array( 'currency' => 'USD' ) );
		add_option( 'plugoza_ett_payment_gateways', \PlugozaEventTicketing\Payment_Gateways::defaults() );
		update_option( 'plugoza_ett_version', PLUGOZA_ETT_VERSION );
	}
	private static function ensure_booking_columns() {
		global $wpdb;
		$table   = $wpdb->prefix . 'plugoza_ett_bookings';
		$columns = $wpdb->get_col( $wpdb->prepare( 'SHOW COLUMNS FROM %i', $table ), 0 );
		if ( ! in_array( 'payment_method', $columns, true ) ) {
			$wpdb->query( $wpdb->prepare( "ALTER TABLE %i ADD payment_method varchar(30) NOT NULL DEFAULT '' AFTER amount", $table ) );
		}
		if ( ! in_array( 'transaction_id', $columns, true ) ) {
			$wpdb->query( $wpdb->prepare( "ALTER TABLE %i ADD transaction_id varchar(190) NOT NULL DEFAULT '' AFTER booking_status", $table ) );
		}
		if ( ! in_array( 'payment_note', $columns, true ) ) {
			$wpdb->query( $wpdb->prepare( 'ALTER TABLE %i ADD payment_note text NOT NULL AFTER transaction_id', $table ) );
		}
	}

	/**
	 * Create the public plugin pages once, without changing existing pages.
	 */
	private static function create_required_pages() {
		$pages = array(
			'events'          => array(
				'title'     => __( 'Events', 'plugoza-event-ticketing' ),
				'shortcode' => '[plugoza_ett_event_list]',
			),
			'book-events'     => array(
				'title'     => __( 'Book Events', 'plugoza-event-ticketing' ),
				'shortcode' => '[plugoza_ett_event_booking]',
			),
			'booking-success' => array(
				'title'     => __( 'Booking Success', 'plugoza-event-ticketing' ),
				'shortcode' => '[plugoza_ett_event_booking_success]',
			),
		);

		$created_pages = array();

		foreach ( $pages as $slug => $page ) {
			$existing = get_page_by_path( $slug );

			if ( $existing instanceof \WP_Post ) {
				$created_pages[ $slug ] = $existing->ID;
				continue;
			}

			$page_id = wp_insert_post(
				array(
					'post_title'   => $page['title'],
					'post_name'    => $slug,
					'post_content' => $page['shortcode'],
					'post_status'  => 'publish',
					'post_type'    => 'page',
				)
			);

			if ( ! is_wp_error( $page_id ) && $page_id ) {
				$created_pages[ $slug ] = absint( $page_id );
			}
		}

		$configured_page_id = absint( get_option( 'plugoza_ett_booking_page_id', 0 ) );
		$configured_page    = $configured_page_id ? get_post( $configured_page_id ) : null;

		if ( ( ! $configured_page || 'page' !== $configured_page->post_type || 'publish' !== $configured_page->post_status ) && ! empty( $created_pages['book-events'] ) ) {
			update_option( 'plugoza_ett_booking_page_id', $created_pages['book-events'] );
		}
	}

	/** Enable the built-in Manual Pay option when the plugin is activated. */
	private static function enable_manual_pay() {
		$settings = get_option( \PlugozaEventTicketing\Payment_Gateways::OPTION, null );

		if ( false === $settings || null === $settings ) {
			update_option( \PlugozaEventTicketing\Payment_Gateways::OPTION, \PlugozaEventTicketing\Payment_Gateways::defaults() );
		}
	}
}
