<?php
/**
 * A1-WooBay - eBay Profiles
 *
 * @package A1_WooBay
 * @since   0.3.2
 */

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

class A1WooBay_Profiles {

	const META_DESCRIPTION    = '_a1wb_description';
	const META_LISTING_TYPE   = '_a1wb_listing_type';
	const META_DURATION       = '_a1wb_duration';
	const META_CONDITION      = '_a1wb_condition';
	const META_CONDITION_DESC = '_a1wb_condition_desc';
	const META_HANDLING_TIME  = '_a1wb_handling_time';
	const META_CATEGORY_ID    = '_a1wb_category_id';
	const META_CATEGORY_NAME  = '_a1wb_category_name';
	const META_CATEGORY2_ID   = '_a1wb_category2_id';
	const META_CATEGORY2_NAME = '_a1wb_category2_name';
	const META_POLICY_SHIP    = '_a1wb_policy_fulfillment';
	const META_POLICY_RETURN  = '_a1wb_policy_return';
	const META_POLICY_PAY     = '_a1wb_policy_payment';
	const META_LOCATION       = '_a1wb_location';
	const META_POSTAL_CODE    = '_a1wb_postal_code';
	const META_COUNTRY        = '_a1wb_country';
	const META_CURRENCY       = '_a1wb_currency';
	const META_PRICE_TYPE     = '_a1wb_price_type';
	const META_PRICE_VALUE    = '_a1wb_price_value';
	const META_TEMPLATE_ID    = '_a1wb_template_id';
	const META_VARIATIONS     = '_a1wb_variations_mode';
	const META_FREE_SHIPPING  = '_a1wb_free_shipping';
	const META_GLOBAL_SHIP    = '_a1wb_global_shipping';
	const META_ITEM_SPECIFICS = '_a1wb_item_specifics';

	const CONDITIONS = array(
		''                         => '-- Select condition --',
		'NEW'                      => 'New',
		'LIKE_NEW'                 => 'Like New',
		'NEW_OTHER'                => 'New (other)',
		'NEW_WITH_DEFECTS'         => 'New with defects',
		'USED_EXCELLENT'           => 'Used - Excellent',
		'USED_VERY_GOOD'           => 'Used - Very Good',
		'USED_GOOD'                => 'Used - Good',
		'USED_ACCEPTABLE'          => 'Used - Acceptable',
		'FOR_PARTS_OR_NOT_WORKING' => 'For parts / not working',
	);

	const DURATIONS = array(
		'GTC'     => 'Good Till Cancelled (GTC)',
		'DAYS_3'  => '3 Days',
		'DAYS_5'  => '5 Days',
		'DAYS_7'  => '7 Days',
		'DAYS_10' => '10 Days',
		'DAYS_14' => '14 Days',
		'DAYS_21' => '21 Days',
		'DAYS_30' => '30 Days',
	);

	const HANDLING_TIMES = array(
		'0' => 'Same day',
		'1' => '1 Business day',
		'2' => '2 Business days',
		'3' => '3 Business days',
		'4' => '4 Business days',
		'5' => '5 Business days',
	);

	const PRICE_TYPES = array(
		'none'       => 'Use WooCommerce price as-is',
		'sale_price' => 'Use sale price (if set, else regular)',
		'percent' => 'Percent adjustment (e.g. +10% or -5%)',
		'fixed'   => 'Fixed price override',
	);

	const VARIATION_MODES = array(
		'single'     => 'List as single item',
		'variations' => 'List as item with variations',
	);

	const COUNTRIES = array(
		'US' => 'United States',
		'CA' => 'Canada',
		'GB' => 'United Kingdom',
		'AU' => 'Australia',
	);

	private static $instance = null;

	public static function get_instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	private function __construct() {
		add_action( 'init', array( $this, 'register_cpt' ) );
	}

