<?php
/**
 * Admin menu registration and page rendering.
 *
 * @package MediaTasker
 */

// Prevent direct file access.
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class Mediat_Admin
 *
 * Registers admin menus, enqueues admin assets,
 * and renders the General Info dashboard page.
 */
class Mediat_Admin
{

    /**
     * Hook into WordPress.
     *
     * @return void
     */
    public static function init()
    {
        add_action('admin_menu', array(__CLASS__, 'register_menus'));
        add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_assets'));
        add_action('wp_ajax_mediat_fetch_work_logs', array(__CLASS__, 'fetch_work_logs'));
    }

    /**
     * Register the top-level admin menu page.
     *
     * Freemius automatically attaches Account / Contact Us
     * under this parent slug.
     *
     * @return void
     */
    public static function register_menus()
    {
        // Main General Info Page.
        add_menu_page(
            esc_html__('MediaTasker', 'mediatasker'),
            esc_html__('Media Tasker', 'mediatasker'),
            'manage_options',
            'mediatasker',
            array(__CLASS__, 'render_general_info'),
            'dashicons-format-gallery',
            30
        );

        // Settings Submenu Page.
        add_submenu_page(
            'mediatasker',
            esc_html__('Settings - MediaTasker', 'mediatasker'),
            esc_html__('Settings', 'mediatasker'),
            'manage_options',
            'media-tasker-settings',
            array(__CLASS__, 'render_settings_page')
        );

        // Work Log Submenu Page.
        add_submenu_page(
            'mediatasker',
            esc_html__('Work Log - MediaTasker', 'mediatasker'),
            esc_html__('Work Log', 'mediatasker'),
            'manage_options',
            'mediat_work-log',
            array(__CLASS__, 'render_work_log_page')
        );

        // Premium Features Submenu (Free Version Only).
        if (!mediat_fs()->is_paying()) {
            add_submenu_page(
                'mediatasker',
                esc_html__('Premium Features - MediaTasker', 'mediatasker'),
                sprintf(
                    '%s <span class="mediat_pro-badge">%s</span>',
                    esc_html__('Premium Features', 'mediatasker'),
                    esc_html__('PRO', 'mediatasker')
                ),
                'manage_options',
                'mediat_premium-features',
                array(__CLASS__, 'render_premium_features_page')
            );
        }
    }

    /**
     * Render the General Information admin page.
     *
     * @return void
     */
    public static function render_general_info()
    {
        // Gather stats for the template.
        $mediat_stats = self::get_dashboard_stats();

        include MEDIAT_PLUGIN_DIR . 'admin/views/general-info.php';
    }

    /**
     * Render the Settings admin page.
     *
     * @return void
     */
    public static function render_settings_page()
    {
        include MEDIAT_PLUGIN_DIR . 'admin/views/settings.php';
    }

    /**
     * Render the Work Log admin page.
     *
     * @return void
     */
    public static function render_work_log_page()
    {
        include MEDIAT_PLUGIN_DIR . 'admin/views/work-log.php';
    }

    /**
     * Render the Premium Features admin page.
     *
     * @return void
     */
    public static function render_premium_features_page()
    {
        include MEDIAT_PLUGIN_DIR . 'admin/views/premium-features.php';
    }

    /**
     * Collect dashboard statistics.
     *
     * @return array {
     *     @type int $original_images Number of mediat_task posts (any status).
     *     @type int $edited_images   Placeholder — 0 until media versioning is built.
     *     @type int $total_comments  Total comments on mediat_task posts.
     * }
     */
    private static function get_dashboard_stats()
    {
        $counts = wp_count_posts('mediat_task');

        $original_images = 0;
        if ($counts) {
            // Sum across all custom statuses + standard publish / draft.
            foreach ($counts as $count) {
                $original_images += (int) $count;
            }
        }

        $total_comments = (int) get_comments(
            array(
                'post_type' => 'mediat_task',
                'count' => true,
            )
        );

        return array(
            'original_images' => $original_images,
            'edited_images' => 0,
            'total_comments' => $total_comments,
        );
    }

    /**
     * AJAX handler: fetch work logs for the admin table.
     *
     * @return void
     */
    public static function fetch_work_logs()
    {
        check_ajax_referer('mediat_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => esc_html__('Permission denied.', 'mediatasker')), 403);
        }

        if (!class_exists('Mediat_Work_Log')) {
            require_once MEDIAT_PLUGIN_DIR . 'includes/class-mediat_work-log.php';
        }

        $mediat_args = array(
            'limit' => isset($_POST['limit']) ? absint(wp_unslash($_POST['limit'])) : 50,
            'offset' => isset($_POST['offset']) ? absint(wp_unslash($_POST['offset'])) : 0,
            'action_type' => isset($_POST['action_type']) ? sanitize_text_field(wp_unslash($_POST['action_type'])) : '',
            'date_from' => isset($_POST['date_from']) ? sanitize_text_field(wp_unslash($_POST['date_from'])) : '',
            'date_to' => isset($_POST['date_to']) ? sanitize_text_field(wp_unslash($_POST['date_to'])) : '',
            'user_id' => isset($_POST['user_id']) ? absint(wp_unslash($_POST['user_id'])) : 0,
        );

        $mediat_logs = Mediat_Work_Log::get_logs($mediat_args);
        $mediat_total = Mediat_Work_Log::get_total_logs($mediat_args);

        ob_start();
        include MEDIAT_PLUGIN_DIR . 'admin/views/work-log-rows.php';
        $html = ob_get_clean();

        wp_send_json_success(array(
            'html' => $html,
            'total' => $mediat_total,
            'has_more' => ($mediat_args['offset'] + count($mediat_logs) < $mediat_total)
        ));
    }

    /**
     * Enqueue admin stylesheets and scripts.
     *
     * Only loads on MediaTasker admin pages.
     *
     * @param string $hook_suffix The current admin page hook suffix.
     * @return void
     */
    public static function enqueue_assets($hook_suffix)
    {
        // Only load on MediaTasker pages.
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';

        // If it's a MediaTasker page (contains mediatasker or starts with mediat_).
        $is_mediat_page = (false !== strpos($hook_suffix, 'mediatasker') || false !== strpos($page, 'mediat_') || false !== strpos($page, 'media-tasker'));

        if (!$is_mediat_page) {
            return;
        }

        wp_enqueue_style(
            'mediat_admin-style',
            MEDIAT_PLUGIN_URL . 'assets/css/admin.css',
            array(),
            MEDIAT_VERSION
        );

        wp_enqueue_script(
            'mediat_admin-script',
            MEDIAT_PLUGIN_URL . 'assets/js/admin.js',
            array('jquery'),
            MEDIAT_VERSION,
            true
        );

        wp_localize_script('mediat_admin-script', 'mediat_admin', array(
            'nonce' => wp_create_nonce('mediat_admin_nonce')
        ));

        // Load specific style for the Premium Features page.
        if ('mediat_premium-features' === $page || false !== strpos($hook_suffix, 'mediat_premium-features')) {
            wp_enqueue_style(
                'mediat_premium-features-style',
                MEDIAT_PLUGIN_URL . 'assets/css/mediat_premium-features.css',
                array(),
                time() // Cache buster for debugging
            );
        }
    }
}
