<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

function chcpl_register_meta_boxes() {
	add_meta_box(
		'chcpl_service_details',
		__( 'Service Details', 'ad-pro-price-list' ),
		'chcpl_render_service_meta_box',
		'price_service',
		'normal',
		'default'
	);
}

function chcpl_render_service_meta_box( $post ) {
	wp_nonce_field( 'chcpl_save_service_meta', 'chcpl_service_meta_nonce' );
	wp_enqueue_media();
	$description = get_post_meta( $post->ID, '_chcpl_service_description', true );
	$price       = get_post_meta( $post->ID, '_chcpl_service_price', true );
	$list_id     = (int) get_post_meta( $post->ID, '_chcpl_list_id', true );
	$sur_devis   = get_post_meta( $post->ID, '_chcpl_service_sur_devis', true );
	$image_id    = (int) get_post_meta( $post->ID, '_chcpl_service_image', true );
	$image_url   = $image_id ? wp_get_attachment_image_url( $image_id, 'medium' ) : '';

	$lists = get_posts( array(
		'post_type' => 'price_list',
		'numberposts' => -1,
		'post_status' => array( 'publish', 'draft' ),
		'orderby' => 'title',
		'order' => 'ASC',
	) );
	?>
	<p>
		<label for="chcpl_list_id"><strong><?php echo esc_html__( 'Price List', 'ad-pro-price-list' ); ?></strong></label><br />
		<select name="chcpl_list_id" id="chcpl_list_id" style="min-width:280px;">
			<option value=""><?php echo esc_html__( '— Select a Price List —', 'ad-pro-price-list' ); ?></option>
			<?php foreach ( $lists as $list ) : ?>
				<option value="<?php echo esc_attr( $list->ID ); ?>" <?php selected( $list_id, $list->ID ); ?>><?php echo esc_html( $list->post_title ); ?></option>
			<?php endforeach; ?>
		</select>
	</p>
	<p>
		<label for="chcpl_service_description"><strong><?php echo esc_html__( 'Description', 'ad-pro-price-list' ); ?></strong></label><br />
		<textarea name="chcpl_service_description" id="chcpl_service_description" rows="4" style="width:100%;max-width:700px;"><?php echo esc_textarea( $description ); ?></textarea>
	</p>
	<p>
		<label for="chcpl_service_price"><strong><?php echo esc_html__( 'Price (text allowed)', 'ad-pro-price-list' ); ?></strong></label><br />
		<input type="text" name="chcpl_service_price" id="chcpl_service_price" value="<?php echo esc_attr( $price ); ?>" style="width:280px;" placeholder="Ex: 100€ / On quote" />
		<br />
		<label style="margin-top:6px;display:inline-block;"><input type="checkbox" name="chcpl_service_sur_devis" value="1" <?php checked( $sur_devis, '1' ); ?> /> <?php echo esc_html__( 'Show "On quote" instead of price', 'ad-pro-price-list' ); ?></label>
	</p>
	<p>
		<label for="chcpl_service_image">
			<strong><?php echo esc_html__( 'Hover Preview Image', 'ad-pro-price-list' ); ?></strong>
			<?php if ( ! ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'pro' ) ) ) : ?>
				<span style="font-size:11px;font-weight:600;background:#7c3aed;color:#fff;padding:2px 7px;border-radius:999px;margin-left:6px;letter-spacing:.04em;vertical-align:middle;">Pro</span>
			<?php endif; ?>
		</label><br />
		<?php if ( function_exists( 'chcpl_is_plan' ) && chcpl_is_plan( 'pro' ) ) : ?>
		<input type="hidden" name="chcpl_service_image" id="chcpl_service_image" value="<?php echo esc_attr( $image_id ); ?>" />
		<div id="chcpl_service_image_preview" style="margin:10px 0;">
			<?php if ( $image_url ) : ?>
				<img src="<?php echo esc_url( $image_url ); ?>" style="max-width:200px;height:auto;display:block;margin-bottom:10px;" />
			<?php endif; ?>
		</div>
		<button type="button" class="button" id="chcpl_upload_image_btn"><?php echo esc_html__( 'Select Image', 'ad-pro-price-list' ); ?></button>
		<?php if ( $image_id ) : ?>
			<button type="button" class="button" id="chcpl_remove_image_btn" style="margin-left:5px;"><?php echo esc_html__( 'Remove Image', 'ad-pro-price-list' ); ?></button>
		<?php endif; ?>
		<p class="description"><?php echo esc_html__( 'This image will appear as a hover overlay when users hover over this service in the price list.', 'ad-pro-price-list' ); ?></p>
		<?php else : ?>
		<p class="description" style="color:#6b7280;">
			<?php esc_html_e( 'Upgrade to Pro to add a hover overlay image to each service.', 'ad-pro-price-list' ); ?>
			<?php if ( function_exists( 'chcpl_upgrade_url' ) ) : ?>
				<a href="<?php echo esc_url( chcpl_upgrade_url() ); ?>"><?php esc_html_e( 'Upgrade to Pro →', 'ad-pro-price-list' ); ?></a>
			<?php endif; ?>
		</p>
		<?php endif; ?>
	</p>
	<p><?php echo esc_html__( 'Assign a category using the Categories box on the right.', 'ad-pro-price-list' ); ?></p>
	<script>
	jQuery(document).ready(function($) {
		var frame;
		$('#chcpl_upload_image_btn').on('click', function(e) {
			e.preventDefault();
			if (frame) {
				frame.open();
				return;
			}
			frame = wp.media({
				title: '<?php echo esc_js( __( 'Select Service Preview Image', 'ad-pro-price-list' ) ); ?>',
				button: { text: '<?php echo esc_js( __( 'Use this image', 'ad-pro-price-list' ) ); ?>' },
				multiple: false
			});
			frame.on('select', function() {
				var attachment = frame.state().get('selection').first().toJSON();
				$('#chcpl_service_image').val(attachment.id);
				$('#chcpl_service_image_preview').html('<img src="' + attachment.url + '" style="max-width:200px;height:auto;display:block;margin-bottom:10px;" />');
				$('#chcpl_remove_image_btn').show();
			});
			frame.open();
		});
		$('#chcpl_remove_image_btn').on('click', function(e) {
			e.preventDefault();
			$('#chcpl_service_image').val('');
			$('#chcpl_service_image_preview').html('');
			$(this).hide();
		});
	});
	</script>
	<?php
}

