<?php
/**
 * Subida de archivos (reemplaza biblioteca de medios de WordPress).
 */
if ( ! defined( 'JB_BOOTSTRAP' ) ) {
	require_once dirname( __DIR__ ) . '/core/bootstrap.php';
}

if ( ! is_user_logged_in() ) {
	wp_send_json_error( array( 'message' => 'No autorizado.' ), 401 );
}

check_ajax_referer( 'jb_media_upload', 'nonce' );

if ( empty( $_FILES['file'] ) ) {
	wp_send_json_error( array( 'message' => 'No se recibió archivo.' ) );
}

$file = $_FILES['file'];
if ( UPLOAD_ERR_OK !== $file['error'] ) {
	wp_send_json_error( array( 'message' => 'Error al subir archivo.' ) );
}

$upload_dir = wp_upload_dir();
$filename   = wp_unique_filename( $upload_dir['path'], sanitize_file_name( $file['name'] ) );
$dest       = $upload_dir['path'] . '/' . $filename;

if ( ! move_uploaded_file( $file['tmp_name'], $dest ) ) {
	wp_send_json_error( array( 'message' => 'No se pudo guardar el archivo.' ) );
}

$url = $upload_dir['url'] . '/' . $filename;
$id  = wp_insert_attachment( array(
	'post_title'     => $filename,
	'post_mime_type' => $file['type'],
	'post_status'    => 'inherit',
), $url );

wp_send_json_success( array(
	'id'  => $id,
	'url' => $url,
) );
