<?php
/**
 * Posts Controller
 *
 * This file is used to register all actions for the Posts Controller.
 *
 * @since 1.0.0
 */

namespace FleekDash\Controllers\Posts;

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

use FleekDash\Controllers\BaseController;
use FleekDash\Core\AuthMiddleware;
use FleekDash\Models\Posts;
use FleekDash\Services\ResponseService;

class Actions extends BaseController
{
    /**
     * Get all posts with pagination and caching
     */
    public function getAllPosts($request)
    {
        return $this->cacheOrExecute(function () use ($request) {
            try {
                // Get pagination params
                $params = $this->getPaginationParams($request);

                // Use WordPress WP_Query instead of Eloquent
                $args = [
                    'post_status' => 'publish',
                    'posts_per_page' => $params['per_page'],
                    'paged' => $params['page'],
                    'orderby' => 'date',
                    'order' => 'DESC'
                ];

                $query = new \WP_Query($args);
                $posts = $query->posts;

                // Format posts data
                $formatted_posts = array_map(function ($post) {
                    return [
                        'id' => $post->ID,
                        'title' => $post->post_title,
                        'excerpt' => wp_trim_words($post->post_content, 20),
                        'date' => $post->post_date,
                        'author' => get_the_author_meta('display_name', $post->post_author),
                        'thumbnail' => PostsActionsImageHelper::getPostImageData((int) $post->ID)['url'],
                        'link' => get_permalink($post->ID)
                    ];
                }, $posts);

                return ResponseService::success('Posts retrieved successfully', [
                    'items' => $formatted_posts,
                    'pagination' => [
                        'current_page' => $query->query_vars['paged'] ?: 1,
                        'per_page' => $params['per_page'],
                        'total_items' => $query->found_posts,
                        'total_pages' => $query->max_num_pages
                    ]
                ], self::CACHE_TTL);

            } catch (\Exception $e) {
                return ResponseService::error('Failed to fetch posts: ' . $e->getMessage());
            }
        });
    }

    /**
     * Get single post by ID
     */
    public function getPost($request)
    {
        return $this->cacheOrExecute(function () use ($request) {
            try {
                $post_id = $request['id'];
                $post = Posts::getPublishedById($post_id);

                if (!$post) {
                    return ResponseService::error('Post not found', null, 404);
                }

                $post_data = [
                    'id' => $post['ID'],
                    'title' => $post['post_title'],
                    'content' => \apply_filters('the_content', $post['post_content']),
                    'date' => $post['post_date'],
                    'modified_date' => $post['post_modified'],
                    'author' => [
                        'id' => $post['post_author'],
                        'name' => get_the_author_meta('display_name', $post['post_author']),
                        'avatar' => get_avatar_url($post['post_author'])
                    ],
                    'thumbnail' => PostsActionsImageHelper::getPostImageData((int) $post['ID'])['url'],
                    'categories' => wp_get_post_categories($post['ID'], ['fields' => 'names']),
                    'tags' => wp_get_post_tags($post['ID'], ['fields' => 'names'])
                ];

                return ResponseService::success('Post retrieved successfully', $post_data, self::CACHE_TTL);

            } catch (\Exception $e) {
                return ResponseService::error('Failed to fetch post: ' . $e->getMessage());
            }
        });
    }

    /**
     * Get posts optimized
     */
    public function getPostsOptimized(\WP_REST_Request $request)
    {
        // Define a constant or flag to easily toggle cache (using WP_DEBUG here)
        $enable_cache = !(defined('WP_DEBUG') && WP_DEBUG === true);

        // Prepare cache key logic (needed whether caching or not, to pass to closure if caching)
        $request_params = $request->get_query_params();
        ksort($request_params);

        $fetch_logic = function () use ($request_params) {
            return PostsOptimizedHelper::executeOptimizedFetch($request_params);
        };

        return $enable_cache
            ? $this->cacheOrExecute($fetch_logic)
            : $fetch_logic();
    }

