<?php
/**
 * Ad Integration for mobile.de API
 *
 * @package           Mobile_API
 * @author            ComMotion
 * @copyright         2025 ComMotion
 * @license           GPL-2.0-or-later
 *
 * @wordpress-plugin
 * Plugin Name: Ad Integration for mobile.de API
 * Plugin URI: https://commotion.online/en/mobile-api/
 * Description: Plugin to integrate the Ad-Integration for mobile.de via the API and show your vehicles on your website.
 * Network: true
 * Version: 1.3.2
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Requires at least: 6.7
 * Requires PHP: 8.0
 * Author: ComMotion
 * Author URI: https://commotion.online/
 * Text Domain: ad-integration-for-mobile-de-api
 */

defined( 'ABSPATH' ) || exit;

$mobile_api = new mobile_api();
class mobile_api {
	public function __construct() {
		$this->include_all();

		add_action( 'init', array( $this, 'register_vehicle_taxonomy' ) );
		add_action( 'init', array( $this, 'register_vehicle_post_type' ) );
		// add_action( 'init', array( $this, 'register_block_templates' ) );
		add_filter( 'single_template', array( $this, 'single_vehicle_template' ) );
		add_filter( 'archive_template', array( $this, 'archive_vehicle_template' ) );

		// register_deactivation_hook( __FILE__, array( $this, 'on_deactivation' ) );
		// register_uninstall_hook( __FILE__, array( $this, 'on_uninstall' ) );
		// add_action( 'wpmu_new_blog', array( $this, 'on_create_blog' ), 10, 6 );
		// add_filter( 'wpmu_drop_tables', array( $this, 'on_delete_blog' ) );
	}

	public static function include_all() {
		require_once plugin_dir_path( __FILE__ ) . 'includes/functions.php';
		require_once plugin_dir_path( __FILE__ ) . 'includes/assets.php';
		require_once plugin_dir_path( __FILE__ ) . 'includes/ajax.php';
		require_once plugin_dir_path( __FILE__ ) . 'includes/shortcodes.php';
		require_once plugin_dir_path( __FILE__ ) . 'includes/cron.php';
		require_once plugin_dir_path( __FILE__ ) . 'includes/permalinks.php';

		require_once plugin_dir_path( __FILE__ ) . 'includes/admin/single.php';
		require_once plugin_dir_path( __FILE__ ) . 'includes/admin/settings.php';

		require_once plugin_dir_path( __FILE__ ) . 'block/vehicle-archive/index.php';

		if ( did_action( 'elementor/loaded' ) || ( defined( 'ELEMENTOR_PATH' ) && class_exists( 'Elementor\Plugin' ) ) )
			require_once plugin_dir_path( __FILE__ ) . 'block/elementor/index.php';
	}

	public function register_vehicle_taxonomy() {
		$labels = array(
			'name'              => _x( 'Vehicle Categories', 'taxonomy general name', 'ad-integration-for-mobile-de-api' ),
			'singular_name'     => _x( 'Vehicle Category', 'taxonomy singular name', 'ad-integration-for-mobile-de-api' ),
			'search_items'      => __( 'Search Vehicle Categories', 'ad-integration-for-mobile-de-api' ),
			'all_items'         => __( 'All Vehicle Categories', 'ad-integration-for-mobile-de-api' ),
			'parent_item'       => __( 'Parent Vehicle Category', 'ad-integration-for-mobile-de-api' ),
			'parent_item_colon' => __( 'Parent Vehicle Category:', 'ad-integration-for-mobile-de-api' ),
			'edit_item'         => __( 'Edit', 'ad-integration-for-mobile-de-api' ), 
			'update_item'       => __( 'Update', 'ad-integration-for-mobile-de-api' ),
			'add_new_item'      => __( 'Add New', 'ad-integration-for-mobile-de-api' ),
			'new_item_name'     => __( 'New Vehicle Category Name', 'ad-integration-for-mobile-de-api' ),
			'menu_name'         => __( 'Vehicle Categories', 'ad-integration-for-mobile-de-api' ),
		);

		register_taxonomy( 'mobile_api_vehicle_category', array( 'mobile-api-vehicle' ), array(
			'hierarchical'      => true,
			'labels'            => $labels,
			'public'            => true,
			'show_ui'           => true,
			'show_in_rest'      => true,
			'show_admin_column' => true,
			'query_var'         => true,
			'rewrite'           => array( 'slug' => get_option( 'mobile_api_custom_term', 'vehicles' ) ),
		));
	}

