<?php
/**
 * Plugin Name: Bookify – Appointment Booking & Scheduling for WordPress
 * Plugin URI: https://www.wpbookify.com
 * Description: Bookify is a WordPress appointment booking plugin for scheduling services and managing online bookings.
 * Version: 1.3.3
 * Tags: bookings, appointments
 * Author: Bookify
 * Author URI: https://wpbookify.com/
 * Requires at least: 6.2
 * Tested up to: 6.9
 * Text Domain: bookify
 * License: GPLv2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 */

 namespace Bookify;

 use Bookify\Models\Bookify_Models;
 use Bookify\Controllers\Admin\Bookify_Menu;
 use Bookify\Controllers\Admin\Bookify_Emails;
 use Bookify\Controllers\REST\Bookify_Services_Rest_API;
 use Bookify\Controllers\REST\Bookify_Staffs_Rest_API;
 use Bookify\Controllers\REST\Bookify_Customers_Rest_API;
 use Bookify\Controllers\REST\Bookify_Settings_Rest_API;
 use Bookify\Controllers\REST\Bookify_Notification_Rest_API;
 use Bookify\Controllers\REST\Bookify_Appointments_Rest_API;
 use Bookify\Controllers\REST\Bookify_Payment_Rest_API;
 use Bookify\Controllers\REST\Bookify_Calendar_Rest_API;
 use Bookify\Controllers\REST\Bookify_Dashboard_Rest_API;
 use Bookify\Controllers\REST\Bookify_Frontend_Rest_API;
 use Bookify\Controllers\REST\Bookify_Onboarding_Rest_API;
 use Bookify\Controllers\Frontend\Bookify_Shortcodes;

// don't call the file directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! function_exists( 'bookify_fs' ) ) {
    // Create a helper function for easy SDK access.
    function bookify_fs() {

        global $bookify_fs;

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

			if ( get_option( 'bookify_onboarding_completed', false ) ) {
				$redirect_path = 'admin.php?page=bookify';
			} else {
				$redirect_path = 'admin.php?page=bookify#/wizard';
			}

            $bookify_fs = fs_dynamic_init( array(
                'id'             => '17388',
                'slug'           => 'bookify',
				'premium_slug'   => 'bookify-premium',
                'type'           => 'plugin',
                'public_key'     => 'pk_235118704b81fa12e82248e4416af',
                'is_premium'     => false,
                'has_addons'     => false,
                'has_paid_plans' => true,
                'menu'           => array(
                    'slug'    => 'bookify',
					'first-path' => $redirect_path,
                    'contact' => false,
                    'support' => false,
                ),
				'parallel_activation' => array(
					'enabled'                  => true,
					'premium_version_basename' => 'bookify-premium/bookify-pro.php',
				),
                'is_live'        => true,
            ) );
        }
		
        return $bookify_fs;
    }

    // Init Freemius.
    bookify_fs();
    // Signal that SDK was initiated.
    do_action( 'bookify_fs_loaded' );
}

