<?php
/**
 * Plugin Name: Appointment and Booking For Gravity Forms
 * Plugin URI: https://gravitybooking.com/
 * Description: With this GravityForms addon you can implement complete booking and appointments system in your WordPress site.
 * Version: 1.3.2
 * Author: Gravity Booking
 * Author URI: https://profiles.wordpress.org/saadiqbal/
 * License: GPLv2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: appointment-and-booking-for-gravity-forms
 */

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

require_once __DIR__ . '/gravity-form-booking-main.php';

if ( ! function_exists( 'apbgf_plugin_deactivate' ) ) {
	function apbgf_plugin_deactivate() {        
		wp_clear_scheduled_hook( 'apbgf_plugin_cron_hook_for_email' );
	}
}

register_deactivation_hook( __FILE__, 'apbgf_plugin_deactivate' );
register_activation_hook(__FILE__, 'apbgf_default_location');

function apbgf_default_location() {
	if ( ! post_type_exists( 'apbgf-location' ) ) {
		$labels = array(
			'name'               => esc_html__( 'Locations', 'appointment-and-booking-for-gravity-forms' ),
			'singular_name'      => esc_html__( 'Location', 'appointment-and-booking-for-gravity-forms' ),
		);

		$args = array(
			'labels'             => $labels,
			'public'             => false,
			'publicly_queryable' => false,
			'show_ui'            => false,
			'show_in_menu'       => false,
			'show_in_rest'       => false,
			'query_var'          => true,
			'rewrite'            => false,
			'capability_type'    => 'post',
			'has_archive'        => false,
			'hierarchical'       => false,
			'supports'           => array( 'title' ),
		);

		register_post_type( 'apbgf-location', $args );
	}

	$existing = get_posts(array(
		'post_type'   => 'apbgf-location',
		'meta_key'    => '_apbgf_default_location',
		'meta_value'  => '1',
		'numberposts' => 1
	));
	
	if ( empty ( $existing ) ) {
		$old_location = get_posts(array(
			'post_type'   => 'apbgf-location',
			'meta_key'    => '_apbgf_default_location',
			'meta_value'  => '1',
			'numberposts' => 1
		));
		
		if ( ! empty($old_location)) {
			$old_post = $old_location[0];
			$post_id = wp_insert_post(array(
				'post_title'   => $old_post->post_title,
				'post_content' => $old_post->post_content,
				'post_status'  => 'publish',
				'post_type'    => 'apbgf-location',
			));
			
			if ($post_id && !is_wp_error($post_id)) {
				$meta_data = get_post_meta($old_post->ID);
				foreach ($meta_data as $key => $values) {
					foreach ($values as $value) {
						update_post_meta($post_id, $key, $value);
					}
				}
				wp_delete_post($old_post->ID, true);
			}
			return;
		}
		
		$post_id = wp_insert_post(array(
			'post_title'   => 'Default Location',
			'post_content' => '',
			'post_status'  => 'publish',
			'post_type'    => 'apbgf-location',
		));

		if ($post_id && !is_wp_error($post_id)) {
			update_post_meta($post_id, '_apbgf_default_location', '1');
		}
	}

	$current_user_id = get_current_user_id();
	
	if ( $current_user_id ) {
		$user = new WP_User( $current_user_id );
		

		if ( in_array( 'administrator', (array) $user->roles, true ) ) {
			$user->add_role( 'apbgf-staff' );

			$existing_staff = get_posts( array(
				'post_type'  => 'apbgf-staff',
				'meta_key'   => 'wp_user',
				'meta_value' => $current_user_id,
				'numberposts'=> 1,
			) );

			if ( empty( $existing_staff ) ) {
				// Get staff name with fallback
				$staff_name = trim( $user->first_name . ' ' . $user->last_name );
				if ( empty( $staff_name ) ) {
					// Fallback to display_name or user_login if first_name/last_name are empty
					$staff_name = ! empty( $user->display_name ) ? $user->display_name : $user->user_login;
				}

				$args = apply_filters( 'apbgf_add_staff_args', array(
					'post_title'  => $staff_name,
					'post_status' => 'publish',
					'post_type'   => 'apbgf-staff',
					'meta_input'  => array(
						'wp_user'    => $current_user_id,
						'info'       => '',
						'profession' => __( 'Administrator', 'appointment-and-booking-for-gravity-forms' ),
						'phone'      => '',
					)
				));

				$apbgf_user = wp_insert_post( $args );

				if ( $apbgf_user && ! is_wp_error( $apbgf_user ) ) {
					update_user_meta( $current_user_id, 'apbgf_user', $apbgf_user );
				}
			} else {
				// Update existing staff post title if it's empty
				$existing_staff_post = $existing_staff[0];
				if ( empty( trim( $existing_staff_post->post_title ) ) ) {
					$staff_name = trim( $user->first_name . ' ' . $user->last_name );
					if ( empty( $staff_name ) ) {
						$staff_name = ! empty( $user->display_name ) ? $user->display_name : $user->user_login;
					}
					wp_update_post( array(
						'ID' => $existing_staff_post->ID,
						'post_title' => $staff_name,
					) );
				}
			}
		}
	}
}

/**
 * Ensure default location exists (e.g. after adding activation code without re-activating).
 */
function apbgf_ensure_default_location_exists() {
	if ( ! post_type_exists( 'apbgf-location' ) ) {
		return;
	}

	$existing = get_posts(
		array(
			'post_type'   => 'apbgf-location',
			'meta_key'    => '_apbgf_default_location',
			'meta_value'  => '1',
			'numberposts' => 1,
			'post_status' => 'any',
		)
	);

	if ( ! empty( $existing ) ) {
		return;
	}

	$post_id = wp_insert_post(
		array(
			'post_title'   => 'Default Location',
			'post_content' => '',
			'post_status'  => 'publish',
			'post_type'    => 'apbgf-location',
		)
	);

	if ( $post_id && ! is_wp_error( $post_id ) ) {
		update_post_meta( $post_id, '_apbgf_default_location', '1' );
	}
}

add_action( 'init', 'apbgf_ensure_default_location_exists', 25 );