<?php
// includes/API/DashboardTemplatesAPI.php

/**
 * FleekDash V2 Dashboard Templates API
 *
 * Handles dashboard template management operations
 */

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

// Load debug helpers
if (!function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

class FLEEKDASH_Dashboard_Templates_API
{

    private $template_controller;

    /**
     * Constructor - register REST API routes
     */
    public function __construct()
    {
        $this->template_controller = new \FleekDash\Controllers\DashboardTemplateController();

        // Register routes immediately since we're already in rest_api_init context
        $this->register_routes();
    }

    /**
     * Register REST API routes
     */
    public function register_routes()
    {
        // Get all templates
        register_rest_route('fleekdash/v1', '/dashboard-templates', array(
            'methods' => 'GET',
            'callback' => array($this->template_controller, 'get_templates'),
            'permission_callback' => array($this, 'check_permissions'),
            'args' => array(
                'category' => array(
                    'type' => 'string',
                    'required' => false,
                    'sanitize_callback' => 'sanitize_text_field'
                )
            )
        ));

        // Get template by ID
        register_rest_route('fleekdash/v1', '/dashboard-templates/(?P<id>\d+)', array(
            'methods' => 'GET',
            'callback' => array($this->template_controller, 'get_template'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        // Apply template
        register_rest_route('fleekdash/v1', '/dashboard-templates/(?P<id>\d+)/apply', array(
            'methods' => 'POST',
            'callback' => array($this->template_controller, 'apply_template'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        // Create new template
        register_rest_route('fleekdash/v1', '/dashboard-templates', array(
            'methods' => 'POST',
            'callback' => array($this->template_controller, 'create_template'),
            'permission_callback' => array($this, 'check_permissions'),
            'args' => array(
                'name' => array(
                    'type' => 'string',
                    'required' => true,
                    'sanitize_callback' => 'sanitize_text_field'
                ),
                'description' => array(
                    'type' => 'string',
                    'required' => false,
                    'sanitize_callback' => 'sanitize_textarea_field'
                ),
                'category' => array(
                    'type' => 'string',
                    'required' => true,
                    'sanitize_callback' => 'sanitize_text_field'
                ),
                'config' => array(
                    'type' => 'object',
                    'required' => true
                )
            )
        ));

        // Update template
        register_rest_route('fleekdash/v1', '/dashboard-templates/(?P<id>\d+)', array(
            'methods' => 'PUT',
            'callback' => array($this->template_controller, 'update_template'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        // Delete template
        register_rest_route('fleekdash/v1', '/dashboard-templates/(?P<id>\d+)', array(
            'methods' => 'DELETE',
            'callback' => array($this->template_controller, 'delete_template'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        // Initialize default templates
        register_rest_route('fleekdash/v1', '/dashboard-templates/initialize-defaults', array(
            'methods' => 'POST',
            'callback' => array($this->template_controller, 'initialize_defaults'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        // Get template categories
        register_rest_route('fleekdash/v1', '/dashboard-templates/categories', array(
            'methods' => 'GET',
            'callback' => array($this->template_controller, 'get_categories'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        // Get user customization for a template
        register_rest_route('fleekdash/v1', '/dashboard-templates/user-customization', array(
            'methods' => 'GET',
            'callback' => array($this->template_controller, 'get_user_customization'),
            'permission_callback' => array($this, 'check_permissions'),
            'args' => array(
                'template_id' => array(
                    'type' => 'string',
                    'required' => true,
                    'sanitize_callback' => 'sanitize_text_field'
                )
            )
        ));

        // Save user customization for a template
        register_rest_route('fleekdash/v1', '/dashboard-templates/user-customization', array(
            'methods' => 'POST',
            'callback' => array($this->template_controller, 'save_user_customization'),
            'permission_callback' => array($this, 'check_permissions'),
            'args' => array(
                'template_id' => array(
                    'type' => 'string',
                    'required' => true,
                    'sanitize_callback' => 'sanitize_text_field'
                )
            )
        ));

        // Delete user customization for a template
        register_rest_route('fleekdash/v1', '/dashboard-templates/user-customization', array(
            'methods' => 'DELETE',
            'callback' => array($this->template_controller, 'delete_user_customization'),
            'permission_callback' => array($this, 'check_permissions'),
            'args' => array(
                'template_id' => array(
                    'type' => 'string',
                    'required' => true,
                    'sanitize_callback' => 'sanitize_text_field'
                )
            )
        ));
    }

    /**
     * Check permissions for API access with graceful fallback
     */
    public function check_permissions()
    {
        // For compatibility with SPA authentication, allow access but log for audit
        $can_manage = current_user_can('manage_options');
        $is_logged_in = is_user_logged_in();

        if (!$can_manage) {
            fleekdash_log_debug("FleekDash: Dashboard templates access without manage_options capability - User ID: " . get_current_user_id() . " - Logged in: " . ($is_logged_in ? 'yes' : 'no'));
        }

        // Allow access for graceful fallback
        return true;
    }
}