	public function register_vehicle_post_type() {
		$labels = array(
			'name'               => _x( 'Vehicles', 'post type general name', 'ad-integration-for-mobile-de-api' ),
			'singular_name'      => _x( 'Vehicle', 'post type singular name', 'ad-integration-for-mobile-de-api' ),
			'add_new'            => __( 'Add New', 'ad-integration-for-mobile-de-api' ),
			'add_new_item'       => __( 'Add New', 'ad-integration-for-mobile-de-api' ),
			'edit_item'          => __( 'Edit', 'ad-integration-for-mobile-de-api' ),
			'new_item'           => __( 'Add New', 'ad-integration-for-mobile-de-api' ),
			'all_items'          => __( 'All Vehicles', 'ad-integration-for-mobile-de-api' ),
			'view_item'          => __( 'View', 'ad-integration-for-mobile-de-api' ),
			'search_items'       => __( 'Search Vehicles', 'ad-integration-for-mobile-de-api' ),
			'not_found'          => __( 'No Vehicles found.', 'ad-integration-for-mobile-de-api' ),
			'not_found_in_trash' => __( 'No Vehicles found in Trash.', 'ad-integration-for-mobile-de-api' ),
			'parent_item_colon'  => '',
			'menu_name'          => __( 'Vehicles', 'ad-integration-for-mobile-de-api' ),
		);

		$args = array(
			'label'               => __( 'Vehicle', 'ad-integration-for-mobile-de-api' ),
			'description'         => __( 'Vehicles', 'ad-integration-for-mobile-de-api' ),
			'labels'              => $labels,
			'supports'            => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions', 'custom-fields' ),
			'taxonomies'          => array( 'mobile_api_vehicle_category' ),
			'hierarchical'        => false,
			'public'              => true,
			'show_ui'             => true,
			'show_in_menu'        => true,
			'show_in_nav_menus'   => true,
			'show_in_admin_bar'   => true,
			'menu_position'       => 5,
			'menu_icon'           => 'dashicons-car',
			'can_export'          => true,
			'exclude_from_search' => false,
			'publicly_queryable'  => true,
			'show_in_rest'        => true,
			'map_meta_cap'        => true,
			'has_archive'         => get_option( 'mobile_api_custom_term', 'vehicles' ),
			'rewrite'             => array(
				'slug' => get_option( 'mobile_api_custom_slug', 'vehicle' ),
				'with_front' => false
			)
		);

		register_post_type( 'mobile-api-vehicle', $args );
	}

	/* public function register_block_templates() {
		if ( function_exists( 'register_block_template' ) ) {
			$base_path = plugin_dir_path( __FILE__ ).'templates/';

			// Single
			register_block_template( 'single-vehicle',
				array(
					'post_types' => array( 'vehicle' ),
					'source'     => 'plugin',
					'file'       => $base_path.'single-vehicle.html',
				)
			);

			// Archive
			register_block_template( 'archive-vehicle',
				array(
					'post_types' => array( 'vehicle' ),
					'source'     => 'plugin',
					'file'       => $base_path.'archive-vehicle.html',
				)
			);

			// Search
			register_block_template( 'search-vehicle',
				array(
					'post_types' => array( 'vehicle' ),
					'source'     => 'plugin',
					'file'       => $base_path.'search-vehicle.html',
				)
			);
		}
	} */

	public function single_vehicle_template( $single ) {
		if ( /* ( !function_exists( 'wp_is_block_theme' ) || !wp_is_block_theme() ) && */ is_singular( 'mobile-api-vehicle' ) ) {
			$theme_templates = array(
				'single-ad-integration-for-mobile-de-api-vehicle.php', // Default WP naming
				'ad-integration-for-mobile-de-api-single-vehicle.php', // Alternate WP naming
				'ad-integration-for-mobile-de-api/single-vehicle.php' // optional structural override
			);
			$theme_template = locate_template( $theme_templates );
			if ( !empty( $theme_template ) )
				return $theme_template;

			$plugin_template = plugin_dir_path( __FILE__ ).'templates/single-vehicle.php';
			if ( file_exists( $plugin_template ) )
				return $plugin_template;
		}

		return $single;
	}

	public function archive_vehicle_template( $archive ) {
		global $post;
	    if ( is_post_type_archive( 'mobile-api-vehicle' ) ) {
	        $plugin_template = plugin_dir_path( __FILE__ ).'templates/archive-vehicle.php';

	        if ( file_exists( $plugin_template ) )
	            return $plugin_template;
	    }

	    return $archive;
	}

