<?php

namespace FleekDash\Controllers;

use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use FleekDash\Services\DashboardTemplateService;
use FleekDash\Core\AuthMiddleware;

/**
 * Dashboard Template Controller
 *
 * Handles dashboard template management via REST API
 */
class DashboardTemplateController
{
    private $template_service;

    public function __construct()
    {
        $this->template_service = new DashboardTemplateService();
    }

    /**
     * Check authentication
     */
    private function check_auth($required_level = 'authenticated')
    {
        try {
            $auth_check = AuthMiddleware::check($required_level);
            if (!$auth_check['authenticated']) {
                return [
                    'authenticated' => false,
                    'user_id' => 0,
                    'fallback' => true,
                    'reason' => $auth_check['reason']
                ];
            }

            return [
                'authenticated' => true,
                'user_id' => $auth_check['user_id'],
                'fallback' => false
            ];

        } catch (\Exception $e) {
            return [
                'authenticated' => false,
                'user_id' => 0,
                'fallback' => true,
                'reason' => 'auth_middleware_error'
            ];
        }
    }

    /**
     * Get all dashboard templates
     */
    public function get_templates(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth('authenticated');
            $category = $request->get_param('category');

            $templates = $this->template_service->getTemplates($category);

            return new WP_REST_Response([
                'success' => true,
                'templates' => $templates,
                'categories' => $this->template_service->getCategories(),
                'meta' => [
                    'total' => count($templates),
                    'category' => $category
                ],
                'auth_status' => [
                    'authenticated' => $auth['authenticated'],
                    'fallback' => $auth['fallback']
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('template_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get template by ID
     */
    public function get_template(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth('authenticated');
            $template_id = $request->get_param('id');

            $template = $this->template_service->getTemplate($template_id);

            if (!$template) {
                return new WP_Error('template_not_found', 'Template not found', ['status' => 404]);
            }

            return new WP_REST_Response([
                'success' => true,
                'template' => $template,
                'auth_status' => [
                    'authenticated' => $auth['authenticated'],
                    'fallback' => $auth['fallback']
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('template_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Apply template to create dashboard
     */
    public function apply_template(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth('authenticated');
            $template_id = $request->get_param('id');
            $user_id = $auth['user_id'];

            $layout = $this->template_service->applyTemplate($template_id, $user_id);

            if (!$layout) {
                return new WP_Error('template_apply_failed', 'Failed to apply template', ['status' => 400]);
            }

            return new WP_REST_Response([
                'success' => true,
                'layout' => $layout,
                'message' => 'Template applied successfully',
                'auth_status' => [
                    'authenticated' => $auth['authenticated'],
                    'fallback' => $auth['fallback']
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('template_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Create new template
     */
    public function create_template(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth('authenticated');

            $data = [
                'name' => $request->get_param('name'),
                'description' => $request->get_param('description'),
                'category' => $request->get_param('category'),
                'config' => $request->get_param('config')
            ];

            // Validate required fields
            if (empty($data['name']) || empty($data['category'])) {
                return new WP_Error('missing_fields', 'Name and category are required', ['status' => 400]);
            }

            $template_id = $this->template_service->createTemplate($data);

            if (!$template_id) {
                return new WP_Error('template_creation_failed', 'Failed to create template', ['status' => 400]);
            }

            $template = $this->template_service->getTemplate($template_id);

            return new WP_REST_Response([
                'success' => true,
                'template' => $template,
                'message' => 'Template created successfully',
                'auth_status' => [
                    'authenticated' => $auth['authenticated'],
                    'fallback' => $auth['fallback']
                ]
            ], 201);

        } catch (\Exception $e) {
            return new WP_Error('template_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Update template
     */
    public function update_template(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth('authenticated');
            $template_id = $request->get_param('id');

            $data = $request->get_json_params();
            unset($data['id']); // Remove ID from update data

            $result = $this->template_service->updateTemplate($template_id, $data);

            if (!$result) {
                return new WP_Error('template_update_failed', 'Failed to update template', ['status' => 400]);
            }

            $template = $this->template_service->getTemplate($template_id);

            return new WP_REST_Response([
                'success' => true,
                'template' => $template,
                'message' => 'Template updated successfully',
                'auth_status' => [
                    'authenticated' => $auth['authenticated'],
                    'fallback' => $auth['fallback']
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('template_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Delete template
     */
    public function delete_template(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth('authenticated');
            $template_id = $request->get_param('id');

            $result = $this->template_service->deleteTemplate($template_id);

            if (!$result) {
                return new WP_Error('template_delete_failed', 'Failed to delete template', ['status' => 400]);
            }

            return new WP_REST_Response([
                'success' => true,
                'message' => 'Template deleted successfully',
                'auth_status' => [
                    'authenticated' => $auth['authenticated'],
                    'fallback' => $auth['fallback']
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('template_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Initialize default templates
     */
    public function initialize_defaults(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth('authenticated');

            $this->template_service->createDefaultTemplates();

            $templates = $this->template_service->getTemplates();

            return new WP_REST_Response([
                'success' => true,
                'templates' => $templates,
                'message' => 'Default templates initialized successfully',
                'auth_status' => [
                    'authenticated' => $auth['authenticated'],
                    'fallback' => $auth['fallback']
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('template_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get template categories
     */
    public function get_categories(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth('authenticated');

            $categories = $this->template_service->getCategories();

            return new WP_REST_Response([
                'success' => true,
                'categories' => $categories,
                'auth_status' => [
                    'authenticated' => $auth['authenticated'],
                    'fallback' => $auth['fallback']
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('template_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Get user customization for a template
     */
    public function get_user_customization(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth('authenticated');
            $template_id = $request->get_param('template_id');

            if (!$template_id) {
                return new WP_Error('missing_template_id', 'Template ID is required', ['status' => 400]);
            }

            $user_id = $auth['user_id'];
            $customization = $this->template_service->get_user_customization($template_id, $user_id);

            return new WP_REST_Response([
                'success' => true,
                'customization' => $customization,
                'template_id' => $template_id,
                'auth_status' => [
                    'authenticated' => $auth['authenticated'],
                    'fallback' => $auth['fallback']
                ]
            ], 200);

        } catch (\Exception $e) {
            return new WP_Error('template_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Save user customization for a template
     */
    public function save_user_customization(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth('authenticated');
            $template_id = $request->get_param('template_id');
            $customization = $request->get_json_params();

            if (!$template_id) {
                return new WP_Error('missing_template_id', 'Template ID is required', ['status' => 400]);
            }

            if (!$customization) {
                return new WP_Error('missing_customization', 'Customization data is required', ['status' => 400]);
            }

            $user_id = $auth['user_id'];
            $result = $this->template_service->save_user_customization($template_id, $customization, $user_id);

            if ($result) {
                return new WP_REST_Response([
                    'success' => true,
                    'message' => 'Customization saved successfully',
                    'template_id' => $template_id,
                    'auth_status' => [
                        'authenticated' => $auth['authenticated'],
                        'fallback' => $auth['fallback']
                    ]
                ], 200);
            } else {
                return new WP_Error('save_failed', 'Failed to save customization', ['status' => 500]);
            }

        } catch (\Exception $e) {
            return new WP_Error('template_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Delete user customization for a template
     */
    public function delete_user_customization(WP_REST_Request $request)
    {
        try {
            $auth = $this->check_auth('authenticated');
            $template_id = $request->get_param('template_id');

            if (!$template_id) {
                return new WP_Error('missing_template_id', 'Template ID is required', ['status' => 400]);
            }

            $user_id = $auth['user_id'];
            $result = $this->template_service->delete_user_customization($template_id, $user_id);

            if ($result) {
                return new WP_REST_Response([
                    'success' => true,
                    'message' => 'Customization deleted successfully',
                    'template_id' => $template_id,
                    'auth_status' => [
                        'authenticated' => $auth['authenticated'],
                        'fallback' => $auth['fallback']
                    ]
                ], 200);
            } else {
                return new WP_Error('delete_failed', 'Failed to delete customization', ['status' => 500]);
            }

        } catch (\Exception $e) {
            return new WP_Error('template_error', $e->getMessage(), ['status' => 500]);
        }
    }
}
