<?php
/**
 * Admin Locations Management
 *
 * Handles the locations management admin page
 *
 * @package    Karate_Club_Manager
 * @subpackage Karate_Club_Manager/includes/admin
 * @since      1.0.0
 */

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

/**
 * Class MACM_Admin_Locations
 *
 * Manages the locations admin interface
 *
 * @since 1.0.0
 */
class MACM_Admin_Locations {

	/**
	 * Constructor
	 *
	 * @since 1.0.0
	 */
	public function __construct() {
		add_action( 'admin_menu', array( $this, 'add_menu_page' ), 16 );
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'admin_post_macm_save_location', array( $this, 'save_location' ) );
		add_action( 'admin_post_macm_delete_location', array( $this, 'delete_location' ) );
	}

	/**
	 * Add submenu page
	 *
	 * @since 1.0.0
	 */
	public function add_menu_page() {
		add_submenu_page(
			'martial-arts-club-manager',
			__( 'Locations', 'martial-arts-club-manager' ),
			__( 'Locations', 'martial-arts-club-manager' ),
			'manage_macm_classes',
			'kcm-locations',
			array( $this, 'render_page' )
		);
	}

	/**
	 * Enqueue scripts for locations page
	 *
	 * @since 1.0.174
	 * @param string $hook Current admin page hook.
	 */
	public function enqueue_scripts( $hook ) {
		// Only load on locations page.
		if ( false === strpos( $hook, 'kcm-locations' ) ) {
			return;
		}

		wp_enqueue_script(
			'kcm-admin-locations',
			MACM_PLUGIN_URL . 'assets/js/admin-locations.js',
			array( 'jquery' ),
			MACM_VERSION,
			true
		);
	}

	/**
	 * Render the locations page
	 *
	 * @since 1.0.0
	 */
	public function render_page() {
		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'You do not have permission to access this page.', 'martial-arts-club-manager' ) );
		}

		// Get all locations (including inactive).
		$locations = MACM_Location::get_all( false );

		// Get message from transient (set by save/delete handlers).
		$message       = '';
		$error         = '';
		$transient_key = 'macm_location_message_' . get_current_user_id();
		$transient     = get_transient( $transient_key );

		if ( $transient ) {
			delete_transient( $transient_key );
			$message = isset( $transient['type'] ) ? $transient['type'] : '';
			$error   = isset( $transient['error'] ) ? $transient['error'] : '';
		}

		// Get location to edit (with nonce verification).
		$edit_location = null;
		$edit_nonce    = filter_input( INPUT_GET, '_wpnonce', FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		$edit_id_input = filter_input( INPUT_GET, 'edit', FILTER_SANITIZE_NUMBER_INT );
		if ( $edit_nonce && $edit_id_input ) {
			$edit_id = absint( $edit_id_input );
			if ( $edit_id > 0 && wp_verify_nonce( $edit_nonce, 'macm_edit_location_' . $edit_id ) ) {
				$edit_location = MACM_Location::get( $edit_id );
			}
		}

		?>
		<div class="wrap">
			<h1 class="wp-heading-inline"><?php esc_html_e( 'Training Locations', 'martial-arts-club-manager' ); ?></h1>
			<a href="#" class="page-title-action" id="kcm-add-location-btn"><?php esc_html_e( 'Add New', 'martial-arts-club-manager' ); ?></a>
			<hr class="wp-header-end">

			<?php if ( 'saved' === $message ) : ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Location saved successfully.', 'martial-arts-club-manager' ); ?></p>
				</div>
			<?php elseif ( 'deleted' === $message ) : ?>
				<div class="notice notice-success is-dismissible">
					<p><?php esc_html_e( 'Location deleted successfully.', 'martial-arts-club-manager' ); ?></p>
				</div>
			<?php endif; ?>

			<?php if ( $error ) : ?>
				<div class="notice notice-error is-dismissible">
					<p><?php echo esc_html( urldecode( $error ) ); ?></p>
				</div>
			<?php endif; ?>

			<!-- Add/Edit Form -->
			<div id="kcm-location-form" style="<?php echo $edit_location ? '' : 'display: none;'; ?>">
				<div class="card" style="max-width: 600px; margin: 20px 0;">
					<h2><?php echo $edit_location ? esc_html__( 'Edit Location', 'martial-arts-club-manager' ) : esc_html__( 'Add New Location', 'martial-arts-club-manager' ); ?></h2>
					<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
						<?php wp_nonce_field( 'macm_save_location', 'macm_location_nonce' ); ?>
						<input type="hidden" name="action" value="macm_save_location">
						<?php if ( $edit_location ) : ?>
							<input type="hidden" name="location_id" value="<?php echo esc_attr( $edit_location->id ); ?>">
						<?php endif; ?>

						<table class="form-table">
							<tr>
								<th scope="row">
									<label for="location_name"><?php esc_html_e( 'Location Name', 'martial-arts-club-manager' ); ?> <span class="description">(<?php esc_html_e( 'required', 'martial-arts-club-manager' ); ?>)</span></label>
								</th>
								<td>
									<input type="text"
											id="location_name"
											name="name"
											class="regular-text"
											value="<?php echo $edit_location ? esc_attr( $edit_location->location_name ) : ''; ?>"
											required>
									<p class="description"><?php esc_html_e( 'Enter the location name (e.g., "Main Dojo", "Downtown Branch")', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="location_address"><?php esc_html_e( 'Address', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<textarea id="location_address"
												name="address"
												class="large-text"
												rows="3"><?php echo $edit_location ? esc_textarea( $edit_location->address ?? '' ) : ''; ?></textarea>
									<p class="description"><?php esc_html_e( 'Full address of the training location', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
							<tr>
								<th scope="row">
									<label for="location_is_active"><?php esc_html_e( 'Status', 'martial-arts-club-manager' ); ?></label>
								</th>
								<td>
									<label>
										<input type="checkbox"
												id="location_is_active"
												name="is_active"
												value="1"
												<?php checked( $edit_location ? $edit_location->is_active : 1, 1 ); ?>>
										<?php esc_html_e( 'Active', 'martial-arts-club-manager' ); ?>
									</label>
									<p class="description"><?php esc_html_e( 'Inactive locations won\'t appear in class schedules', 'martial-arts-club-manager' ); ?></p>
								</td>
							</tr>
						</table>

						<p class="submit">
							<input type="submit" class="button button-primary" value="<?php echo $edit_location ? esc_attr__( 'Update Location', 'martial-arts-club-manager' ) : esc_attr__( 'Add Location', 'martial-arts-club-manager' ); ?>">
							<a href="<?php echo esc_url( admin_url( 'admin.php?page=kcm-locations' ) ); ?>" class="button"><?php esc_html_e( 'Cancel', 'martial-arts-club-manager' ); ?></a>
						</p>
					</form>
				</div>
			</div>

			<!-- Locations List -->
			<table class="wp-list-table widefat fixed striped kcm-locations-table">
				<thead>
					<tr>
						<th scope="col"><?php esc_html_e( 'Location Name', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Address', 'martial-arts-club-manager' ); ?></th>
						<th scope="col" class="num"><?php esc_html_e( 'Classes', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Status', 'martial-arts-club-manager' ); ?></th>
						<th scope="col"><?php esc_html_e( 'Actions', 'martial-arts-club-manager' ); ?></th>
					</tr>
				</thead>
				<tbody>
					<?php if ( ! empty( $locations ) ) : ?>
						<?php foreach ( $locations as $location ) : ?>
							<?php
							$classes     = MACM_Location::get_classes( $location->id, true );
							$class_count = count( $classes );
							?>
							<tr>
								<td>
									<strong><?php echo esc_html( $location->location_name ); ?></strong>
								</td>
								<td>
									<?php echo $location->address ? esc_html( $location->address ) : '<span class="description">' . esc_html__( 'No address', 'martial-arts-club-manager' ) . '</span>'; ?>
								</td>
								<td class="num">
									<?php echo esc_html( $class_count ); ?>
								</td>
								<td>
									<?php if ( $location->is_active ) : ?>
										<span class="kcm-badge kcm-badge-success"><?php esc_html_e( 'Active', 'martial-arts-club-manager' ); ?></span>
									<?php else : ?>
										<span class="kcm-badge kcm-badge-inactive"><?php esc_html_e( 'Inactive', 'martial-arts-club-manager' ); ?></span>
									<?php endif; ?>
								</td>
								<td>
									<?php
									$actions = array();

									// Edit action (with nonce for security).
									$edit_url        = wp_nonce_url(
										admin_url( 'admin.php?page=kcm-locations&edit=' . $location->id ),
										'macm_edit_location_' . $location->id
									);
									$actions['edit'] = sprintf(
										'<a href="%s">%s</a>',
										esc_url( $edit_url ),
										esc_html__( 'Edit', 'martial-arts-club-manager' )
									);

									// Delete action (only if not in use).
									if ( 0 === $class_count ) {
										$confirm_message   = esc_js( __( 'Are you sure you want to delete this location?', 'martial-arts-club-manager' ) );
										$actions['delete'] = sprintf(
											'<a href="%s" class="submitdelete" onclick="return confirm(&quot;%s&quot;);">%s</a>',
											esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=macm_delete_location&location_id=' . $location->id ), 'macm_delete_location_' . $location->id ) ),
											$confirm_message,
											esc_html__( 'Delete', 'martial-arts-club-manager' )
										);
									}

									echo '<div class="row-actions">';
									$action_links = array();
									foreach ( $actions as $key => $action ) {
										$action_links[] = '<span class="' . esc_attr( $key ) . '">' . $action . '</span>';
									}
									$allowed_html = array(
										'span' => array( 'class' => array() ),
										'a'    => array(
											'href'    => array(),
											'class'   => array(),
											'onclick' => array(),
										),
									);
									echo wp_kses( implode( ' | ', $action_links ), $allowed_html );
									if ( $class_count > 0 ) {
										echo ' | <span class="description">' . esc_html__( 'In use', 'martial-arts-club-manager' ) . '</span>';
									}
									echo '</div>';
									?>
								</td>
							</tr>
						<?php endforeach; ?>
					<?php else : ?>
						<tr>
							<td colspan="5" style="text-align: center; padding: 40px;">
								<p><?php esc_html_e( 'No locations found.', 'martial-arts-club-manager' ); ?></p>
								<p><a href="#" class="button button-primary" id="kcm-add-first-location"><?php esc_html_e( 'Add Your First Location', 'martial-arts-club-manager' ); ?></a></p>
							</td>
						</tr>
					<?php endif; ?>
				</tbody>
			</table>
		</div>
		<?php
	}

	/**
	 * Save location
	 *
	 * @since 1.0.0
	 */
	public function save_location() {
		// Verify nonce.
		check_admin_referer( 'macm_save_location', 'macm_location_nonce' );

		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'Permission denied', 'martial-arts-club-manager' ) );
		}

		// Get and sanitize data.
		$location_id = isset( $_POST['location_id'] ) ? absint( wp_unslash( $_POST['location_id'] ) ) : 0;
		$data        = array(
			'name'      => isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '',
			'address'   => isset( $_POST['address'] ) ? sanitize_textarea_field( wp_unslash( $_POST['address'] ) ) : '',
			'is_active' => isset( $_POST['is_active'] ) ? 1 : 0,
		);

		// Save or update.
		if ( $location_id ) {
			$result = MACM_Location::update( $location_id, $data );
		} else {
			$result = MACM_Location::create( $data );
		}

		// Store message in transient.
		$transient_key = 'macm_location_message_' . get_current_user_id();
		if ( is_wp_error( $result ) ) {
			set_transient(
				$transient_key,
				array(
					'type'  => 'error',
					'error' => $result->get_error_message(),
				),
				30
			);
		} else {
			set_transient(
				$transient_key,
				array( 'type' => 'saved' ),
				30
			);
		}

		wp_safe_redirect( admin_url( 'admin.php?page=kcm-locations' ) );
		exit;
	}

	/**
	 * Delete location
	 *
	 * @since 1.0.0
	 */
	public function delete_location() {
		// Get location ID.
		$location_id = isset( $_GET['location_id'] ) ? absint( wp_unslash( $_GET['location_id'] ) ) : 0;

		// Verify nonce.
		check_admin_referer( 'macm_delete_location_' . $location_id );

		// Check permissions.
		if ( ! current_user_can( 'manage_macm_classes' ) ) {
			wp_die( esc_html__( 'Permission denied', 'martial-arts-club-manager' ) );
		}

		// Delete location.
		$result = MACM_Location::delete( $location_id );

		// Store message in transient.
		$transient_key = 'macm_location_message_' . get_current_user_id();
		if ( is_wp_error( $result ) ) {
			set_transient(
				$transient_key,
				array(
					'type'  => 'error',
					'error' => $result->get_error_message(),
				),
				30
			);
		} else {
			set_transient(
				$transient_key,
				array( 'type' => 'deleted' ),
				30
			);
		}

		wp_safe_redirect( admin_url( 'admin.php?page=kcm-locations' ) );
		exit;
	}
}

// Initialize.
new MACM_Admin_Locations();