    /**
     * Get posts statistics (counts by status)
     */
    public function getPostsStats(\WP_REST_Request $request)
    {
        return $this->cacheOrExecute(function () use ($request) {
            try {
                self::logStatsAuthResult();

                $params = $request->get_query_params();
                $post_type = $params['post_type'] ?? 'post';
                $total_count = PostsStatsHelper::getTotalCount($post_type);
                $status_counts = PostsStatsHelper::getStatusCounts($post_type);
                $all_statuses = PostsStatsHelper::collectAllStatuses($post_type);
                $payload = PostsStatsHelper::buildStatsPayload($total_count, $status_counts, $all_statuses);

                \wp_send_json_success([
                    'stats' => $payload['stats'],
                    'labels' => $payload['labels'],
                    'all_status_options' => $payload['all_status_options'],
                    'post_type' => $post_type,
                    'post_type_label' => PostsStatsHelper::getPostTypeDisplayLabel($post_type),
                    'can_create_new' => PostsStatsHelper::canCreateNewInAdmin($post_type),
                ]);
                die();
            } catch (\Exception $e) {
                \fleekdash_log_error('CSRM Posts Stats Error: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
                \wp_send_json_error(['message' => 'Failed to fetch posts statistics: ' . $e->getMessage()], 500);
                die();
            }
        });
    }

    private static function logStatsAuthResult(): void
    {
        try {
            $auth_check = AuthMiddleware::check('editor');
            if (!$auth_check['authenticated']) {
                \fleekdash_log_debug("FleekDash: Stats access without proper authentication - User ID: " . \get_current_user_id() . " - Reason: " . ($auth_check['reason'] ?? 'Unknown'));
            } else {
                \fleekdash_log_debug("FleekDash: Authenticated stats access - User ID: " . $auth_check['user_id']);
            }
        } catch (\Exception $e) {
            \fleekdash_log_error("FleekDash: AuthMiddleware error in posts-stats: " . $e->getMessage());
        }
    }

    /**
     * Delete a post by ID (supports all post types)
     */
    public function deletePost(\WP_REST_Request $request)
    {
        try {
            // 1. Permission Check
            if (!\current_user_can('delete_posts')) {
                \wp_send_json_error(['message' => 'Unauthorized'], 403);
                die();
            }

            // 2. Get post ID from request
            $post_id = $request->get_param('id');
            if (!$post_id || !is_numeric($post_id)) {
                \wp_send_json_error(['message' => 'Invalid post ID'], 400);
                die();
            }

            $post_id = (int) $post_id;

            // 3. Get the post to verify it exists and get its type
            $post = Posts::find($post_id);
            if (!$post) {
                \wp_send_json_error(['message' => 'Post not found'], 404);
                die();
            }

            // 4. Check if user can delete this specific post type
            $post_type_object = get_post_type_object($post['post_type']);
            if (!$post_type_object || !\current_user_can($post_type_object->cap->delete_posts)) {
                \wp_send_json_error(['message' => 'Unauthorized to delete this post type'], 403);
                die();
            }

            // 5. Determine action based on current status
            $is_already_trashed = ($post['post_status'] === 'trash');
            $action_taken = '';
            $deleted = false;

            if ($is_already_trashed) {
                // Post is already in trash - delete permanently
                $deleted = \wp_delete_post($post_id, true); // true = force delete (bypass trash)
                $action_taken = 'permanently_deleted';
            } else {
                // Post is not in trash - move to trash first
                $deleted = wp_trash_post($post_id);
                $action_taken = 'moved_to_trash';
            }

            if (!$deleted) {
                $error_message = $is_already_trashed
                    ? 'Failed to permanently delete post'
                    : 'Failed to move post to trash';
                \wp_send_json_error(['message' => $error_message], 500);
                die();
            }

            // 6. Return success with action information
            $success_message = $is_already_trashed
                ? 'Post permanently deleted successfully'
                : 'Post moved to trash successfully';

            \wp_send_json_success([
                'message' => $success_message,
                'post_id' => $post_id,
                'post_type' => $post['post_type'],
                'action' => $action_taken,
                'was_trashed' => $is_already_trashed
            ]);
            die();

        } catch (\Exception $e) {
            \fleekdash_log_error('CSRM Delete Post Error: ' . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
            \wp_send_json_error(['message' => 'Failed to delete post: ' . $e->getMessage()], 500);
            die();
        }
    }

    /**
     * Debug endpoint to check all available post statuses
     */
    public function debugPostStatuses(\WP_REST_Request $request)
    {
        try {
            $post_type = $request->get_param('post_type') ?? 'post';

            // Method 1: WordPress built-in function
            $wp_statuses = get_post_statuses();

            // Method 2: Get all status objects (including non-public ones)
            global $wp_post_statuses;
            $all_status_objects = $wp_post_statuses ? $wp_post_statuses : [];

            // Method 3: Get statuses that actually exist in database for this post type
            global $wpdb;
            $db_statuses = $wpdb->get_col($wpdb->prepare(
                "SELECT DISTINCT post_status FROM {$wpdb->posts} WHERE post_type = %s",
                $post_type
            ));

            // Method 4: Get all statuses that have ever been used in the database
            global $wpdb;
            $all_db_statuses = $wpdb->get_col("SELECT DISTINCT post_status FROM {$wpdb->posts}");

            // Test validation function used in routes
            $validation_test = function ($status) {
                $valid_statuses = array_keys(get_post_statuses());

                global $wp_post_statuses;
                $all_status_objects = $wp_post_statuses ? $wp_post_statuses : [];

                global $wpdb;
                $db_statuses = $wpdb->get_col("SELECT DISTINCT post_status FROM {$wpdb->posts}");

                $all_valid_statuses = $valid_statuses;

                foreach ($all_status_objects as $status_key => $status_obj) {
                    $all_valid_statuses[] = $status_key;
                }

                $all_valid_statuses = array_merge($all_valid_statuses, $db_statuses);

                $built_in_statuses = ['draft', 'publish', 'pending', 'private', 'future', 'trash', 'auto-draft', 'inherit'];
                $all_valid_statuses = array_merge($all_valid_statuses, $built_in_statuses);

                $all_valid_statuses = array_unique($all_valid_statuses);

                return in_array($status, $all_valid_statuses);
            };

            $debug_info = [
                'post_type' => $post_type,
                'methods' => [
                    'get_post_statuses' => $wp_statuses,
                    'wp_post_statuses_global' => array_keys($all_status_objects),
                    'db_statuses_for_post_type' => $db_statuses,
                    'all_db_statuses' => $all_db_statuses
                ],
                'validation_tests' => []
            ];

            // Test some common statuses
            $test_statuses = ['draft', 'publish', 'pending', 'private', 'future', 'trash', 'expired', 'scheduled'];
            foreach ($test_statuses as $status) {
                $debug_info['validation_tests'][$status] = $validation_test($status);
            }

            // Test all db statuses
            foreach ($all_db_statuses as $status) {
                $debug_info['validation_tests'][$status] = $validation_test($status);
            }

            return ResponseService::success($debug_info, 'Debug information for post statuses');

        } catch (\Exception $e) {
            return ResponseService::error('Failed to get debug info: ' . $e->getMessage());
        }
    }
}
