/**
 * Descomplicar® Crescimento Digital
 * https://descomplicar.pt
 */

<?php
/**
 * Plugin Name: KiviCare API
 * Plugin URI: https://descomplicar.pt
 * Description: REST API extension for KiviCare plugin - Healthcare management system
 * Version: 1.0.0
 * Author: Descomplicar® Crescimento Digital
 * Author URI: https://descomplicar.pt
 * Text Domain: kivicare-api
 * Domain Path: /languages
 * Requires at least: 6.0
 * Tested up to: 6.4
 * Requires PHP: 8.1
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 *
 * Network: false
 *
 * KiviCare API is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * any later version.
 *
 * KiviCare API is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * @package KiviCare_API
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Define plugin constants
define( 'KIVICARE_API_VERSION', '1.0.0' );
define( 'KIVICARE_API_FILE', __FILE__ );
define( 'KIVICARE_API_PATH', plugin_dir_path( __FILE__ ) );
define( 'KIVICARE_API_ABSPATH', plugin_dir_path( __FILE__ ) );
define( 'KIVICARE_API_URL', plugin_dir_url( __FILE__ ) );
define( 'KIVICARE_API_BASENAME', plugin_basename( __FILE__ ) );

/**
 * Main KiviCare API class.
 *
 * @class KiviCare_API
 */
final class KiviCare_API {

	/**
	 * The single instance of the class.
	 *
	 * @var KiviCare_API
	 * @since 1.0.0
	 */
	protected static $_instance = null;

	/**
	 * Main KiviCare_API Instance.
	 *
	 * Ensures only one instance of KiviCare_API is loaded or can be loaded.
	 *
	 * @since 1.0.0
	 * @static
	 * @return KiviCare_API - Main instance.
	 */
	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * KiviCare_API Constructor.
	 */
	public function __construct() {
		$this->define_constants();
		$this->includes();
		$this->init_hooks();
	}

	/**
	 * Define KiviCare API Constants.
	 */
	private function define_constants() {
		$this->define( 'KIVICARE_API_CACHE_TTL', 3600 );
		$this->define( 'KIVICARE_API_DEBUG', WP_DEBUG );
	}

	/**
	 * Define constant if not already set.
	 *
	 * @param string      $name  Constant name.
	 * @param string|bool $value Constant value.
	 */
	private function define( $name, $value ) {
		if ( ! defined( $name ) ) {
			define( $name, $value );
		}
	}

	/**
	 * Include required core files.
	 */
	public function includes() {
		/**
		 * Core classes.
		 */
		include_once KIVICARE_API_ABSPATH . 'includes/class-api-init.php';
	}

	/**
	 * Hook into actions and filters.
	 *
	 * @since 1.0.0
	 */
	private function init_hooks() {
		add_action( 'init', array( $this, 'init' ), 0 );
	}

	/**
	 * Init KiviCare API when WordPress Initialises.
	 */
	public function init() {
		// Before init action.
		do_action( 'before_kivicare_api_init' );

		// Set up localisation.
		$this->load_plugin_textdomain();

		// Initialize API.
		if ( class_exists( 'KiviCare_API_Init' ) ) {
			KiviCare_API_Init::instance();
		}

		// Init action.
		do_action( 'kivicare_api_init' );
	}

	/**
	 * Load Localisation files.
	 */
	public function load_plugin_textdomain() {
		load_plugin_textdomain( 'kivicare-api', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
	}

	/**
	 * Get the plugin url.
	 *
	 * @return string
	 */
	public function plugin_url() {
		return untrailingslashit( plugins_url( '/', KIVICARE_API_PLUGIN_FILE ) );
	}

	/**
	 * Get the plugin path.
	 *
	 * @return string
	 */
	public function plugin_path() {
		return untrailingslashit( plugin_dir_path( KIVICARE_API_PLUGIN_FILE ) );
	}

	/**
	 * Get the template path.
	 *
	 * @return string
	 */
	public function template_path() {
		return apply_filters( 'kivicare_api_template_path', 'kivicare-api/' );
	}
}

/**
 * Main instance of KiviCare_API.
 *
 * Returns the main instance of KiviCare_API to prevent the need to use globals.
 *
 * @since  1.0.0
 * @return KiviCare_API
 */
function kivicare_api() {
	return KiviCare_API::instance();
}

/**
 * Check if KiviCare plugin is active.
 *
 * @return bool
 */
function kivicare_api_is_kivicare_active() {
	return is_plugin_active( 'kivicare-clinic-&-patient-management-system/kivicare-clinic-&-patient-management-system.php' );
}

/**
 * Plugin activation hook.
 */
function kivicare_api_activate() {
	// Check if KiviCare plugin is active
	if ( ! kivicare_api_is_kivicare_active() ) {
		wp_die( 
			esc_html__( 'KiviCare Plugin is required to activate KiviCare API.', 'kivicare-api' ),
			esc_html__( 'Plugin Dependency Error', 'kivicare-api' ),
			array( 'back_link' => true )
		);
	}

	// Create capabilities for roles
	$roles = array( 'administrator', 'doctor', 'patient', 'kivicare_receptionist' );
	
	foreach ( $roles as $role_name ) {
		$role = get_role( $role_name );
		if ( $role ) {
			$role->add_cap( 'manage_kivicare_api' );
			
			// Add specific capabilities based on role
			switch ( $role_name ) {
				case 'administrator':
					$role->add_cap( 'kivicare_api_full_access' );
					break;
				case 'doctor':
					$role->add_cap( 'kivicare_api_medical_access' );
					break;
				case 'patient':
					$role->add_cap( 'kivicare_api_patient_access' );
					break;
				case 'kivicare_receptionist':
					$role->add_cap( 'kivicare_api_reception_access' );
					break;
			}
		}
	}

	// Flush rewrite rules to ensure REST API routes work
	flush_rewrite_rules();

	// Set activation flag
	update_option( 'kivicare_api_activated', true );
	update_option( 'kivicare_api_version', KIVICARE_API_VERSION );
}

/**
 * Plugin deactivation hook.
 */
function kivicare_api_deactivate() {
	// Remove capabilities
	$roles = array( 'administrator', 'doctor', 'patient', 'kivicare_receptionist' );
	$capabilities = array( 
		'manage_kivicare_api',
		'kivicare_api_full_access',
		'kivicare_api_medical_access',
		'kivicare_api_patient_access',
		'kivicare_api_reception_access'
	);
	
	foreach ( $roles as $role_name ) {
		$role = get_role( $role_name );
		if ( $role ) {
			foreach ( $capabilities as $cap ) {
				$role->remove_cap( $cap );
			}
		}
	}

	// Flush rewrite rules
	flush_rewrite_rules();

	// Clean up options
	delete_option( 'kivicare_api_activated' );
}

/**
 * Plugin uninstall hook.
 */
function kivicare_api_uninstall() {
	// Clean up all plugin data
	delete_option( 'kivicare_api_version' );
	delete_option( 'kivicare_api_activated' );
	
	// Clear any cached data
	wp_cache_flush();
}

// Hooks
register_activation_hook( __FILE__, 'kivicare_api_activate' );
register_deactivation_hook( __FILE__, 'kivicare_api_deactivate' );
register_uninstall_hook( __FILE__, 'kivicare_api_uninstall' );

// Global for backwards compatibility.
$GLOBALS['kivicare_api'] = kivicare_api();