<?php
/**
 * Descomplicar® Crescimento Digital
 * https://descomplicar.pt
 */
/**
 * Plugin Name: Care API
 * Plugin URI: https://descomplicar.pt
 * Description: REST API extension for Care plugin - Healthcare management system
 * Version: 1.0.0
 * Author: Descomplicar® Crescimento Digital
 * Author URI: https://descomplicar.pt
 * Text Domain: care-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
 *
 * Care 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.
 *
 * Care 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 Care_API
 */

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

// Define plugin constants
define( 'CARE_API_VERSION', '1.0.0' );
define( 'CARE_API_FILE', __FILE__ );
define( 'CARE_API_PATH', plugin_dir_path( __FILE__ ) );
define( 'CARE_API_ABSPATH', plugin_dir_path( __FILE__ ) );
define( 'CARE_API_URL', plugin_dir_url( __FILE__ ) );
define( 'CARE_API_BASENAME', plugin_basename( __FILE__ ) );

/**
 * Main Care API class.
 *
 * @class Care_API
 */
final class Care_API {

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

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

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

	/**
	 * Define Care API Constants.
	 */
	private function define_constants() {
		$this->define( 'CARE_API_CACHE_TTL', 3600 );
		$this->define( 'CARE_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 CARE_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 Care API when WordPress Initialises.
	 */
	public function init() {
		// Before init action.
		do_action( 'before_care_api_init' );

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

		// Initialize API.
		if ( class_exists( 'Care_API\\API_Init' ) ) {
			\Care_API\API_Init::instance();
		}

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

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

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

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

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

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

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

/**
 * Plugin activation hook.
 */
function care_api_activate() {
	// Check if Care plugin is active
	if ( ! care_api_is_kivicare_active() ) {
		wp_die( 
			esc_html__( 'Care Plugin is required to activate Care API.', 'care-api' ),
			esc_html__( 'Plugin Dependency Error', 'care-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_care_api' );
			
			// Add specific capabilities based on role
			switch ( $role_name ) {
				case 'administrator':
					$role->add_cap( 'care_api_full_access' );
					break;
				case 'doctor':
					$role->add_cap( 'care_api_medical_access' );
					break;
				case 'patient':
					$role->add_cap( 'care_api_patient_access' );
					break;
				case 'kivicare_receptionist':
					$role->add_cap( 'care_api_reception_access' );
					break;
			}
		}
	}

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

	// Set activation flag
	update_option( 'care_api_activated', true );
	update_option( 'care_api_version', CARE_API_VERSION );
}

/**
 * Plugin deactivation hook.
 */
function care_api_deactivate() {
	// Remove capabilities
	$roles = array( 'administrator', 'doctor', 'patient', 'kivicare_receptionist' );
	$capabilities = array( 
		'manage_care_api',
		'care_api_full_access',
		'care_api_medical_access',
		'care_api_patient_access',
		'care_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( 'care_api_activated' );
}

/**
 * Plugin uninstall hook.
 */
function care_api_uninstall() {
	// Clean up all plugin data
	delete_option( 'care_api_version' );
	delete_option( 'care_api_activated' );
	
	// Clear any cached data
	wp_cache_flush();
}

// Hooks
register_activation_hook( __FILE__, 'care_api_activate' );
register_deactivation_hook( __FILE__, 'care_api_deactivate' );
register_uninstall_hook( __FILE__, 'care_api_uninstall' );

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