if ( ! class_exists( 'Bookify_Main' ) ) {

	final class Bookify_Main { 

		 /**
		 * Plugin version
		 *
		 * @var string
		 */
		public $version = '1.3.3';

		/**
		 * Constructor for the Bookify_Main class
		 *
		 * Sets up all the appropriate hooks and actions
		 * within our plugin.
		 */
		public function __construct() {
			
			$this->define_constants();

			require_once BOOKIFY_DIR . '/vendor/autoload.php';

			register_activation_hook( __FILE__, array( $this, 'bookify_network_activation' ) );

			add_action( 'wp_initialize_site', array( $this, 'bookify_initialize_site' ), 10, 2);

			add_action( 'init', array( $this, 'init_plugin' ) );

			add_action( 'admin_footer', array( $this, 'highlight_bookify_menu') );

			add_action( 'admin_init', array( $this, 'check_wizard_redirect' ) );

		}

		public function check_wizard_redirect() {
			$wizard_completed = get_option( 'bookify_onboarding_completed', false );
			if ( ! $wizard_completed ) {
				$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
				if ( $page === 'bookify' ) {
					?>
					<script>
						if (window.location.hash !== '#/wizard') {
							window.location.href = "<?php echo esc_url( admin_url( 'admin.php?page=bookify#/wizard' ) ); ?>";
						}
					</script>
					<?php
				}
			}
		}

		public function bookify_network_activation() {
			if ( is_multisite() ) {
				$sites = get_sites();
				$super_admins = get_super_admins();
				
				foreach ( $sites as $site ) {
					switch_to_blog( $site->blog_id );

					$this->bookify_activation();

					foreach ( $super_admins as $username ) {
						$user = get_user_by( 'login', $username );
						if ( $user && ! is_user_member_of_blog( $user->ID, $site->blog_id ) ) {
							add_user_to_blog( $site->blog_id, $user->ID, 'administrator' );
						}
					}

					restore_current_blog();
				}
			} else {
				$this->bookify_activation();
			}
		}

		public function bookify_initialize_site( $site, $args ) {
			if ( is_plugin_active_for_network( plugin_basename( __FILE__ ) ) ) {
				switch_to_blog( $site->blog_id );
				$super_admins = get_super_admins();

				foreach ( $super_admins as $username ) {
					$user = get_user_by( 'login', $username );
					if ( $user && ! is_user_member_of_blog( $user->ID, $site->blog_id ) ) {
						add_user_to_blog( $site->blog_id, $user->ID, 'administrator' );
					}
				}

				$this->bookify_activation();
				restore_current_blog();
			}
		}

		/**
		 * Highlight Selected Bookify Menu
		 *
		 * @return void
		 */
		public function highlight_bookify_menu() {
			global $current_screen;
		
			if ( isset( $current_screen->id ) && 'toplevel_page_bookify' === $current_screen->id ) {
				?>
				<script type="text/javascript">
					function updateMenuHighlight() {
						var hash = window.location.hash;
						var menuItems = jQuery('#adminmenu .toplevel_page_bookify ul.wp-submenu li');
						menuItems.removeClass('current');
						var targetItem = hash ? menuItems.find('a[href$="' + hash + '"]').parent() : menuItems.filter('.wp-first-item');
						if (targetItem.length) targetItem.addClass('current');
					}
					jQuery(window).on('hashchange', updateMenuHighlight);
					updateMenuHighlight();
				</script>
				<?php
			}
		}

		/**
		 * Define all constants
		 *
		 * @return void
		 */
		public function define_constants() {
			$this->define( 'BOOKIFY_VERSION', $this->version );
			$this->define( 'BOOKIFY_FILE_PATH', plugin_dir_path( __FILE__ ) );
			$this->define( 'BOOKIFY_FILE_URL', plugin_dir_url( __FILE__ ) );
			$this->define( 'BOOKIFY_DIR', __DIR__ );
			$this->define( 'BOOKIFY_CONTROLLER_DIR', __DIR__ . '/Controllers' );
			$this->define( 'BOOKIFY_MODEL_DIR', BOOKIFY_DIR . '/Models' );
		}

		/**
		 * Define constant if not already defined
		 *
		 * @since 1.0.0
		 *
		 * @param string      $name
		 * @param string|bool $value
		 *
		 * @return void
		 */
		private function define( $bookify_name, $bookify_value ) {
			if ( ! defined( $bookify_name ) ) {
				define( $bookify_name, $bookify_value );
			}
		}

		/**
		 * Placeholder for activation function
		 *
		 * Nothing being called here yet.
		 */
		public function bookify_activation() {
			Bookify_Models::bookify_create_tables();

			add_role(
				'bookify-staff',
				__( 'WPB Staff', 'bookify'  ),
			);

			$staff_role = get_role('bookify-staff');

			if ( $staff_role ) {
				$staff_role->add_cap('read');
				$staff_role->add_cap('view_admin_dashboard');
				$staff_role->add_cap('bookify_staff_pages');
			}

			$admin_role = get_role('administrator');
			if ( $admin_role ) {
				$admin_role->add_cap('view_admin_dashboard');
				$admin_role->add_cap('bookify_staff_pages');
			}

			add_role(
				'bookify-customer',
				__( 'WPB Customer', 'bookify'  ),
			);

			$customer_role = get_role('bookify-customer');

			if ( $customer_role ) {
				$customer_role->add_cap('read');
			}
		}
		
		/**
		 * Load the plugin after WP User Frontend is loaded
		 *
		 * @return void
		 */
		public function init_plugin() {

			require_once BOOKIFY_MODEL_DIR . '/Bookify_Meta_Handlers.php' ;

			$this->register_assets();

			new Bookify_Menu();
			new Bookify_Emails();
			new Bookify_Services_Rest_API();
			new Bookify_Staffs_Rest_API();
			new Bookify_Customers_Rest_API();
			new Bookify_Settings_Rest_API();
			new Bookify_Notification_Rest_API();
		    new Bookify_Appointments_Rest_API();
			new Bookify_Payment_Rest_API();
			new Bookify_Calendar_Rest_API();
			new Bookify_Dashboard_Rest_API();
			new Bookify_Frontend_Rest_API();
			new Bookify_Onboarding_Rest_API();
			new Bookify_Shortcodes();
		}

		public function register_assets() {

			wp_register_style( 'tailwind-css', "https://cdn.tailwindcss.com", array(), $this->version, 'all' );
			wp_register_style( 'bookify-frontend-default-style', plugins_url( 'build/default-theme.css', __FILE__ ), array(), $this->version, 'all' );
			wp_register_style( 'bookify-frontend-light-style', plugins_url( 'build/light-theme.css', __FILE__ ), array(), $this->version, 'all' );
			wp_register_script( 'bookify-frontend-script', plugins_url( 'build/frontend.bundle.js', __FILE__ ), array( 'wp-element', 'wp-i18n' ), $this->version, true );
			wp_register_script( 'bookify-appointments-script', plugins_url( 'build/appointments.bundle.js', __FILE__ ), array( 'wp-element', 'wp-i18n' ), $this->version, true );
		}
	}

	new Bookify_Main();
}