function chcpl_save_service_meta( $post_id, $post ) {
	if ( $post->post_type !== 'price_service' ) {
		return;
	}

	if ( ! isset( $_POST['chcpl_service_meta_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['chcpl_service_meta_nonce'] ) ), 'chcpl_save_service_meta' ) ) {
		return;
	}
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}
	if ( ! current_user_can( 'edit_post', $post_id ) ) {
		return;
	}

	$description = isset( $_POST['chcpl_service_description'] ) ? wp_kses_post( wp_unslash( $_POST['chcpl_service_description'] ) ) : '';
	$price       = isset( $_POST['chcpl_service_price'] ) ? sanitize_text_field( wp_unslash( $_POST['chcpl_service_price'] ) ) : '';
	$list_id     = isset( $_POST['chcpl_list_id'] ) ? (int) sanitize_text_field( wp_unslash( $_POST['chcpl_list_id'] ) ) : 0;
	$sur_devis   = isset( $_POST['chcpl_service_sur_devis'] ) ? '1' : '';
	$image_id    = isset( $_POST['chcpl_service_image'] ) ? (int) sanitize_text_field( wp_unslash( $_POST['chcpl_service_image'] ) ) : 0;

	update_post_meta( $post_id, '_chcpl_service_description', $description );
	update_post_meta( $post_id, '_chcpl_service_price', $price );
	if ( $sur_devis ) {
		update_post_meta( $post_id, '_chcpl_service_sur_devis', '1' );
	} else {
		delete_post_meta( $post_id, '_chcpl_service_sur_devis' );
	}
	if ( $list_id > 0 ) {
		update_post_meta( $post_id, '_chcpl_list_id', $list_id );
	} else {
		delete_post_meta( $post_id, '_chcpl_list_id' );
	}
	if ( $image_id > 0 ) {
		update_post_meta( $post_id, '_chcpl_service_image', $image_id );
	} else {
		delete_post_meta( $post_id, '_chcpl_service_image' );
	}
}
