<?php

namespace MediaTrim\Admin;

use MediaTrim\Traits\Singleton;

defined('ABSPATH') || exit;

/**
 * Class Admin
 *
 * Handles admin menu, scripts, styles, and media cleaning for Media Image Cleaner.
 *
 * @package MediaTrim\Admin
 */
class Admin
{
    use Singleton;

    /**
     * Constructor - Bootstrap admin hooks.
     */
    public function __construct()
    {
        // Admin menu & dashboard
        add_action('admin_menu', [$this, 'add_menu_page']);
        add_action('admin_init', [$this, 'remove_admin_notices']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_styles']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_scripts']);
        add_action('plugin_action_links', [$this, 'add_action_links'], 10, 2);
        add_action('wp_ajax_mtrim_get_stats', [$this, 'ajax_get_stats']);
    }

    /**
     * Register the Media Trim menu entry in wp-admin.
     */
    public function add_menu_page()
    {
        add_menu_page(
            __('Media Trim', 'media-trim'),
            __('Media Trim', 'media-trim'),
            'manage_options',
            'mtrim-dashboard',
            [$this, 'display_page'],
            'dashicons-images-alt2',
            30
        );

        add_submenu_page(
            'mtrim-dashboard',
            __('Dashboard', 'media-trim'),
            __('Dashboard', 'media-trim'),
            'manage_options',
            'mtrim-dashboard',
            [$this, 'display_page']
        );

        add_submenu_page(
            'mtrim-dashboard',
            __('Unused Media', 'media-trim'),
            __('Unused Media', 'media-trim'),
            'manage_options',
            'mtrim-unused',
            [$this, 'display_page']
        );

        add_submenu_page(
            'mtrim-dashboard',
            __('Duplicates', 'media-trim'),
            __('Duplicates', 'media-trim'),
            'manage_options',
            'mtrim-duplicates',
            [$this, 'display_page']
        );

        add_submenu_page(
            'mtrim-dashboard',
            __('Orphaned Files', 'media-trim'),
            __('Orphaned Files', 'media-trim'),
            'manage_options',
            'mtrim-orphaned',
            [$this, 'display_page']
        );

        add_submenu_page(
            'mtrim-dashboard',
            __('Stock Images', 'media-trim'),
            __('Stock Images', 'media-trim'),
            'manage_options',
            'mtrim-stock',
            [$this, 'display_page']
        );

        add_submenu_page(
            'mtrim-dashboard',
            __('Trash', 'media-trim'),
            __('Trash', 'media-trim'),
            'manage_options',
            'mtrim-trash',
            [$this, 'display_page']
        );

        add_submenu_page(
            'mtrim-dashboard',
            __('Settings', 'media-trim'),
            __('Settings', 'media-trim'),
            'manage_options',
            'mtrim-settings',
            [$this, 'display_page']
        );
    }

    /**
     * Render the React admin container.
     */
    public function display_page()
    {
        echo "<div id='media-trim-admin'></div>";
    }

    /**
     * Hide default WP admin notices inside the Media Trim dashboard.
     */
    public function remove_admin_notices()
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page parameter for conditional only, no state change.
        $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
        if ($page && strpos($page, 'mtrim-') === 0) {
            remove_all_actions('admin_notices');
            remove_all_actions('all_admin_notices');
        }
    }

    /**
     * Load admin styles for dashboard.
     */
    public function enqueue_styles($hook)
    {
        if (strpos($hook, 'mtrim-') !== false) {
            wp_enqueue_style(
                'media-trim-admin',
                MTRIM_PLUGIN_URL . 'assets/admin/dashboard.css',
                [],
                MTRIM_VERSION
            );
        }
    }

    /**
     * Load admin scripts and localize data for the dashboard.
     */
    public function enqueue_scripts($hook)
    {
        if (strpos($hook, 'mtrim-') === false) {
            return;
        }

        $script_asset_path = MTRIM_PLUGIN_PATH . 'assets/admin/dashboard.asset.php';
        $script_asset = file_exists($script_asset_path)
            ? require($script_asset_path)
            : ['dependencies' => [], 'version' => MTRIM_VERSION];

        wp_enqueue_script(
            'media-trim-admin',
            MTRIM_PLUGIN_URL . 'assets/admin/dashboard.js',
            $script_asset['dependencies'],
            $script_asset['version'],
            true
        );

        wp_localize_script('media-trim-admin', 'mtrimAdminData', [
            'nonce'       => wp_create_nonce('mtrim_admin_nonce'),
            'adminUrl'    => admin_url(),
            'ajaxUrl'     => admin_url('admin-ajax.php'),
            'restUrl'     => get_rest_url(),
            'pluginUrl'   => MTRIM_PLUGIN_URL,
            'version'     => MTRIM_VERSION,
            'stats'       => $this->get_stats(),
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading page parameter for conditional display only, no state change.
            'currentPage' => isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : 'mtrim-dashboard',
        ]);
    }

    /**
     * AJAX handler to get fresh stats.
     */
    public function ajax_get_stats()
    {
        check_ajax_referer('mtrim_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Unauthorized', 'media-trim')]);
        }

        wp_send_json_success($this->get_stats());
    }

    /**
     * Get updated stats for the dashboard
     */
    public function get_stats()
    {
        global $wpdb;
        $table = $wpdb->prefix . 'mtrim_scan_results';
        
        $count_posts = wp_count_posts('attachment');
        $total_media = 0;
        foreach ($count_posts as $status => $count) {
            $total_media += $count;
        }

        $unused_media = 0;
        $duplicates = 0;

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name is safely constructed.
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table))) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name is safely constructed.
            $unused_media = $wpdb->get_var("SELECT COUNT(*) FROM $table WHERE status = 'unused'");
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Table name is safely constructed.
            $duplicates = $wpdb->get_var("SELECT COUNT(*) FROM (SELECT file_hash FROM $table GROUP BY file_hash HAVING COUNT(*) > 1) as dups");
        }

        return [
            'total'   => (int)$total_media,
            'unused'  => (int)$unused_media,
            'duplicates' => (int)$duplicates,
        ];
    }

    /**
     * Add settings link to plugin action links.
     */
    public function add_action_links($links, $file)
    {
        if ($file === MTRIM_PLUGIN_BASENAME) {
            $settings_link = sprintf(
                '<a href="%s">%s</a>',
                admin_url('admin.php?page=mtrim-settings'),
                __('Settings', 'media-trim')
            );
            array_unshift($links, $settings_link);
        }

        return $links;
    }
}