<?php
/**
 * Avatar Upload API Handler
 * Handles profile photo upload and processing
 *
 * @since   4.2.3
 * @package WPUF\UserDirectory
 */

namespace WPUF\UserDirectory\Api;

/**
 * Avatar Upload API Class
 */
class AvatarUpload {

    /**
     * Constructor
     */
    public function __construct() {
        add_action( 'wp_ajax_wpuf_upload_avatar', [ $this, 'handle_avatar_upload' ] );
    }

    /**
     * Handle avatar upload AJAX request
     *
     * @since 4.2.3
     */
    public function handle_avatar_upload() {
        // Verify nonce
        if ( ! wp_verify_nonce( $_POST['nonce'] ?? '', 'wpuf_avatar_upload_nonce' ) ) {
            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 a profile photo.', 'wpuf-pro' ),
                ], 401
            );
        }
        // Check if user can edit this profile
        if ( $current_user_id !== $user_id ) {
            wp_send_json_error(
                [
                    'message' => __( 'You can only upload photos for your own profile.', 'wpuf-pro' ),
                ], 403
            );
        }

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

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

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

        // Process upload
        $upload_result = wpuf_ud_process_avatar_upload( $file, $user_id );

        if ( is_wp_error( $upload_result ) ) {
            wp_send_json_error(
                [
                    'message' => $upload_result->get_error_message(),
                ], 500
            );
        }
        // Return success response
        wp_send_json_success(
            [
                'avatar_url'    => $upload_result['avatar_url'],
                'attachment_id' => $upload_result['attachment_id'],
                'message'       => __( 'Profile photo updated successfully!', 'wpuf-pro' ),
            ]
        );
    }

}

// Initialize the API handler
new AvatarUpload();
