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

class BingoCR_Activator {

	public static function activate() {
		self::create_tables();
		self::set_default_settings();
		update_option( 'bingocr_db_version', BINGOCR_DB_VERSION );
		flush_rewrite_rules();
	}

	public static function deactivate() {
		flush_rewrite_rules();
	}

	/**
	 * Full data cleanup on uninstall.
	 *
	 * Hooked to Freemius's `after_uninstall` action (not register_uninstall_hook /
	 * uninstall.php), because Freemius requires the uninstall event to be reported
	 * before cleanup — an uninstall.php file would block that.
	 */
	public static function uninstall() {
		global $wpdb;

		$bingocr_tables = array(
			$wpdb->prefix . 'bingocr_cars',
			$wpdb->prefix . 'bingocr_reservations',
			$wpdb->prefix . 'bingocr_locations',
			$wpdb->prefix . 'bingocr_extras',
			$wpdb->prefix . 'bingocr_discounts',
			$wpdb->prefix . 'bingocr_seasonal_prices',
			$wpdb->prefix . 'bingocr_period_pricing',
			$wpdb->prefix . 'bingocr_payments',
		);

		foreach ( $bingocr_tables as $bingocr_table ) {
			// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange
			$wpdb->query( "DROP TABLE IF EXISTS `{$bingocr_table}`" );
		}

		delete_option( 'bingocr_settings' );
		delete_option( 'bingocr_db_version' );
		delete_option( 'bingocr_license_active' ); // legacy fallback option (removed in 1.0.43)
	}

