<?php
/**
 * Plugin activation tasks.
 *
 * @package Logistica
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Handles activation-time setup.
 */
class Logistica_Activator {
	/**
	 * Creates database structures and stores plugin version.
	 *
	 * @return void
	 */
	public static function activate() {
		Logistica_Database::create_tables();
		require_once LOGISTICA_PLUGIN_DIR . 'includes/class-logistica-roles.php';
		Logistica_Roles::register_roles();
		Logistica_Roles::ensure_backend_page();
		self::create_frontend_page();

		add_option( 'logistica_version', LOGISTICA_VERSION );
		add_option( 'logistica_roles_initialized', true, false );
	}

	/**
	 * Creates a simple frontend page with the inventory panel shortcode.
	 *
	 * @return void
	 */
	private static function create_frontend_page() {
		$page_id = (int) get_option( 'logistica_frontend_page_id', 0 );

		if ( $page_id && 'trash' !== get_post_status( $page_id ) ) {
			return;
		}

		$existing = get_page_by_path( 'latingraf-inventarios' );
		if ( $existing ) {
			update_option( 'logistica_frontend_page_id', (int) $existing->ID );
			return;
		}

		$new_page_id = wp_insert_post(
			array(
				'post_title'   => 'Latingraf Inventarios',
				'post_name'    => 'latingraf-inventarios',
				'post_content' => '[logistica_panel]',
				'post_status'  => 'publish',
				'post_type'    => 'page',
			)
		);

		if ( ! is_wp_error( $new_page_id ) ) {
			update_option( 'logistica_frontend_page_id', (int) $new_page_id );
		}
	}
}
