<?php
// File: modules/folder-structure.php

defined('ABSPATH') || exit;

// Shared 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', '/folder-structure', [
        'methods'             => WP_REST_Server::READABLE,
        'callback'            => 'myaio_sac_get_folder_structure',
        // Replace myaio_sac_permission_check with shared checker (auth behavior stays same: 401 on invalid key)
        'permission_callback' => 'myaio_sac_rest_permission_check',
        // Optional args added safely (does not affect output unless caller sends them)
        'args'                => [
            'max_depth' => [
                'required'          => false,
                'default'           => 10,
                'sanitize_callback' => 'absint',
            ],
        ],
    ]);
});

/**
 * Main folder structure API handler
 * Output MUST remain same.
 */
if ( ! function_exists('myaio_sac_get_folder_structure') ) {
    function myaio_sac_get_folder_structure(WP_REST_Request $request) {
        $root_path = ABSPATH;

        // Keep same default behavior: 10
        $max_depth = absint($request->get_param('max_depth'));
        if ($max_depth < 1) $max_depth = 10;

        $structure = myaio_sac_scan_directory_tree($root_path, 0, $max_depth);

        return rest_ensure_response([
            'root'      => site_url(),
            'base_path' => $root_path,
            'structure' => $structure,
        ]);
    }
}

/**
 * Recursive directory scanner with path and count
 * Output MUST remain same.
 */
if ( ! function_exists('myaio_sac_scan_directory_tree') ) {
    function myaio_sac_scan_directory_tree($dir, $depth = 0, $max_depth = 10) {
        if ($depth > $max_depth || !is_readable($dir)) return [];

        // Replace @scandir with safer check first; keep same "return [] on failure" behavior
        if (!is_dir($dir)) return [];
        $entries = scandir($dir);
        if (!$entries) return [];

        $folders = [];

        foreach ($entries as $entry) {
            if ($entry === '.' || $entry === '..') continue;

            $path = $dir . DIRECTORY_SEPARATOR . $entry;
            if (is_dir($path)) {
                $sub = myaio_sac_scan_directory_tree($path, $depth + 1, $max_depth);
                $folders[] = [
                    'name'       => $entry,
                    'path'       => $path,
                    'count'      => count($sub),
                    'subfolders' => $sub
                ];
            }
        }

        return $folders;
    }
}
