<?php
// File: class/class-upload-image-handler.php
// Handles AJAX upload to WordPress media library for custom JS uploader

if ( ! class_exists( 'ALPHA_upload_image_handler' ) ) :
	class ALPHA_upload_image_handler {
		public function __construct() {
			add_action( 'wp_ajax_alpha_upload_image', array( $this, 'handle_upload_image' ) );
			add_action( 'wp_ajax_nopriv_alpha_upload_image', array( $this, 'handle_upload_image' ) );
		}

		public function handle_upload_image() {
			if ( ! current_user_can( 'upload_files' ) ) {
				wp_send_json_error( array( 'message' => 'Permission denied.' ) );
			}
			check_ajax_referer( 'upload-attachment', 'nonce' );

			if ( empty( $_FILES['async-upload'] ) ) {
				wp_send_json_error( array( 'message' => 'No file uploaded.' ) );
			}

			$file          = $_FILES['async-upload'];
			$overrides     = array(
				'test_form' => false,
				'mimes'     => null,
			);
			$attachment_id = media_handle_upload( 'async-upload', 0, array(), $overrides );
			if ( is_wp_error( $attachment_id ) ) {
				wp_send_json_error( array( 'message' => $attachment_id->get_error_message() ) );
			}
			$attachment = get_post( $attachment_id );
			$url        = wp_get_attachment_url( $attachment_id );
			wp_send_json_success(
				array(
					'id'    => $attachment_id,
					'url'   => $url,
					'title' => $attachment->post_title,
				)
			);
		}
	}
endif;
