<?php

namespace Bricksforge\Api;

if (!defined('ABSPATH')) exit; // Exit if accessed directly

require_once(BRICKSFORGE_PATH . '/includes/elements/pro-forms/ProFormsLogger.php');

use Bricksforge\ProForms\ProFormsLogger;

class LogsApi
{
    public function __construct()
    {
        add_action('rest_api_init', array($this, 'register_routes'));
    }

    public function register_routes()
    {
        register_rest_route('bricksforge/v1', '/logs', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_logs'),
            'permission_callback' => array($this, 'check_permissions'),
            'args' => array(
                'limit' => array(
                    'default' => 100,
                    'sanitize_callback' => 'absint',
                ),
                'level' => array(
                    'default' => null,
                    'sanitize_callback' => 'sanitize_text_field',
                ),
                'action' => array(
                    'default' => null,
                    'sanitize_callback' => 'sanitize_text_field',
                ),
            ),
        ));

        register_rest_route('bricksforge/v1', '/logs/stats', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_log_stats'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        register_rest_route('bricksforge/v1', '/logs/clear', array(
            'methods' => 'POST',
            'callback' => array($this, 'clear_logs'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        register_rest_route('bricksforge/v1', '/logs/settings', array(
            'methods' => 'GET',
            'callback' => array($this, 'get_settings'),
            'permission_callback' => array($this, 'check_permissions'),
        ));

        register_rest_route('bricksforge/v1', '/logs/settings', array(
            'methods' => 'POST',
            'callback' => array($this, 'update_settings'),
            'permission_callback' => array($this, 'check_permissions'),
        ));
    }

    public function check_permissions()
    {
        return current_user_can('manage_options');
    }

    public function get_logs(\WP_REST_Request $request)
    {
        $limit = $request->get_param('limit');
        $level = $request->get_param('level');
        $action = $request->get_param('action');

        try {
            $logs = ProFormsLogger::get_logs($limit, $level, $action);

            return rest_ensure_response(array(
                'success' => true,
                'data' => $logs,
                'total' => count($logs),
            ));
        } catch (\Exception $e) {
            return new \WP_Error('logs_error', $e->getMessage(), array('status' => 500));
        }
    }

    public function get_log_stats(\WP_REST_Request $request)
    {
        try {
            $stats = ProFormsLogger::get_log_stats();

            return rest_ensure_response(array(
                'success' => true,
                'data' => $stats,
            ));
        } catch (\Exception $e) {
            return new \WP_Error('stats_error', $e->getMessage(), array('status' => 500));
        }
    }

    public function clear_logs(\WP_REST_Request $request)
    {
        try {
            ProFormsLogger::clear_logs();

            return rest_ensure_response(array(
                'success' => true,
                'message' => __('Logs cleared successfully', 'bricksforge'),
            ));
        } catch (\Exception $e) {
            return new \WP_Error('clear_error', $e->getMessage(), array('status' => 500));
        }
    }

    public function get_settings(\WP_REST_Request $request)
    {
        try {
            $settings = array(
                'logging_enabled' => (bool) get_option('brf_logging_enabled', true),
                'notifications_enabled' => (bool) get_option('brf_admin_notifications_enabled', true),
                'partial_notifications_enabled' => (bool) get_option('brf_admin_partial_notifications_enabled', true),
                'notification_email' => get_option('brf_admin_notification_email', get_option('admin_email')),
                'webhook_enabled' => (bool) get_option('brf_webhook_notifications_enabled', false),
                'webhook_url' => get_option('brf_webhook_notification_url', ''),
            );

            return rest_ensure_response(array(
                'success' => true,
                'data' => $settings,
            ));
        } catch (\Exception $e) {
            return new \WP_Error('settings_error', $e->getMessage(), array('status' => 500));
        }
    }

    public function update_settings(\WP_REST_Request $request)
    {
        try {
            $logging_enabled = $request->get_param('logging_enabled');
            $notifications_enabled = $request->get_param('notifications_enabled');
            $partial_notifications_enabled = $request->get_param('partial_notifications_enabled');
            $notification_email = $request->get_param('notification_email');
            $webhook_enabled = $request->get_param('webhook_enabled');
            $webhook_url = $request->get_param('webhook_url');

            // Validate email
            if ($notification_email && !is_email($notification_email)) {
                return new \WP_Error('invalid_email', 'Invalid email address', array('status' => 400));
            }

            // Validate webhook URL
            if ($webhook_enabled && $webhook_url && !filter_var($webhook_url, FILTER_VALIDATE_URL)) {
                return new \WP_Error('invalid_webhook_url', 'Invalid webhook URL', array('status' => 400));
            }

            // Update options
            update_option('brf_logging_enabled', (bool) $logging_enabled);
            update_option('brf_admin_notifications_enabled', (bool) $notifications_enabled);
            update_option('brf_admin_partial_notifications_enabled', (bool) $partial_notifications_enabled);
            if ($notification_email) {
                update_option('brf_admin_notification_email', sanitize_email($notification_email));
            }
            update_option('brf_webhook_notifications_enabled', (bool) $webhook_enabled);
            if ($webhook_url) {
                update_option('brf_webhook_notification_url', esc_url_raw($webhook_url));
            }

            return rest_ensure_response(array(
                'success' => true,
                'message' => __('Settings updated successfully', 'bricksforge'),
            ));
        } catch (\Exception $e) {
            return new \WP_Error('update_error', $e->getMessage(), array('status' => 500));
        }
    }
}
