<?php
/**
 * Profile Image Upload API Handler (Generalized)
 * Handles profile image uploads (avatar, cover photo, etc.)
 *
 * @since   4.2.3
 * @package WPUF\UserDirectory
 */

namespace WPUF\UserDirectory\Api;

/**
 * Profile Image Upload API Class
 */
class ProfileImageUpload {

	/**
	 * Configuration for the image type
	 *
	 * @var array
	 */
	protected $config;

	/**
	 * Constructor
	 *
	 * @param array $config Configuration array.
	 */
	public function __construct( $config ) {
		$this->config = wp_parse_args(
			$config,
			[
				'action'            => 'wpuf_upload_image',
				'nonce_name'       => 'wpuf_image_upload_nonce',
				'file_input_name'  => 'image',
				'meta_key'         => 'wpuf_profile_image',
				'processing_func'  => '', // Must be provided in config
				'error_message'    => 'You can only upload photos for your own profile.',
				'success_message'  => 'Image updated successfully!',
				'response_key'     => 'image_url',
			]
		);

		add_action( "wp_ajax_{$this->config['action']}", [ $this, 'handle_upload' ] );
	}

	/**
	 * Handle upload AJAX request
	 *
	 * @since 4.2.3
	 */
	public function handle_upload() {
		// Verify nonce
		if ( ! wp_verify_nonce( sanitize_text_field( $_POST['nonce'] ?? '' ), $this->config['nonce_name'] ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Security check failed. Please refresh the page and try again.', 'wpuf-pro' ),
				],
				403
			);
		}

		$user_id         = intval( $_POST['user_id'] ?? 0 );
		$current_user_id = get_current_user_id();

		// Check if user is logged in
		if ( ! $current_user_id ) {
			wp_send_json_error(
				[
					'message' => __( 'You must be logged in to upload an image.', 'wpuf-pro' ),
				],
				401
			);
		}

		// Check if user has permission to upload files
		if ( ! current_user_can( 'upload_files' ) ) {
			wp_send_json_error(
				[
					'message' => __( 'You do not have permission to upload files.', 'wpuf-pro' ),
				],
				403
			);
		}

		// Check if user can edit this profile
		if ( $current_user_id !== $user_id ) {
			wp_send_json_error(
				[
					'message' => __( $this->config['error_message'], 'wpuf-pro' ),
				],
				403
			);
		}

		// Check if file was uploaded
		$file_input_name = sanitize_key( $this->config['file_input_name'] );
		if ( ! isset( $_FILES[ $file_input_name ] ) || $_FILES[ $file_input_name ]['error'] !== UPLOAD_ERR_OK ) {
			wp_send_json_error(
				[
					'message' => __( 'No file was uploaded or upload failed.', 'wpuf-pro' ),
				],
				400
			);
		}

		$file = $_FILES[ $file_input_name ];

		// Validate file
		$validation_result = wpuf_ud_validate_uploaded_file( $file );

		if ( ! $validation_result['valid'] ) {
			wp_send_json_error(
				[
					'message' => $validation_result['message'],
				],
				400
			);
		}

		// Check if processing function exists and is callable
		if ( ! is_callable( $this->config['processing_func'] ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Upload processing function not available.', 'wpuf-pro' ),
				],
				500
			);
		}

		// Process upload
		$upload_result = call_user_func(
			$this->config['processing_func'],
			$file,
			$user_id,
			$this->config
		);

		if ( is_wp_error( $upload_result ) ) {
			wp_send_json_error(
				[
					'message' => $upload_result->get_error_message(),
				],
				500
			);
		}

		// Validate upload result structure
		if ( ! is_array( $upload_result ) || ! isset( $upload_result['attachment_id'] ) ) {
			wp_send_json_error(
				[
					'message' => __( 'Invalid upload result format.', 'wpuf-pro' ),
				],
				500
			);
		}

		// Return success response
		$response_key = $this->config['response_key'];
		$response_data = [
			'attachment_id' => $upload_result['attachment_id'],
			'message'       => __( $this->config['success_message'], 'wpuf-pro' ),
		];

		// Add the image URL with the configured key
		$response_data[ $response_key ] = $upload_result['image_url'] ?? $upload_result[ $response_key ] ?? '';

		wp_send_json_success( $response_data );
	}
}

