<?php

/**
 * AJAX upload handler for creating tasks via drag-and-drop.
 *
 * @package MediaTasker
 */
// Prevent direct file access.
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * Class Mediat_Upload
 *
 * Handles the server-side processing of file uploads from the
 * frontend dropzone. Validates files, creates mediat_task posts,
 * and attaches the uploaded media as featured images.
 */
class Mediat_Upload {
    /**
     * Hook into WordPress.
     *
     * @return void
     */
    public static function init() {
        add_action( 'wp_ajax_mediat_upload_task', array(__CLASS__, 'handle_upload') );
    }

    /**
     * AJAX handler: process a file upload and create a task.
     *
     * Expected:
     *   - $_FILES['mediat_file']  The uploaded file.
     *   - $_POST['nonce']     Verified against 'mediat_frontend_nonce'.
     *
     * @return void Sends JSON response and dies.
     */
    public static function handle_upload() {
        // Verify nonce.
        check_ajax_referer( 'mediat_frontend_nonce', 'nonce' );
        // Capability check — user must be able to upload files.
        if ( !current_user_can( 'upload_files' ) ) {
            wp_send_json_error( array(
                'message' => esc_html__( 'You do not have permission to upload files.', 'mediatasker' ),
            ), 403 );
        }
        // Verify file was sent.
        if ( empty( $_FILES['mediat_file'] ) ) {
            wp_send_json_error( array(
                'message' => esc_html__( 'No file was uploaded.', 'mediatasker' ),
            ), 400 );
        }
        // Validate file extension against plugin settings.
        $file_name = ( isset( $_FILES['mediat_file']['name'] ) ? sanitize_file_name( wp_unslash( $_FILES['mediat_file']['name'] ) ) : '' );
        $allowed_types = Mediat_Settings::get_option( 'allowed_file_types' );
        $allowed_arr = array_map( 'trim', explode( ',', $allowed_types ) );
        $file_ext = strtolower( pathinfo( $file_name, PATHINFO_EXTENSION ) );
        if ( !in_array( $file_ext, $allowed_arr, true ) ) {
            wp_send_json_error( array(
                'message' => sprintf( 
                    /* translators: %s: comma-separated list of allowed file extensions */
                    esc_html__( 'File type not allowed. Accepted types: %s', 'mediatasker' ),
                    esc_html( $allowed_types )
                 ),
            ), 400 );
        }
        // Validate file size against plugin settings.
        $max_size_mb = absint( Mediat_Settings::get_option( 'max_file_size' ) );
        $max_size_bytes = $max_size_mb * 1024 * 1024;
        $file_size = ( isset( $_FILES['mediat_file']['size'] ) ? absint( $_FILES['mediat_file']['size'] ) : 0 );
        if ( $file_size > $max_size_bytes ) {
            wp_send_json_error( array(
                'message' => sprintf( 
                    /* translators: %d: maximum file size in megabytes */
                    esc_html__( 'File exceeds the maximum size of %d MB.', 'mediatasker' ),
                    $max_size_mb
                 ),
            ), 400 );
        }
        // Validate MIME type with WordPress.
        $file_type_check = wp_check_filetype( $file_name );
        if ( empty( $file_type_check['ext'] ) || empty( $file_type_check['type'] ) ) {
            wp_send_json_error( array(
                'message' => esc_html__( 'Invalid file type.', 'mediatasker' ),
            ), 400 );
        }
        // WordPress needs the media functions.
        require_once ABSPATH . 'wp-admin/includes/image.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';
        // Upload the file into the media library.
        $attachment_id = media_handle_upload( 'mediat_file', 0 );
        if ( is_wp_error( $attachment_id ) ) {
            wp_send_json_error( array(
                'message' => esc_html( $attachment_id->get_error_message() ),
            ), 500 );
        }
        // Set the task title cleanly to the file name with extension.
        $task_title = $file_name;
        // Assignment view type logic
        $view_type = ( isset( $_POST['view_type'] ) ? sanitize_key( wp_unslash( $_POST['view_type'] ) ) : 'original' );
        // Get the default status from settings.
        $default_status = sanitize_key( Mediat_Settings::get_option( 'default_status' ) );
        if ( empty( $default_status ) ) {
            $default_status = 'mediat_pending';
        }
        // Overwrite status if it's an edited upload
        if ( $view_type === 'edited' ) {
            $default_status = 'mediat_not_dl';
        }
        // Create the mediat_task post.
        $post_id = wp_insert_post( array(
            'post_type'   => 'mediat_task',
            'post_title'  => sanitize_text_field( $task_title ),
            'post_status' => $default_status,
            'post_author' => get_current_user_id(),
        ), true );
        if ( is_wp_error( $post_id ) ) {
            // Clean up the orphaned attachment.
            wp_delete_attachment( $attachment_id, true );
            wp_send_json_error( array(
                'message' => esc_html( $post_id->get_error_message() ),
            ), 500 );
        }
        // Set the uploaded image as the task's featured image.
        set_post_thumbnail( $post_id, $attachment_id );
        // Assign to "Original" or "Edited" based on view_type.
        // For simplicity, we can use a hidden tag or a meta field.
        wp_set_object_terms( $post_id, $view_type, 'mediat_view_source' );
        // Auto-complete original tasks if this is an edited upload.
        if ( $view_type === 'edited' ) {
            $new_file_base = pathinfo( $file_name, PATHINFO_FILENAME );
            // Query for in-progress original tasks.
            $query_args = array(
                'post_type'      => 'mediat_task',
                'post_status'    => 'mediat_in_progress',
                'posts_per_page' => -1,
            );
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_tax_query
            $query_args['tax_query'] = array(array(
                'taxonomy' => 'mediat_view_source',
                'field'    => 'slug',
                'terms'    => 'original',
            ));
            // Query for in-progress original tasks.
            $original_tasks = get_posts( $query_args );
            if ( !empty( $original_tasks ) ) {
                foreach ( $original_tasks as $task ) {
                    $orig_title = $task->post_title;
                    $orig_base = pathinfo( $orig_title, PATHINFO_FILENAME );
                    // If the original base name matches the new edited base name exactly,
                    // or the edited name starts with the original name followed by a dash/underscore (e.g., test-7-edited).
                    if ( $new_file_base === $orig_base || strpos( $new_file_base, $orig_base . '-' ) === 0 || strpos( $new_file_base, $orig_base . '_' ) === 0 ) {
                        wp_update_post( array(
                            'ID'          => $task->ID,
                            'post_status' => 'mediat_completed',
                        ) );
                        if ( class_exists( 'Mediat_Work_Log' ) ) {
                            Mediat_Work_Log::insert_log( $task->ID, 'status_change', array(
                                'new_status' => 'mediat_completed',
                                'reason'     => sprintf( 
                                    /* translators: %s: Filename of the uploaded edited image. */
                                    esc_html__( 'Auto-completed via edited upload: %s', 'mediatasker' ),
                                    $file_name
                                 ),
                            ) );
                        }
                    }
                }
            }
        }
        // Log the upload event.
        if ( class_exists( 'Mediat_Work_Log' ) ) {
            Mediat_Work_Log::insert_log( $post_id, 'upload', array(
                'file_name' => $file_name,
                'view_type' => $view_type,
            ) );
        }
        // Build the card HTML for the newly created task so the frontend
        // can append it to the gallery without a full refresh.
        $card_html = self::build_card_html( $post_id );
        wp_send_json_success( array(
            'message'   => esc_html__( 'Task created successfully.', 'mediatasker' ),
            'card'      => $card_html,
            'post_id'   => $post_id,
            'view_type' => $view_type,
        ) );
    }