	public function register_cpt() {
		register_post_type(
			'a1woobay_profile',
			array(
				'labels'          => array(
					'name'               => __( 'eBay Profiles', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
					'singular_name'      => __( 'eBay Profile', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
					'add_new_item'       => __( 'Add New Profile', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
					'edit_item'          => __( 'Edit Profile', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
					'not_found'          => __( 'No profiles found.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
					'not_found_in_trash' => __( 'No profiles found in Trash.', 'a1-marketplace-sync-with-ebay-for-woocommerce' ),
				),
				'public'          => false,
				'show_ui'         => false,
				'show_in_menu'    => false,
				'show_in_rest'    => false,
				'supports'        => array( 'title' ),
				'capability_type' => 'post',
				'map_meta_cap'    => true,
			)
		);
	}

	public static function get_all() {
		return get_posts( array(
			'post_type'      => 'a1woobay_profile',
			'post_status'    => 'publish',
			'posts_per_page' => -1,
			'orderby'        => 'title',
			'order'          => 'ASC',
		) );
	}

	public static function get_profile( $id ) {
		$post = get_post( (int) $id );
		if ( ! $post || 'a1woobay_profile' !== $post->post_type ) {
			return null;
		}
		return $post;
	}

	public static function get_meta( $profile_id ) {
		$id       = (int) $profile_id;
		$raw_spec = get_post_meta( $id, self::META_ITEM_SPECIFICS, true );
		$specifics = array();
		if ( $raw_spec ) {
			$decoded = json_decode( $raw_spec, true );
			if ( is_array( $decoded ) ) {
				$specifics = $decoded;
			}
		}
		return array(
			'description'    => get_post_meta( $id, self::META_DESCRIPTION,    true ),
			'listing_type'   => get_post_meta( $id, self::META_LISTING_TYPE,   true ) ?: 'FIXED_PRICE',
			'duration'       => get_post_meta( $id, self::META_DURATION,        true ) ?: 'GTC',
			'condition'      => get_post_meta( $id, self::META_CONDITION,       true ),
			'condition_desc' => get_post_meta( $id, self::META_CONDITION_DESC,  true ),
			'handling_time'  => get_post_meta( $id, self::META_HANDLING_TIME,   true ) ?: '1',
			'category_id'    => get_post_meta( $id, self::META_CATEGORY_ID,     true ),
			'category_name'  => get_post_meta( $id, self::META_CATEGORY_NAME,   true ),
			'category2_id'   => get_post_meta( $id, self::META_CATEGORY2_ID,    true ),
			'category2_name' => get_post_meta( $id, self::META_CATEGORY2_NAME,  true ),
			'policy_ship'    => get_post_meta( $id, self::META_POLICY_SHIP,     true ),
			'policy_return'  => get_post_meta( $id, self::META_POLICY_RETURN,   true ),
			'policy_pay'     => get_post_meta( $id, self::META_POLICY_PAY,      true ),
			'location'       => get_post_meta( $id, self::META_LOCATION,        true ),
			'postal_code'    => get_post_meta( $id, self::META_POSTAL_CODE,     true ),
			'country'        => get_post_meta( $id, self::META_COUNTRY,         true ) ?: 'US',
			'currency'       => get_post_meta( $id, self::META_CURRENCY,        true ) ?: 'USD',
			'price_type'     => get_post_meta( $id, self::META_PRICE_TYPE,      true ) ?: 'none',
			'price_value'    => get_post_meta( $id, self::META_PRICE_VALUE,     true ) ?: '0',
			'template_id'    => get_post_meta( $id, self::META_TEMPLATE_ID,     true ),
			'variations'     => get_post_meta( $id, self::META_VARIATIONS,      true ) ?: 'single',
			'free_shipping'  => get_post_meta( $id, self::META_FREE_SHIPPING,   true ) ?: '0',
			'global_ship'    => get_post_meta( $id, self::META_GLOBAL_SHIP,     true ) ?: '0',
			'item_specifics' => $specifics,
		);
	}

	public static function save_profile( $data ) {
		$title = isset( $data['title'] ) ? sanitize_text_field( $data['title'] ) : '';
		if ( ! $title ) {
			return new WP_Error( 'missing_title', 'Profile name is required.' );
		}

		$post_id = isset( $data['id'] ) ? (int) $data['id'] : 0;

		$post_data = array(
			'post_type'   => 'a1woobay_profile',
			'post_title'  => $title,
			'post_status' => 'publish',
		);

		if ( $post_id ) {
			$post_data['ID'] = $post_id;
			$result = wp_update_post( $post_data, true );
		} else {
			$result = wp_insert_post( $post_data, true );
		}

		if ( is_wp_error( $result ) ) {
			return $result;
		}

		$id = (int) $result;
		$s  = 'sanitize_text_field';

		update_post_meta( $id, self::META_DESCRIPTION,    $s( $data['description']    ?? '' ) );
		update_post_meta( $id, self::META_LISTING_TYPE,   $s( $data['listing_type']   ?? 'FIXED_PRICE' ) );
		update_post_meta( $id, self::META_DURATION,       $s( $data['duration']       ?? 'GTC' ) );
		update_post_meta( $id, self::META_CONDITION,      $s( $data['condition']      ?? '' ) );
		update_post_meta( $id, self::META_CONDITION_DESC, $s( $data['condition_desc'] ?? '' ) );
		update_post_meta( $id, self::META_HANDLING_TIME,  $s( $data['handling_time']  ?? '1' ) );
		update_post_meta( $id, self::META_CATEGORY_ID,    $s( $data['category_id']    ?? '' ) );
		update_post_meta( $id, self::META_CATEGORY_NAME,  $s( $data['category_name']  ?? '' ) );
		update_post_meta( $id, self::META_CATEGORY2_ID,   $s( $data['category2_id']   ?? '' ) );
		update_post_meta( $id, self::META_CATEGORY2_NAME, $s( $data['category2_name'] ?? '' ) );
		update_post_meta( $id, self::META_POLICY_SHIP,    $s( $data['policy_ship']    ?? '' ) );
		update_post_meta( $id, self::META_POLICY_RETURN,  $s( $data['policy_return']  ?? '' ) );
		update_post_meta( $id, self::META_POLICY_PAY,     $s( $data['policy_pay']     ?? '' ) );
		update_post_meta( $id, self::META_LOCATION,       $s( $data['location']       ?? '' ) );
		update_post_meta( $id, self::META_POSTAL_CODE,    $s( $data['postal_code']    ?? '' ) );
		update_post_meta( $id, self::META_COUNTRY,        $s( $data['country']        ?? 'US' ) );
		update_post_meta( $id, self::META_CURRENCY,       $s( $data['currency']       ?? 'USD' ) );
		update_post_meta( $id, self::META_PRICE_TYPE,     $s( $data['price_type']     ?? 'none' ) );
		update_post_meta( $id, self::META_PRICE_VALUE,    $s( $data['price_value']    ?? '0' ) );
		update_post_meta( $id, self::META_TEMPLATE_ID,    (int) ( $data['template_id'] ?? 0 ) );
		update_post_meta( $id, self::META_VARIATIONS,     $s( $data['variations']     ?? 'single' ) );
		update_post_meta( $id, self::META_FREE_SHIPPING,  $s( $data['free_shipping']  ?? '0' ) );
		update_post_meta( $id, self::META_GLOBAL_SHIP,    $s( $data['global_ship']    ?? '0' ) );

		// Item specifics - sanitize each row
		$specifics = array();
		if ( ! empty( $data['item_specifics'] ) && is_array( $data['item_specifics'] ) ) {
			foreach ( $data['item_specifics'] as $row ) {
				$name = sanitize_text_field( $row['name'] ?? '' );
				if ( ! $name ) {
					continue;
				}
				$source = in_array( $row['source'] ?? '', array( 'custom', 'attribute' ), true )
					? $row['source'] : 'custom';
				$specifics[] = array(
					'name'   => $name,
					'source' => $source,
					'value'  => sanitize_text_field( $row['value'] ?? '' ),
				);
			}
		}
		update_post_meta( $id, self::META_ITEM_SPECIFICS, wp_json_encode( $specifics ) );

		// If updating an existing profile, flag all active/verified products using it.
		if ( $post_id ) {
			$flagged = new WP_Query( array(
				'post_type'      => 'product',
				'post_status'    => 'any',
				'posts_per_page' => -1,
				'fields'         => 'ids',
				'meta_query'     => array(
					'relation' => 'AND',
					array(
						'key'   => A1WooBay_Product_Meta::META_PROFILE_ID,
						'value' => $id,
					),
					array(
						'key'     => A1WooBay_Product_Meta::META_EBAY_STATUS,
						'value'   => array( A1WooBay_Product_Meta::STATUS_ACTIVE, A1WooBay_Product_Meta::STATUS_VERIFIED ),
						'compare' => 'IN',
					),
				),
			) );
			foreach ( $flagged->posts as $pid ) {
				A1WooBay_Product_Meta::flag_needs_revision( $pid );
			}
		}

		return $id;
	}

	public static function delete_profile( $id ) {
		$post = self::get_profile( $id );
		if ( ! $post ) {
			return false;
		}
		return (bool) wp_delete_post( (int) $id, true );
	}

	public static function get_dropdown_options() {
		$profiles = self::get_all();
		$options  = array( '' => '-- No profile --' );
		foreach ( $profiles as $p ) {
			$options[ $p->ID ] = esc_html( $p->post_title );
		}
		return $options;
	}
}
