<?php
// File: modules/url-slug-api.php

defined('ABSPATH') || exit;

// Shared api_key validation used across ALL modules
require_once plugin_dir_path(__FILE__) . '../includes/sac-utils.php';

add_action('rest_api_init', function () {

    register_rest_route('myaio/v1', '/get-all-urls', [
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'myaio_sac_get_all_urls',
        'permission_callback' => 'myaio_sac_rest_permission_check',
        'args'                => [
            // Keep compatibility with your client sending ?api_key=...
            'api_key' => [
                'required'          => true,
                'sanitize_callback' => 'sanitize_text_field',
                'location'          => 'query',
            ],
        ],
    ]);

    register_rest_route('myaio/v1', '/update-slug', [
        'methods'             => WP_REST_Server::CREATABLE,
        'callback'            => 'myaio_sac_update_slug',
        'permission_callback' => 'myaio_sac_rest_permission_check',
        'args'                => [
            // Keep compatibility with your client sending "api_key" in JSON or query
            'api_key' => [
                'required' => true,
            ],
            'url'  => ['required' => true],
            'slug' => ['required' => true],
        ],
    ]);
});

/**
 * GET: Retrieve all posts and pages with URL, slug, and type
 * Also highlights homepage.
 * Output MUST remain same.
 */
if (!function_exists('myaio_sac_get_all_urls')) {
    function myaio_sac_get_all_urls(WP_REST_Request $request) {
        $args = [
            'post_type'      => ['post', 'page'],
            'posts_per_page' => -1,
            'post_status'    => ['publish', 'draft', 'pending'],
        ];

        $query = new WP_Query($args);
        $results = [];

        $home_url      = trailingslashit(home_url('/'));
        $front_page_id = (int) get_option('page_on_front');
        $show_on_front = (string) get_option('show_on_front');

        foreach ((array) $query->posts as $post) {
            $permalink = get_permalink($post->ID);

            $is_home = false;
            if ($show_on_front === 'page' && $front_page_id > 0 && (int) $post->ID === $front_page_id) {
                $is_home = true;
            }
            if (!$is_home && trailingslashit($permalink) === $home_url) {
                $is_home = true;
            }

            $results[] = [
                'ID'       => $post->ID,
                'url'      => $permalink,
                'slug'     => $post->post_name,
                'type'     => $post->post_type,
                'homepage' => $is_home,
            ];
        }

        return new WP_REST_Response([
            'count' => count($results),
            'items' => $results,
        ], 200);
    }
}

/**
 * POST: Update slug (post_name) by URL
 * Expects JSON body: { "api_key": "...", "url": "...", "slug": "..." }
 * Output MUST remain same.
 */
if ( ! function_exists( 'myaio_sac_update_slug' ) ) {
    function myaio_sac_update_slug( WP_REST_Request $request ) {
        // Keep same behavior: read from JSON body
        $body = (array) $request->get_json_params();

        $url  = isset( $body['url'] ) ? esc_url_raw( $body['url'] ) : '';
        $slug = isset( $body['slug'] ) ? sanitize_title( $body['slug'] ) : '';

        if ( empty( $url ) || empty( $slug ) ) {
            return new WP_REST_Response( [ 'error' => 'Missing URL or slug' ], 400 );
        }

        $post_id = url_to_postid( $url );
        if ( ! $post_id ) {
            return new WP_REST_Response( [ 'error' => 'No post found for given URL' ], 404 );
        }

        $post_id  = absint( $post_id );
        $post_type = get_post_type( $post_id );

        if ( empty( $post_type ) ) {
            return new WP_REST_Response( [ 'error' => 'Invalid post type' ], 400 );
        }

        /**
         * Slug uniqueness check WITHOUT direct DB queries:
         * - Non-hierarchical: check `slug`
         * - Hierarchical (pages): check full path (parent/slug) so we don't false-block
         */
        if ( is_post_type_hierarchical( $post_type ) ) {
            $parent_id   = (int) wp_get_post_parent_id( $post_id );
            $parent_path = $parent_id ? trim( (string) get_page_uri( $parent_id ), '/' ) : '';
            $full_path   = $parent_path ? $parent_path . '/' . $slug : $slug;

            $existing = get_page_by_path( $full_path, OBJECT, $post_type );
        } else {
            $existing = get_page_by_path( $slug, OBJECT, $post_type );
        }

        if ( $existing && (int) $existing->ID !== $post_id ) {
            return new WP_REST_Response( [ 'error' => 'Slug already in use' ], 409 );
        }

        // Update slug (wp_update_post will handle unique-suffixes in some cases)
        $updated = wp_update_post(
            [
                'ID'        => $post_id,
                'post_name' => $slug,
            ],
            true
        );

        if ( is_wp_error( $updated ) ) {
            return new WP_REST_Response(
                [
                    'error'   => 'Failed to update slug',
                    'details' => $updated->get_error_message(),
                ],
                500
            );
        }

        // Return the updated permalink
        return new WP_REST_Response(
            [
                'success' => true,
                'message' => 'Slug updated successfully',
                'new_url' => get_permalink( $post_id ),
            ],
            200
        );
    }
}