    /**
     * Build a single task-card HTML fragment.
     *
     * @param int $post_id The mediat_task post ID.
     * @return string Escaped HTML.
     */
    private static function build_card_html( $post_id ) {
        $title = get_the_title( $post_id );
        $status_key = get_post_status( $post_id );
        $statuses = Mediat_Post_Types::get_task_statuses();
        $status_label = ( isset( $statuses[$status_key] ) ? $statuses[$status_key]['label'] : ucfirst( str_replace( 'mediat_', '', $status_key ) ) );
        $html = '<div class="mediat_task-card" data-task-id="' . esc_attr( $post_id ) . '">';
        $html .= '<div class="mediat_card-thumbnail">';
        if ( has_post_thumbnail( $post_id ) ) {
            $html .= get_the_post_thumbnail( $post_id, 'medium', array(
                'alt' => esc_attr( $title ),
            ) );
        } else {
            $html .= '<div class="mediat_card-no-image"><span class="dashicons dashicons-format-image"></span></div>';
        }
        $html .= '</div>';
        $html .= '<div class="mediat_card-body">';
        $html .= '<h3 class="mediat_card-title">' . esc_html( $title ) . '</h3>';
        $html .= '<span class="mediat_status-badge mediat_status--' . esc_attr( $status_key ) . '">' . esc_html( $status_label ) . '</span>';
        $html .= '</div>';
        $html .= '</div>';
        return $html;
    }

}
