<?php
/**
 * Campaign Post Type Manager
 *
 * Handles campaign CPT registration and admin customization.
 *
 * @package DonorCore\PostTypes
 */

namespace DonorCore\PostTypes;

defined( 'ABSPATH' ) || exit;

/**
 * Campaign Post Type Class
 */
class Campaign_Post_Type {

	/**
	 * Initialize hooks.
	 */
	public function init() {
		// Register post type immediately (we're already in init hook)
		$this->register();
		
		// Register meta fields for REST API on rest_api_init
		add_action( 'rest_api_init', array( $this, 'register_meta_fields' ) );
		
		add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) );
		add_action( 'save_post_donorcore_campaign', array( $this, 'save_meta' ), 10, 2 );
		add_filter( 'manage_donorcore_campaign_posts_columns', array( $this, 'admin_columns' ) );
		add_action( 'manage_donorcore_campaign_posts_custom_column', array( $this, 'admin_column_content' ), 10, 2 );
	}

	/**
	 * Register Campaign CPT.
	 */
	public function register() {
		$labels = array(
			'name'                  => __( 'Campaigns', 'donorcore-donations' ),
			'singular_name'         => __( 'Campaign', 'donorcore-donations' ),
			'menu_name'             => __( 'Campaigns', 'donorcore-donations' ),
			'add_new'               => __( 'Add New', 'donorcore-donations' ),
			'add_new_item'          => __( 'Add New Campaign', 'donorcore-donations' ),
			'edit_item'             => __( 'Edit Campaign', 'donorcore-donations' ),
			'new_item'              => __( 'New Campaign', 'donorcore-donations' ),
			'view_item'             => __( 'View Campaign', 'donorcore-donations' ),
			'search_items'          => __( 'Search Campaigns', 'donorcore-donations' ),
			'not_found'             => __( 'No campaigns found', 'donorcore-donations' ),
			'not_found_in_trash'    => __( 'No campaigns found in trash', 'donorcore-donations' ),
			'all_items'             => __( 'All Campaigns', 'donorcore-donations' ),
			'archives'              => __( 'Campaign Archives', 'donorcore-donations' ),
			'insert_into_item'      => __( 'Insert into campaign', 'donorcore-donations' ),
			'uploaded_to_this_item' => __( 'Uploaded to this campaign', 'donorcore-donations' ),
		);

		$args = array(
			'labels'              => $labels,
			'public'              => true,
			'publicly_queryable'  => true,
			'show_ui'             => true,
			'show_in_menu'        => 'donorcore-donations', // Show under DonorCore menu
			'query_var'           => true,
			'rewrite'             => array( 'slug' => 'campaign' ),
			'capability_type'     => 'post', // Use standard WordPress post capabilities
			'map_meta_cap'        => true,
			'has_archive'         => true,
			'hierarchical'        => false,
			'menu_position'       => null,
			'supports'            => array( 'title', 'editor', 'thumbnail', 'excerpt' ),
			'show_in_rest'        => true,
		);

		register_post_type( 'donorcore_campaign', $args );
	}

	/**
	 * Register meta fields for REST API.
	 */
	public function register_meta_fields() {
		// Add meta fields to REST API response
		register_rest_field( 'donorcore_campaign', 'campaign_meta', array(
			'get_callback' => function( $object ) {
				$suggested_raw = get_post_meta( $object['id'], '_donorcore_campaign_suggested_amounts', true );
				$suggested     = is_string( $suggested_raw ) && ! empty( $suggested_raw ) ? json_decode( $suggested_raw, true ) : null;
				if ( is_array( $suggested ) ) {
					$suggested = array_filter( array_map( 'floatval', $suggested ) );
				}
				if ( empty( $suggested ) || ! is_array( $suggested ) ) {
					$global_suggested = get_option( 'donorcore_suggested_amounts', '50,100,250,500' );
					$suggested        = array_map( 'floatval', array_filter( array_map( 'trim', explode( ',', $global_suggested ) ) ) );
					if ( empty( $suggested ) ) {
						$suggested = array( 50, 100, 250, 500 );
					}
				}
				return array(
					'_donorcore_campaign_goal'              => floatval( get_post_meta( $object['id'], '_donorcore_campaign_goal', true ) ),
					'_donorcore_campaign_min_donation'      => floatval( get_post_meta( $object['id'], '_donorcore_campaign_min_donation', true ) ),
					'_donorcore_campaign_suggested_amounts' => wp_json_encode( array_values( $suggested ) ),
					'_donorcore_campaign_start_date'        => sanitize_text_field( get_post_meta( $object['id'], '_donorcore_campaign_start_date', true ) ),
					'_donorcore_campaign_end_date'          => sanitize_text_field( get_post_meta( $object['id'], '_donorcore_campaign_end_date', true ) ),
				);
			},
			'schema'       => array(
				'description' => __( 'Campaign meta fields', 'donorcore-donations' ),
				'type'        => 'object',
			),
		) );
	}

	/**
	 * Add meta boxes.
	 */
	public function add_meta_boxes() {
		add_meta_box(
			'donorcore_campaign_settings',
			__( 'Campaign Settings', 'donorcore-donations' ),
			array( $this, 'render_meta_box' ),
			'donorcore_campaign',
			'side',
			'high'
		);
	}

	/**
	 * Render campaign settings meta box.
	 *
	 * @param \WP_Post $post Current post object.
	 */
	public function render_meta_box( $post ) {
		wp_nonce_field( 'donorcore_campaign_meta', 'donorcore_campaign_meta_nonce' );

		// Get global default settings
		$global_min_donation      = floatval( get_option( 'donorcore_minimum_donation_amount', '10' ) );
		$global_suggested_amounts = sanitize_text_field( get_option( 'donorcore_suggested_amounts', '50,100,250,500' ) );
		
		// Get saved values or use defaults
		$goal              = get_post_meta( $post->ID, '_donorcore_campaign_goal', true );
		$min_donation      = get_post_meta( $post->ID, '_donorcore_campaign_min_donation', true );
		$suggested_amounts = get_post_meta( $post->ID, '_donorcore_campaign_suggested_amounts', true );
		
		// Use global settings as fallback for display
		if ( empty( $min_donation ) ) {
			$min_donation = '';
		}
		if ( empty( $suggested_amounts ) ) {
			$suggested_amounts = '';
		}
		$start_date     = get_post_meta( $post->ID, '_donorcore_campaign_start_date', true );
		$end_date       = get_post_meta( $post->ID, '_donorcore_campaign_end_date', true );
		$product_id     = get_post_meta( $post->ID, '_donorcore_campaign_product_id', true );

		// Parse suggested amounts.
		if ( ! empty( $suggested_amounts ) && is_string( $suggested_amounts ) ) {
			$suggested_array = json_decode( $suggested_amounts, true );
			$suggested_amounts       = is_array( $suggested_array ) ? implode( ', ', $suggested_array ) : '';
		}

		// Enqueue styles for the meta box
		wp_register_style( 'donor-core-campaign-meta', false, array(), DONOR_CORE_VERSION );
		wp_enqueue_style( 'donor-core-campaign-meta' );
		$css = "
			#donorcore_campaign_settings,
			#donorcore_campaign_settings .inside {
				overflow-x: hidden !important;
				box-sizing: border-box !important;
				max-width: 100% !important;
			}
			#donorcore_campaign_settings .form-table {
				width: 100% !important;
				max-width: 100% !important;
				table-layout: fixed !important;
				margin: 0 !important;
				box-sizing: border-box !important;
				display: block !important;
			}
			#donorcore_campaign_settings .form-table tbody,
			#donorcore_campaign_settings .form-table tr {
				display: block !important;
				width: 100% !important;
				max-width: 100% !important;
				box-sizing: border-box !important;
			}
			#donorcore_campaign_settings .form-table th,
			#donorcore_campaign_settings .form-table td {
				display: block !important;
				width: 100% !important;
				max-width: 100% !important;
				box-sizing: border-box !important;
				padding: 4px 0 !important;
				margin: 0 !important;
				word-wrap: break-word;
				overflow-wrap: break-word;
			}
			#donorcore_campaign_settings .form-table th {
				padding-top: 10px !important;
				font-weight: 600;
			}
			#donorcore_campaign_settings .form-table input[type='text'],
			#donorcore_campaign_settings .form-table input[type='number'],
			#donorcore_campaign_settings .form-table input[type='datetime-local'] {
				width: 100% !important;
				max-width: 100% !important;
				min-width: 0 !important;
				box-sizing: border-box !important;
				font-size: 13px !important;
				padding: 4px 6px !important;
				margin: 0 !important;
			}
			#donorcore_campaign_settings .form-table .description {
				font-size: 12px;
				line-height: 1.4;
				color: #646970;
				margin-top: 4px;
				margin-bottom: 0;
				word-wrap: break-word;
				white-space: normal;
				max-width: 100%;
			}
		";
		$css = wp_strip_all_tags( $css );
		wp_add_inline_style( 'donor-core-campaign-meta', esc_html( $css ) );
		?>
		<table class="form-table">
			<tr>
				<th><label for="donorcore_campaign_goal"><?php esc_html_e( 'Fundraising Goal', 'donorcore-donations' ); ?></label></th>
				<td>
					<input type="number" id="donorcore_campaign_goal" name="donorcore_campaign_goal" value="<?php echo esc_attr( $goal ); ?>" step="0.01" min="0" class="widefat" />
					<p class="description"><?php esc_html_e( 'Target amount to raise (e.g., 10000.00).', 'donorcore-donations' ); ?></p>
				</td>
			</tr>
			<tr>
				<th><label for="donorcore_campaign_min_donation"><?php esc_html_e( 'Minimum Donation', 'donorcore-donations' ); ?></label></th>
				<td>
					<input
						type="number"
						name="donorcore_campaign_min_donation"
						id="donorcore_campaign_min_donation"
						value="<?php echo esc_attr( $min_donation ); ?>"
						placeholder="<?php echo esc_attr( $global_min_donation ); ?>"
						step="0.01"
						min="0"
						class="widefat"
					/>
					<p class="description"><?php esc_html_e( 'Minimum donation amount (optional). Leave empty to use global default.', 'donorcore-donations' ); ?></p>
				</td>
			</tr>
			<tr>
				<th><label for="donorcore_campaign_suggested_amounts"><?php esc_html_e( 'Suggested Amounts', 'donorcore-donations' ); ?></label></th>
				<td>
					<input
						type="text"
						name="donorcore_campaign_suggested_amounts"
						id="donorcore_campaign_suggested_amounts"
						value="<?php echo esc_attr( $suggested_amounts ); ?>"
						placeholder="<?php echo esc_attr( $global_suggested_amounts ); ?>"
						class="widefat"
					/>
					<p class="description"><?php esc_html_e( 'Comma-separated amounts to suggest to donors (e.g., 25, 50, 100, 250). Leave empty to use global default.', 'donorcore-donations' ); ?></p>
				</td>
			</tr>
			<tr>
				<th><label for="donorcore_campaign_start_date"><?php esc_html_e( 'Start Date', 'donorcore-donations' ); ?></label></th>
				<td>
					<input type="datetime-local" id="donorcore_campaign_start_date" name="donorcore_campaign_start_date" value="<?php echo esc_attr( $start_date ? gmdate( 'Y-m-d\TH:i', strtotime( $start_date ) ) : '' ); ?>" class="widefat" />
				</td>
			</tr>
			<tr>
				<th><label for="donorcore_campaign_end_date"><?php esc_html_e( 'End Date', 'donorcore-donations' ); ?></label></th>
				<td>
					<input type="datetime-local" id="donorcore_campaign_end_date" name="donorcore_campaign_end_date" value="<?php echo esc_attr( $end_date ? gmdate( 'Y-m-d\TH:i', strtotime( $end_date ) ) : '' ); ?>" class="widefat" />
				</td>
			</tr>
			<?php if ( $product_id ) : ?>
			<tr>
				<th><?php esc_html_e( 'Linked Product', 'donorcore-donations' ); ?></th>
				<td>
					<a href="<?php echo esc_url( get_edit_post_link( $product_id ) ); ?>" target="_blank">
						<?php
						printf(
							/* translators: %d: product ID */
							esc_html__( 'Donation Product #%d', 'donorcore-donations' ),
							intval( $product_id )
						);
						?>
					</a>
				</td>
			</tr>
			<?php endif; ?>
		</table>
		<?php
	}

	/**
	 * Save campaign meta data.
	 *
	 * @param int      $post_id Post ID.
	 * @param \WP_Post $post    Post object.
	 */
	public function save_meta( $post_id, $post ) {
		// Verify nonce.
		if ( ! isset( $_POST['donorcore_campaign_meta_nonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_POST['donorcore_campaign_meta_nonce'] ) ), 'donorcore_campaign_meta' ) ) {
			return;
		}

		// Check autosave.
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		// Check permissions.
		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		// Save goal.
		if ( isset( $_POST['donorcore_campaign_goal'] ) ) {
			update_post_meta( $post_id, '_donorcore_campaign_goal', floatval( sanitize_text_field( wp_unslash( $_POST['donorcore_campaign_goal'] ) ) ) );
		}

		// Save minimum donation.
		if ( isset( $_POST['donorcore_campaign_min_donation'] ) ) {
			update_post_meta( $post_id, '_donorcore_campaign_min_donation', floatval( sanitize_text_field( wp_unslash( $_POST['donorcore_campaign_min_donation'] ) ) ) );
		}

		// Save suggested amounts.
		if ( isset( $_POST['donorcore_campaign_suggested_amounts'] ) ) {
			$suggested = sanitize_text_field( wp_unslash( $_POST['donorcore_campaign_suggested_amounts'] ) );
			$amounts   = array_map( 'floatval', array_filter( array_map( 'trim', explode( ',', $suggested ) ) ) );
			if ( ! empty( $amounts ) ) {
				update_post_meta( $post_id, '_donorcore_campaign_suggested_amounts', wp_json_encode( array_values( $amounts ) ) );
			} else {
				delete_post_meta( $post_id, '_donorcore_campaign_suggested_amounts' );
			}
		}

		// Save dates.
		if ( isset( $_POST['donorcore_campaign_start_date'] ) ) {
			$start_date = sanitize_text_field( wp_unslash( $_POST['donorcore_campaign_start_date'] ) );
			update_post_meta( $post_id, '_donorcore_campaign_start_date', $start_date ? gmdate( 'Y-m-d H:i:s', strtotime( $start_date ) ) : '' );
		}

		if ( isset( $_POST['donorcore_campaign_end_date'] ) ) {
			$end_date = sanitize_text_field( wp_unslash( $_POST['donorcore_campaign_end_date'] ) );
			update_post_meta( $post_id, '_donorcore_campaign_end_date', $end_date ? gmdate( 'Y-m-d H:i:s', strtotime( $end_date ) ) : '' );
		}
	}

	/**
	 * Customize admin columns.
	 *
	 * @param array $columns Existing columns.
	 * @return array
	 */
	public function admin_columns( $columns ) {
		$new_columns = array();
		
		// Checkbox
		if ( isset( $columns['cb'] ) ) {
			$new_columns['cb'] = $columns['cb'];
		}
		
		// Title
		if ( isset( $columns['title'] ) ) {
			$new_columns['title'] = $columns['title'];
		}
		
		// Campaign ID
		$new_columns['campaign_id'] = __( 'Campaign ID', 'donorcore-donations' );
		
		// Custom columns
		$new_columns['goal']       = __( 'Goal', 'donorcore-donations' );
		$new_columns['raised']     = __( 'Raised', 'donorcore-donations' );
		$new_columns['progress']   = __( 'Progress', 'donorcore-donations' );
		$new_columns['start_date'] = __( 'Start Date', 'donorcore-donations' );
		$new_columns['end_date']   = __( 'End Date', 'donorcore-donations' );
		$new_columns['date']       = __( 'Date', 'donorcore-donations' );
		
		return $new_columns;
	}

	/**
	 * Display admin column content.
	 *
	 * @param string $column  Column name.
	 * @param int    $post_id Post ID.
	 */
	public function admin_column_content( $column, $post_id ) {
		switch ( $column ) {
			case 'campaign_id':
				// Display campaign ID
				echo '<strong>' . esc_html( $post_id ) . '</strong>';
				break;
			
			case 'goal':
				$goal = get_post_meta( $post_id, '_donorcore_campaign_goal', true );
				if ( $goal && function_exists( 'wc_price' ) ) {
					echo wp_kses_post( wc_price( $goal ) );
				} elseif ( $goal ) {
					echo '$' . esc_html( number_format( (float) $goal, 2 ) );
				} else {
					echo '—';
				}
				break;

			case 'raised':
				// Get raised amount from donation logs.
				$repo   = new \DonorCore\Database\Donation_Log_Repository();
				$raised = $repo->get_campaign_total( $post_id );
				if ( function_exists( 'wc_price' ) ) {
					echo wp_kses_post( wc_price( $raised ) );
				} else {
					echo '$' . esc_html( number_format( (float) $raised, 2 ) );
				}
				break;

			case 'progress':
				$goal   = get_post_meta( $post_id, '_donorcore_campaign_goal', true );
				$repo   = new \DonorCore\Database\Donation_Log_Repository();
				$raised = $repo->get_campaign_total( $post_id );
				
				if ( $goal && $goal > 0 ) {
					$percentage = min( 100, ( $raised / $goal ) * 100 );
					echo esc_html( number_format( $percentage, 1 ) ) . '%';
				} else {
					echo '—';
				}
				break;
			
			case 'start_date':
				$start_date = get_post_meta( $post_id, '_donorcore_campaign_start_date', true );
				if ( $start_date ) {
					echo esc_html( gmdate( 'M j, Y', strtotime( $start_date ) ) );
				} else {
					echo '—';
				}
				break;
			
			case 'end_date':
				$end_date = get_post_meta( $post_id, '_donorcore_campaign_end_date', true );
				if ( $end_date ) {
					echo esc_html( gmdate( 'M j, Y', strtotime( $end_date ) ) );
				} else {
					echo '—';
				}
				break;
		}
	}
}