	private static function create_tables() {
		global $wpdb;
		$c = $wpdb->get_charset_collate();
		require_once ABSPATH . 'wp-admin/includes/upgrade.php';

		dbDelta( "CREATE TABLE {$wpdb->prefix}bingocr_cars (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			brand varchar(100) NOT NULL DEFAULT '',
			model varchar(100) NOT NULL DEFAULT '',
			year smallint(4) DEFAULT NULL,
			category varchar(50) NOT NULL DEFAULT '',
			transmission varchar(20) NOT NULL DEFAULT 'manual',
			fuel_type varchar(20) NOT NULL DEFAULT 'petrol',
			seats tinyint(3) unsigned NOT NULL DEFAULT 5,
			price_per_day decimal(10,2) NOT NULL DEFAULT 0.00,
			deposit_type enum('default','percentage','flat') NOT NULL DEFAULT 'default',
			deposit_value decimal(10,2) NOT NULL DEFAULT 0.00,
			image_id bigint(20) unsigned DEFAULT NULL,
			image_url varchar(500) DEFAULT NULL,
			description text DEFAULT NULL,
			features longtext DEFAULT NULL,
			quantity tinyint(3) unsigned NOT NULL DEFAULT 1,
			status enum('available','unavailable','maintenance') NOT NULL DEFAULT 'available',
			sort_order int(11) NOT NULL DEFAULT 0,
			created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY category (category),
			KEY status (status)
		) $c;" );

		dbDelta( "CREATE TABLE {$wpdb->prefix}bingocr_reservations (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			reservation_number varchar(20) NOT NULL DEFAULT '',
			car_id bigint(20) unsigned NOT NULL,
			customer_name varchar(200) NOT NULL DEFAULT '',
			customer_email varchar(200) NOT NULL DEFAULT '',
			customer_phone varchar(50) DEFAULT NULL,
			pickup_date date NOT NULL,
			return_date date NOT NULL,
			pickup_time varchar(10) NOT NULL DEFAULT '10:00',
			return_time varchar(10) NOT NULL DEFAULT '10:00',
			pickup_location_id bigint(20) unsigned DEFAULT NULL,
			dropoff_location_id bigint(20) unsigned DEFAULT NULL,
			status enum('pending','confirmed','active','cancelled','completed') NOT NULL DEFAULT 'pending',
			total_price decimal(10,2) DEFAULT NULL,
			deposit_amount decimal(10,2) NOT NULL DEFAULT 0.00,
			discount_code varchar(50) DEFAULT NULL,
			discount_amount decimal(10,2) NOT NULL DEFAULT 0.00,
			extras longtext DEFAULT NULL,
			notes text DEFAULT NULL,
			payment_method varchar(50) NOT NULL DEFAULT 'cash',
			payment_status varchar(20) NOT NULL DEFAULT 'unpaid',
			paid_amount decimal(10,2) NOT NULL DEFAULT 0.00,
			language varchar(10) NOT NULL DEFAULT 'en',
			created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			UNIQUE KEY reservation_number (reservation_number),
			KEY car_id (car_id),
			KEY status (status),
			KEY pickup_date (pickup_date),
			KEY customer_email (customer_email)
		) $c;" );

		dbDelta( "CREATE TABLE {$wpdb->prefix}bingocr_locations (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			name varchar(200) NOT NULL DEFAULT '',
			address text DEFAULT NULL,
			city varchar(100) DEFAULT NULL,
			phone varchar(50) DEFAULT NULL,
			email varchar(200) DEFAULT NULL,
			opening_hours varchar(100) DEFAULT NULL,
			status enum('active','inactive') NOT NULL DEFAULT 'active',
			sort_order int(11) NOT NULL DEFAULT 0,
			created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY status (status)
		) $c;" );

		dbDelta( "CREATE TABLE {$wpdb->prefix}bingocr_extras (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			name varchar(200) NOT NULL DEFAULT '',
			description text DEFAULT NULL,
			price decimal(10,2) NOT NULL DEFAULT 0.00,
			price_type enum('per_day','flat') NOT NULL DEFAULT 'per_day',
			status enum('active','inactive') NOT NULL DEFAULT 'active',
			sort_order int(11) NOT NULL DEFAULT 0,
			PRIMARY KEY (id)
		) $c;" );

		dbDelta( "CREATE TABLE {$wpdb->prefix}bingocr_seasonal_prices (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			name varchar(200) NOT NULL DEFAULT '',
			start_date date NOT NULL,
			end_date date NOT NULL,
			modifier decimal(6,2) NOT NULL DEFAULT 0.00,
			applies_to enum('all','category') NOT NULL DEFAULT 'all',
			category varchar(50) NOT NULL DEFAULT '',
			priority tinyint(3) NOT NULL DEFAULT 0,
			status enum('active','inactive') NOT NULL DEFAULT 'active',
			created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY status (status),
			KEY start_date (start_date),
			KEY end_date (end_date)
		) $c;" );

		dbDelta( "CREATE TABLE {$wpdb->prefix}bingocr_period_pricing (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			name varchar(200) NOT NULL DEFAULT '',
			pricing_type enum('fixed_total','rate_per_day') NOT NULL DEFAULT 'rate_per_day',
			min_days tinyint(3) unsigned NOT NULL DEFAULT 1,
			max_days tinyint(3) unsigned NOT NULL DEFAULT 30,
			fixed_price decimal(10,2) NOT NULL DEFAULT 0.00,
			price_per_day decimal(10,2) NOT NULL DEFAULT 0.00,
			applies_to enum('all','category','car') NOT NULL DEFAULT 'all',
			category varchar(50) NOT NULL DEFAULT '',
			car_id bigint(20) unsigned DEFAULT NULL,
			priority tinyint(3) NOT NULL DEFAULT 0,
			status enum('active','inactive') NOT NULL DEFAULT 'active',
			created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			PRIMARY KEY (id),
			KEY status (status),
			KEY min_days (min_days),
			KEY max_days (max_days)
		) $c;" );

		dbDelta( "CREATE TABLE {$wpdb->prefix}bingocr_discounts (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			code varchar(50) NOT NULL DEFAULT '',
			type enum('percentage','flat') NOT NULL DEFAULT 'percentage',
			value decimal(10,2) NOT NULL DEFAULT 0.00,
			min_days tinyint(3) unsigned NOT NULL DEFAULT 1,
			max_uses int(11) DEFAULT NULL,
			used_count int(11) NOT NULL DEFAULT 0,
			expires_at date DEFAULT NULL,
			status enum('active','inactive') NOT NULL DEFAULT 'active',
			PRIMARY KEY (id),
			UNIQUE KEY code (code)
		) $c;" );

		dbDelta( "CREATE TABLE {$wpdb->prefix}bingocr_payments (
			id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
			reservation_id bigint(20) unsigned NOT NULL,
			method varchar(20) NOT NULL DEFAULT 'paypal',
			amount decimal(10,2) NOT NULL DEFAULT 0.00,
			currency varchar(10) NOT NULL DEFAULT 'EUR',
			status varchar(20) NOT NULL DEFAULT 'pending',
			paypal_order_id varchar(64) DEFAULT NULL,
			paypal_capture_id varchar(64) DEFAULT NULL,
			payer_email varchar(200) DEFAULT NULL,
			gateway_response longtext DEFAULT NULL,
			created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
			completed_at datetime DEFAULT NULL,
			PRIMARY KEY (id),
			KEY reservation_id (reservation_id),
			KEY paypal_order_id (paypal_order_id)
		) $c;" );
	}

	private static function set_default_settings() {
		if ( get_option( 'bingocr_settings' ) ) {
			return;
		}
		update_option( 'bingocr_settings', array(
			'company_name'         => get_bloginfo( 'name' ),
			'currency'             => 'EUR',
			'currency_symbol'      => '€',
			'currency_position'    => 'before',
			'date_format'          => 'DD/MM/YYYY',
			'min_rental_days'      => 1,
			'max_rental_days'      => 90,
			'advance_booking_days' => 365,
			'default_deposit'      => 0,
			'notify_email'         => get_option( 'admin_email' ),
			'from_name'            => get_bloginfo( 'name' ),
			'from_email'           => get_option( 'admin_email' ),
			'language'             => 'en',
			'auto_detect_language' => false,
			'show_attribution'     => false,
			'theme'                => 'light',
			'primary_color'        => '#e63946',
			'business_hours_start' => '09:00',
			'business_hours_end'   => '18:00',
			'out_of_hours_enabled' => false,
			'out_of_hours_fee'     => 25,
			'terms_conditions'     => '',
			'payment_cash'         => true,
			'payment_card'         => false,
			'payment_bank'         => false,
			'payment_instructions' => '',
			'paypal_enabled'       => false,
			'paypal_mode'          => 'sandbox',
			'paypal_client_id'     => '',
			'paypal_client_secret' => '',
			'paypal_webhook_id'    => '',
		) );
	}
}