	/* public static function on_activation() {
		require_once plugin_dir_path( __FILE__ ) . 'includes/db/create.php';
		flush_rewrite_rules();
	}

	public static function on_deactivation() {
		flush_rewrite_rules();
		wp_cache_flush();
	}

	public static function on_uninstall() {
		require_once plugin_dir_path( __FILE__ ) . 'includes/db/drop.php';
	}

	public static function on_create_blog( $blog_id, $user_id, $domain, $path, $site_id, $meta ) {
		if ( is_plugin_active_for_network( dirname( plugin_basename( __FILE__ ) ) . '/' . dirname( plugin_basename( __FILE__ ) ) . '.php' ) ) {
			switch_to_blog($blog_id);

			require_once plugin_dir_path( __FILE__ ) . 'includes/db/create.php';

			restore_current_blog();
		}
	}

	public static function on_delete_blog($tables) {
		require_once plugin_dir_path( __FILE__ ) . 'includes/db/drop.php';
	} */
}

function mobile_api_on_activation() {
	$plugin = new mobile_api();
	$plugin->register_vehicle_taxonomy();
	$plugin->register_vehicle_post_type();

	if ( is_multisite() ) {
		$sites = get_sites();
		if ( is_plugin_active_for_network( __FILE__ ) ) {
			foreach ( $sites as $site ) {
				switch_to_blog( $site->blog_id );

				require plugin_dir_path( __FILE__ ) . 'includes/db/create.php';

				restore_current_blog();
			}
		} else {
			require plugin_dir_path( __FILE__ ) . 'includes/db/create.php';
		}
	} else {
		require plugin_dir_path( __FILE__ ) . 'includes/db/create.php';
	}

	flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'mobile_api_on_activation' );

function mobile_api_on_deactivation() {
	flush_rewrite_rules();
	wp_cache_flush();
}
register_deactivation_hook( __FILE__, 'mobile_api_on_deactivation' );

function mobile_api_on_uninstall() {
	// Delete databases
	include_once plugin_dir_path( __FILE__ ) . 'includes/db/drop.php';

	// Delete options
	global $wpdb;
	// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query( "DELETE FROM `".$wpdb->prefix."options` WHERE `option_name` LIKE ('mobile_api%')" );

	// Delete posts
	mobile_api_delete_vehicles( true );

	// Delete terms
	$args = array(
		'taxonomy' => 'mobile_api_vehicle_category',
		'hide_empty' => false
	);
	$terms = get_terms( $args );
	foreach ( $terms as $term )
		wp_delete_term( $term->term_id, 'mobile_api_vehicle_category' );
}
register_uninstall_hook( __FILE__, 'mobile_api_on_uninstall' );

function mobile_api_on_create_blog( $blog_id, $user_id, $domain, $path, $site_id, $meta ) {
	if ( is_plugin_active_for_network( dirname( plugin_basename( __FILE__ ) ) . '/' . dirname( plugin_basename( __FILE__ ) ) . '.php' ) ) {
		switch_to_blog( $blog_id );

		require_once plugin_dir_path( __FILE__ ) . 'includes/db/create.php';

		restore_current_blog();
	}
}
add_action( 'wpmu_new_blog', 'mobile_api_on_create_blog', 10, 6 );

function mobile_api_on_delete_blog( $tables ) {
	include_once plugin_dir_path( __FILE__ ) . 'includes/db/drop.php';
}
add_filter( 'wpmu_drop_tables', 'mobile_api_on_delete_blog' );

// Admin notices
function mobile_api_plugin_check() {
	if ( is_admin() )
		add_action( 'admin_notices', 'mobile_api_shortcode_notice' );
}
add_action( 'admin_init', 'mobile_api_plugin_check' );

function mobile_api_shortcode_notice() {
	$screen = get_current_screen();
	if ( sanitize_key( $screen->id ) == 'edit-mobile-api-vehicle' ) :
		?>
		<div class="notice notice-success is-dismissible">
			<p>
				<?php
				// translators: %s is the shortcode [vehicle-archive]
				echo sprintf( esc_html__( 'To display the vehicles on any page as an archive, you can embed them using a block in the Gutenberg editor or the shortcode %s.', 'ad-integration-for-mobile-de-api' ), '<code>[mobile-api-vehicle-archive]</code>' );
				?>
			</p>
			<p><a href="<?php esc_html_e( 'https://commotion.online/en/mobile-api-documentation/shortcodes-mobile-api/', 'ad-integration-for-mobile-de-api' ) ?>" target="_blank" class="button button-primary"><?php esc_html_e( 'More information about Shortcodes', 'ad-integration-for-mobile-de-api' ); ?></a></p>
		</div>
		<?php
	endif;
}

function mobile_api_get_version_number() {
	$plugin_data = get_plugin_data( __FILE__ );
	return $plugin_data['Version'];
}