<?php

namespace ZenoChatbot\Http\Controller\Api\V1;

use ZenoChatbot\Helper\Settings;
use ZenoChatbot\Helper\Security;

class InternalContentSettingsController
{
    /**
     * Get available post types with counts
     *
     * @param \WP_REST_Request $request
     * @return array
     */
    public function getPostTypes(\WP_REST_Request $request)
    {
        // Verify user permissions
        if (!Security::currentUserCan('manage_options')) {
            return [
                'success' => false,
                'message' => 'Insufficient permissions',
                'status' => 403
            ];
        }

        try {
            $post_types = get_post_types(['public' => true], 'objects');
            $available_types = [];

            foreach ($post_types as $post_type) {
                // Skip attachments
                if ($post_type->name === 'attachment') {
                    continue;
                }

                $count = wp_count_posts($post_type->name);
                $published_count = isset($count->publish) ? $count->publish : 0;

                $available_types[] = [
                    'name' => $post_type->name,
                    'label' => $post_type->labels->name,
                    'count' => $published_count,
                    'description' => $post_type->description ?: $post_type->labels->name
                ];
            }

            return [
                'success' => true,
                'data' => [
                    'post_types' => $available_types
                ]
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Failed to retrieve post types',
                'error' => $e->getMessage(),
                'status' => 500
            ];
        }
    }

    /**
     * Get internal content settings
     *
     * @param \WP_REST_Request $request
     * @return array
     */
    public function get(\WP_REST_Request $request)
    {
        // Verify user permissions
        if (!Security::currentUserCan('manage_options')) {
            return [
                'success' => false,
                'message' => 'Insufficient permissions',
                'status' => 403
            ];
        }

        try {
            $settings = [
                'selected_post_types' => Settings::get('internal_content.selected_post_types', ['post', 'page'])
            ];

            return [
                'success' => true,
                'data' => $settings
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Failed to retrieve internal content settings',
                'error' => $e->getMessage(),
                'status' => 500
            ];
        }
    }

    /**
     * Save internal content settings
     *
     * @param \WP_REST_Request $request
     * @return array
     */
    public function save(\WP_REST_Request $request)
    {
        // Verify user permissions
        if (!Security::currentUserCan('manage_options')) {
            return [
                'success' => false,
                'message' => 'Insufficient permissions',
                'status' => 403
            ];
        }

        try {
            // Get parameters
            $selected_post_types = $request->get_param('selected_post_types');

            // Validate and sanitize selected_post_types
            if (!is_array($selected_post_types)) {
                $selected_post_types = [];
            }
            $selected_post_types = array_map('sanitize_text_field', $selected_post_types);

            // Validate that selected post types exist
            $available_post_types = get_post_types(['public' => true]);
            $valid_post_types = [];

            foreach ($selected_post_types as $post_type) {
                if (isset($available_post_types[$post_type]) && $post_type !== 'attachment') {
                    $valid_post_types[] = $post_type;
                }
            }

            // Save settings using Settings helper
            Settings::update('internal_content.selected_post_types', $valid_post_types);

            return [
                'success' => true,
                'message' => 'Internal content settings saved successfully',
                'data' => [
                    'selected_post_types' => $valid_post_types
                ]
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Failed to save internal content settings',
                'error' => $e->getMessage(),
                'status' => 500
            ];
        }
    }
}
