<?php
/**
 * Customers REST API Controller
 *
 * @package ShopExplorer\Api
 * @since 1.0.0
 */

namespace SHOPEXPLORER\Api;

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

/**
 * Customers Controller class
 */
class SHOPEX_CustomersController {

	/**
	 * Register routes
	 */
	public function register_routes() {
		// Get customers list
		register_rest_route( 'shop-explorer/v1', '/customers', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_customers' ],
			'permission_callback' => [ $this, 'check_permission' ],
		]);

		// Get single customer
		register_rest_route( 'shop-explorer/v1', '/customers/(?P<id>\d+)', [
			'methods' => 'GET',
			'callback' => [ $this, 'get_customer' ],
			'permission_callback' => [ $this, 'check_permission' ],
		]);

		// Create customer
		register_rest_route( 'shop-explorer/v1', '/customers', [
			'methods' => 'POST',
			'callback' => [ $this, 'create_customer' ],
			'permission_callback' => [ $this, 'check_permission' ],
		]);

		// Update customer
		register_rest_route( 'shop-explorer/v1', '/customers/(?P<id>\d+)', [
			'methods' => 'PUT',
			'callback' => [ $this, 'update_customer' ],
			'permission_callback' => [ $this, 'check_permission' ],
		]);

		// Delete customer
		register_rest_route( 'shop-explorer/v1', '/customers/(?P<id>\d+)', [
			'methods' => 'DELETE',
			'callback' => [ $this, 'delete_customer' ],
			'permission_callback' => [ $this, 'check_permission' ],
		]);
	}

	/**
	 * Check permission
	 */
	public function check_permission() {
		return current_user_can( 'manage_woocommerce' ) || current_user_can( 'edit_users' );
	}

	/**
	 * Get customers list
	 */
	public function get_customers( $request ) {
		try {
			$page = $request->get_param( 'page' ) ?: 1;
			$per_page = $request->get_param( 'per_page' ) ?: 20;
			$search = $request->get_param( 'search' ) ?: '';
			$role = $request->get_param( 'role' ) ?: '';

			$args = [
				'number' => $per_page,
				'paged' => $page,
				'orderby' => 'registered',
				'order' => 'DESC',
			];

			if ( ! empty( $search ) ) {
				$args['search'] = '*' . $search . '*';
				$args['search_columns'] = [ 'user_login', 'user_email', 'display_name' ];
			}

			if ( ! empty( $role ) && $role !== 'all' ) {
				$args['role'] = $role;
			}

			$user_query = new \WP_User_Query( $args );
			$users = $user_query->get_results();
			$total = $user_query->get_total();

			$customers = [];
			foreach ( $users as $user ) {
				$customers[] = $this->format_customer( $user );
			}

			return new \WP_REST_Response([
				'success' => true,
				'customers' => $customers,
				'total' => $total,
				'total_pages' => ceil( $total / $per_page ),
			], 200);

		} catch ( \Exception $e ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => $e->getMessage(),
			], 500);
		}
	}

	/**
	 * Get single customer
	 */
	public function get_customer( $request ) {
		try {
			$user_id = $request->get_param( 'id' );
			$user = get_user_by( 'id', $user_id );

			if ( ! $user ) {
				return new \WP_REST_Response([
					'success' => false,
					'message' => 'Customer not found',
				], 404);
			}

			return new \WP_REST_Response([
				'success' => true,
				'customer' => $this->format_customer( $user, true ),
			], 200);

		} catch ( \Exception $e ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => $e->getMessage(),
			], 500);
		}
	}

	/**
	 * Create customer
	 */
	public function create_customer( $request ) {
		try {
			$data = $request->get_json_params();

			// Validate required fields
			if ( empty( $data['username'] ) || empty( $data['email'] ) || empty( $data['password'] ) ) {
				return new \WP_REST_Response([
					'success' => false,
					'message' => 'Username, email, and password are required',
				], 400);
			}

			// Create user
			$user_id = wp_create_user( $data['username'], $data['password'], $data['email'] );

			if ( is_wp_error( $user_id ) ) {
				return new \WP_REST_Response([
					'success' => false,
					'message' => $user_id->get_error_message(),
				], 400);
			}

			// Update user data
			wp_update_user([
				'ID' => $user_id,
				'first_name' => $data['first_name'] ?? '',
				'last_name' => $data['last_name'] ?? '',
				'role' => $data['role'] ?? 'customer',
			]);

			// Update billing and shipping
			$this->update_customer_meta( $user_id, $data );

			return new \WP_REST_Response([
				'success' => true,
				'message' => 'Customer created successfully',
				'customer_id' => $user_id,
			], 201);

		} catch ( \Exception $e ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => $e->getMessage(),
			], 500);
		}
	}

	/**
	 * Update customer
	 */
	public function update_customer( $request ) {
		try {
			$user_id = $request->get_param( 'id' );
			$data = $request->get_json_params();

			$user = get_user_by( 'id', $user_id );
			if ( ! $user ) {
				return new \WP_REST_Response([
					'success' => false,
					'message' => 'Customer not found',
				], 404);
			}

			// Update user data
			$update_data = [
				'ID' => $user_id,
			];

			if ( ! empty( $data['email'] ) ) {
				$update_data['user_email'] = $data['email'];
			}

			if ( ! empty( $data['first_name'] ) ) {
				$update_data['first_name'] = $data['first_name'];
			}

			if ( ! empty( $data['last_name'] ) ) {
				$update_data['last_name'] = $data['last_name'];
			}

			if ( ! empty( $data['password'] ) ) {
				$update_data['user_pass'] = $data['password'];
			}

			wp_update_user( $update_data );

			// Update role
			if ( ! empty( $data['role'] ) ) {
				$user->set_role( $data['role'] );
			}

			// Update billing and shipping
			$this->update_customer_meta( $user_id, $data );

			return new \WP_REST_Response([
				'success' => true,
				'message' => 'Customer updated successfully',
			], 200);

		} catch ( \Exception $e ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => $e->getMessage(),
			], 500);
		}
	}

	/**
	 * Delete customer
	 */
	public function delete_customer( $request ) {
		try {
			$user_id = $request->get_param( 'id' );

			if ( ! get_user_by( 'id', $user_id ) ) {
				return new \WP_REST_Response([
					'success' => false,
					'message' => 'Customer not found',
				], 404);
			}

			require_once ABSPATH . 'wp-admin/includes/user.php';
			$result = wp_delete_user( $user_id );

			if ( ! $result ) {
				return new \WP_REST_Response([
					'success' => false,
					'message' => 'Failed to delete customer',
				], 500);
			}

			return new \WP_REST_Response([
				'success' => true,
				'message' => 'Customer deleted successfully',
			], 200);

		} catch ( \Exception $e ) {
			return new \WP_REST_Response([
				'success' => false,
				'message' => $e->getMessage(),
			], 500);
		}
	}

	/**
	 * Format customer data
	 */
	private function format_customer( $user, $include_meta = false ) {
		$customer = [
			'id' => $user->ID,
			'username' => $user->user_login ?: '',
			'email' => $user->user_email ?: '',
			'first_name' => $user->first_name ?: '',
			'last_name' => $user->last_name ?: '',
			'display_name' => $user->display_name ?: '',
			'role' => ! empty( $user->roles ) ? $user->roles[0] : 'subscriber',
			'date_created' => $user->user_registered ?: current_time( 'mysql' ),
			'orders_count' => 0,
			'total_spent' => '0.00',
			'avatar_url' => get_avatar_url( $user->user_email, [ 'size' => 80, 'default' => 'mp' ] ),
		];

		// Get WooCommerce customer data
		if ( class_exists( 'WC_Customer' ) ) {
			try {
				$wc_customer = new \WC_Customer( $user->ID );
				$customer['orders_count'] = $wc_customer->get_order_count();
				$customer['total_spent'] = number_format( $wc_customer->get_total_spent(), 2 );
			} catch ( \Exception $e ) {
				// Silently fail if WC_Customer fails
			}
		}

		// Include billing and shipping if requested
		if ( $include_meta ) {
			$customer['billing'] = [
				'first_name' => get_user_meta( $user->ID, 'billing_first_name', true ),
				'last_name' => get_user_meta( $user->ID, 'billing_last_name', true ),
				'company' => get_user_meta( $user->ID, 'billing_company', true ),
				'address_1' => get_user_meta( $user->ID, 'billing_address_1', true ),
				'address_2' => get_user_meta( $user->ID, 'billing_address_2', true ),
				'city' => get_user_meta( $user->ID, 'billing_city', true ),
				'state' => get_user_meta( $user->ID, 'billing_state', true ),
				'postcode' => get_user_meta( $user->ID, 'billing_postcode', true ),
				'country' => get_user_meta( $user->ID, 'billing_country', true ),
				'phone' => get_user_meta( $user->ID, 'billing_phone', true ),
				'email' => get_user_meta( $user->ID, 'billing_email', true ),
			];

			$customer['shipping'] = [
				'first_name' => get_user_meta( $user->ID, 'shipping_first_name', true ),
				'last_name' => get_user_meta( $user->ID, 'shipping_last_name', true ),
				'company' => get_user_meta( $user->ID, 'shipping_company', true ),
				'address_1' => get_user_meta( $user->ID, 'shipping_address_1', true ),
				'address_2' => get_user_meta( $user->ID, 'shipping_address_2', true ),
				'city' => get_user_meta( $user->ID, 'shipping_city', true ),
				'state' => get_user_meta( $user->ID, 'shipping_state', true ),
				'postcode' => get_user_meta( $user->ID, 'shipping_postcode', true ),
				'country' => get_user_meta( $user->ID, 'shipping_country', true ),
			];
		}

		return $customer;
	}

	/**
	 * Update customer meta (billing/shipping)
	 */
	private function update_customer_meta( $user_id, $data ) {
		// Update billing address
		if ( ! empty( $data['billing'] ) ) {
			foreach ( $data['billing'] as $key => $value ) {
				update_user_meta( $user_id, 'billing_' . $key, sanitize_text_field( $value ) );
			}
		}

		// Update shipping address
		if ( ! empty( $data['shipping'] ) ) {
			foreach ( $data['shipping'] as $key => $value ) {
				update_user_meta( $user_id, 'shipping_' . $key, sanitize_text_field( $value ) );
			}
		}
	}
}
