<?php
/**
 * File: modules/bin-crunch.php
 * Endpoint: GET /wp-json/myaio/v1/bin-crunch
 */

if ( ! defined('ABSPATH') ) { exit; }

require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

add_action('rest_api_init', function () {
    register_rest_route('myaio/v1', '/bin-crunch', [
        'methods'             => WP_REST_Server::READABLE, // GET
        'callback'            => 'myaio_sac_bin_crunch',
        'permission_callback' => 'myaio_sac_bin_crunch_permission',
    ]);
});

/**
 * Permission callback (official WP REST style): return true or WP_Error.
 */
function myaio_sac_bin_crunch_permission( WP_REST_Request $request ) {
    if ( function_exists('myaio_sac_validate_api_key') && myaio_sac_validate_api_key($request) ) {
        return true;
    }
    return new WP_Error('rest_forbidden', 'Unauthorized', [ 'status' => 401 ]);
}

function myaio_sac_bin_crunch( WP_REST_Request $request ) {

    // Post types to include
    $post_types = [ 'post', 'page', 'attachment' ];

    // Post statuses to include
    $post_statuses = [ 'trash', 'draft', 'private' ];

    $items = [];

    foreach ($post_types as $type) {
        foreach ($post_statuses as $status) {

            $q = new WP_Query([
                'post_type'              => $type,
                'post_status'            => $status,
                'posts_per_page'         => -1,
                'fields'                 => 'ids',
                'no_found_rows'          => true,
                'update_post_meta_cache' => false,
                'update_post_term_cache' => false,
            ]);

            if ( empty($q->posts) ) {
                continue;
            }

            foreach ($q->posts as $post_id) {
                $post = get_post($post_id);
                if ( ! $post ) continue;

                $items[] = [
                    'id'            => (int) $post_id,
                    'title'         => get_the_title($post_id),
                    'type'          => $post->post_type,
                    'status'        => $post->post_status,
                    'author'        => get_the_author_meta('display_name', $post->post_author),
                    'date_modified' => get_post_modified_time('Y-m-d H:i:s', false, $post_id, true),
                    'original_url'  => get_permalink($post_id),
                    'is_image'      => ($post->post_type === 'attachment' && wp_attachment_is_image($post_id)),
                    'mime_type'     => get_post_mime_type($post_id),
                ];
            }
        }
    }

    return rest_ensure_response([
        'total_items' => count($items),
        'items'       => $items,
    ]);
}
