<?php
/**
 * Plugin Name: Fe Adulta — API carta_id
 * Description: Endpoint REST para que Inma y su asistente asignen el meta interno _carta_id.
 * Version: 1.0
 */

add_action('rest_api_init', function() {
    register_rest_route('fea/v1', '/carta-id/(?P<post_id>\d+)', [
        [
            'methods'             => WP_REST_Server::READABLE,
            'callback'            => 'fea_carta_id_api_get',
            'permission_callback' => 'fea_carta_id_api_can_edit_post',
            'args'                => fea_carta_id_api_route_args(),
        ],
        [
            'methods'             => WP_REST_Server::CREATABLE,
            'callback'            => 'fea_carta_id_api_update',
            'permission_callback' => 'fea_carta_id_api_can_edit_post',
            'args'                => array_merge(fea_carta_id_api_route_args(), [
                'carta_id' => [
                    'required' => true,
                ],
            ]),
        ],
        [
            'methods'             => WP_REST_Server::DELETABLE,
            'callback'            => 'fea_carta_id_api_delete',
            'permission_callback' => 'fea_carta_id_api_can_edit_post',
            'args'                => fea_carta_id_api_route_args(),
        ],
    ]);
});

function fea_carta_id_api_route_args() {
    return [
        'post_id' => [
            'required' => true,
        ],
    ];
}

function fea_carta_id_api_can_edit_post(WP_REST_Request $request) {
    if (!is_user_logged_in()) {
        return new WP_Error(
            'fea_carta_id_not_authenticated',
            'Debes autenticarte para leer o modificar _carta_id.',
            ['status' => 401]
        );
    }

    $post_id = (int) $request['post_id'];
    if (!fea_carta_id_api_post_exists($post_id)) {
        return true;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return new WP_Error(
            'fea_carta_id_forbidden',
            'No tienes permiso para editar este post.',
            ['status' => 403]
        );
    }

    return true;
}

function fea_carta_id_api_get(WP_REST_Request $request) {
    $post_id = (int) $request['post_id'];
    $error = fea_carta_id_api_validate_post_id($post_id);
    if ($error) return $error;

    return fea_carta_id_api_response($post_id);
}

function fea_carta_id_api_update(WP_REST_Request $request) {
    $post_id = (int) $request['post_id'];
    $error = fea_carta_id_api_validate_post_id($post_id);
    if ($error) return $error;

    $carta_id = fea_carta_id_api_parse_positive_int($request->get_param('carta_id'));
    if (!$carta_id) {
        return new WP_Error(
            'fea_carta_id_invalid',
            'carta_id debe ser un entero positivo.',
            ['status' => 400]
        );
    }

    if (!fea_carta_id_api_post_exists($carta_id)) {
        return new WP_Error(
            'fea_carta_id_not_found',
            'carta_id debe corresponder a un post existente.',
            ['status' => 400]
        );
    }

    update_post_meta($post_id, '_carta_id', $carta_id);

    return fea_carta_id_api_response($post_id);
}

function fea_carta_id_api_delete(WP_REST_Request $request) {
    $post_id = (int) $request['post_id'];
    $error = fea_carta_id_api_validate_post_id($post_id);
    if ($error) return $error;

    delete_post_meta($post_id, '_carta_id');

    return fea_carta_id_api_response($post_id);
}

function fea_carta_id_api_validate_post_id($post_id) {
    if (!fea_carta_id_api_post_exists($post_id)) {
        return new WP_Error(
            'fea_carta_id_post_not_found',
            'post_id debe corresponder a un post existente.',
            ['status' => 404]
        );
    }

    return null;
}

function fea_carta_id_api_post_exists($post_id) {
    $post = get_post($post_id);
    return $post && $post->post_type === 'post';
}

function fea_carta_id_api_parse_positive_int($value) {
    $int = filter_var($value, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
    return $int === false ? null : (int) $int;
}

function fea_carta_id_api_response($post_id) {
    $carta_id = fea_carta_id_api_parse_positive_int(get_post_meta($post_id, '_carta_id', true));

    return rest_ensure_response([
        'post_id'  => (int) $post_id,
        'carta_id' => $carta_id,
    ]);
}
