<?php
/**
 * Plugin Name:       MerchantKits Attendance Manager
 * Plugin URI:        https://merchantkits.com/attendance/
 * Description:       AI-powered attendance tracking and leave management for small businesses. Clock in/out, shift management, leave requests, smart reports, and AI attendance insights — all from your WordPress dashboard.
 * Version:           1.1.2
 * Requires at least: 6.0
 * Tested up to:      7.0
 * Requires PHP:      8.0
 * Author:            MerchantKits
 * Author URI:        https://merchantkits.com
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       merchantkits-attendance-manager
 * Domain Path:       /languages
 *
 * @package MerchantKits\AttendanceManager
 */

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

if ( ! function_exists( 'mkam_fs' ) ) {
	// Create a helper function for easy SDK access.
	function mkam_fs() {
		global $mkam_fs;

		if ( ! isset( $mkam_fs ) ) {
			// Include Freemius SDK.
			require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';

			$mkam_fs = fs_dynamic_init( array(
				'id'                  => '33298',
				'slug'                => 'merchantkits-attendance-manager',
				'type'                => 'plugin',
				'public_key'          => 'pk_f9756b5b9c3b5f1d32cc7624df620',
				'is_premium'          => false,
				'premium_suffix'      => 'Pro',
				'has_premium_version' => true,
				'has_addons'          => false,
				'has_paid_plans'      => true,
				'is_org_compliant'    => true,
				'trial'               => array(
					'days'               => 7,
					'is_require_payment' => false,
				),
				'menu'                => array(
					'slug'    => 'mkam-dashboard',
					'support' => false,
				),
			) );
		}

		return $mkam_fs;
	}

	// Init Freemius.
	mkam_fs();
	// Signal that SDK was initiated.
	do_action( 'mkam_fs_loaded' );
}

/**
 * Plugin constants.
 */
define( 'MKAM_VERSION', '1.1.2' );
define( 'MKAM_PLUGIN_FILE', __FILE__ );
define( 'MKAM_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'MKAM_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
define( 'MKAM_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
define( 'MKAM_INCLUDES_DIR', MKAM_PLUGIN_DIR . 'includes/' );
define( 'MKAM_TEMPLATES_DIR', MKAM_PLUGIN_DIR . 'templates/' );
define( 'MKAM_DB_VERSION', '1.0.0' );

/**
 * PSR-style autoloader for plugin classes.
 *
 * Maps a class name such as MKAM_Employee to includes/class-employee.php
 * and MKAM_Admin_Employees_Table to includes/class-admin-employees-table.php.
 *
 * @param string $class_name Fully qualified class name being loaded.
 * @return void
 */
function mkam_autoload( $class_name ) {
	if ( 0 !== strpos( $class_name, 'MKAM_' ) ) {
		return;
	}

	$class_slug = strtolower( str_replace( '_', '-', substr( $class_name, 5 ) ) );
	$file       = MKAM_INCLUDES_DIR . 'class-' . $class_slug . '.php';

	if ( is_readable( $file ) ) {
		require_once $file;
	}
}
spl_autoload_register( 'mkam_autoload' );

/**
 * Activation hook.
 *
 * @return void
 */
function mkam_activate() {
	require_once MKAM_INCLUDES_DIR . 'class-activator.php';
	MKAM_Activator::activate();
}
register_activation_hook( __FILE__, 'mkam_activate' );

/**
 * Deactivation hook.
 *
 * @return void
 */
function mkam_deactivate() {
	require_once MKAM_INCLUDES_DIR . 'class-activator.php';
	MKAM_Activator::deactivate();
}
register_deactivation_hook( __FILE__, 'mkam_deactivate' );

/**
 * Boot the plugin core once all plugins are loaded.
 *
 * @return void
 */
function mkam_init() {
	if ( class_exists( 'MKAM_Core' ) ) {
		MKAM_Core::instance();
	}
}
add_action( 'plugins_loaded', 'mkam_init' );

/**
 * Register the uninstall cleanup with Freemius (replaces uninstall.php).
 */
if ( function_exists( 'mkam_fs' ) ) {
	mkam_fs()->add_action( 'after_uninstall', 'mkam_fs_uninstall_cleanup' );
}

/**
 * Freemius after-uninstall callback. Removes plugin data only when the site
 * owner opted in via the "Remove all data on uninstall" setting.
 *
 * @return void
 */
function mkam_fs_uninstall_cleanup() {
	global $wpdb;

	if ( ! get_option( 'mkam_delete_data_on_uninstall', 0 ) ) {
		return;
	}

	$tables = array(
		$wpdb->prefix . 'mkam_attendance',
		$wpdb->prefix . 'mkam_leaves',
		$wpdb->prefix . 'mkam_leave_policies',
		$wpdb->prefix . 'mkam_shifts',
		$wpdb->prefix . 'mkam_employees',
	);

	foreach ( $tables as $table ) {
		// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange
		$wpdb->query( "DROP TABLE IF EXISTS {$table}" );
	}

	$options = array(
		'mkam_db_version', 'mkam_company_name', 'mkam_financial_year_start',
		'mkam_date_format', 'mkam_week_start', 'mkam_currency',
		'mkam_enable_geolocation', 'mkam_restrict_ip', 'mkam_allowed_ips',
		'mkam_auto_clock_out', 'mkam_auto_clock_out_buffer', 'mkam_overtime_threshold',
		'mkam_enable_clock_in_note', 'mkam_enable_employee_pin', 'mkam_notify_admin_clock_in',
		'mkam_notify_admin_leave_request', 'mkam_notify_employee_leave_decision', 'mkam_admin_email',
		'mkam_enable_weekly_digest', 'mkam_weekly_digest_day', 'mkam_openai_api_key',
		'mkam_ai_model', 'mkam_delete_data_on_uninstall', 'mkam_employee_role', 'mkam_items_per_page',
		'mkam_geofence_enable', 'mkam_geofence_lat', 'mkam_geofence_lng', 'mkam_geofence_radius',
	);

	foreach ( $options as $option ) {
		delete_option( $option );
	}

	// phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared
	$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_transient\_mkam\_%' OR option_name LIKE '\_transient\_timeout\_mkam\_%'" );

	$hooks = array( 'mkam_auto_clock_out', 'mkam_daily_absent_marker', 'mkam_weekly_digest', 'mkam_leave_year_reset' );
	foreach ( $hooks as $hook ) {
		wp_clear_scheduled_hook( $hook );
	}
}
