<?php
/**
 * Custom Dashboard
 *
 * @package _121Digital\Connect
 */

namespace _121Digital\Connect\Admin\Dashboard;

use _121Digital\Connect\Admin\Services\NoticeService;
use _121Digital\Connect\Core\Environment;
use _121Digital\Connect\Core\Plugin;
use _121Digital\Connect\Integration\ContactForms;
use _121Digital\Connect\User\UserRoles;

/**
 * Dashboard Class
 *
 * Handles custom WordPress dashboard widgets and customizations
 */
class Dashboard
{
    /**
     * Whitelisted dashboard widgets
     *
     * @var array
     */
    private array $whitelistedWidgets = [
        'sc_custom_dashboard_widget',
        'sc_recent_pages_dashboard_widget',
        'sc_quick_create_dashboard_widget',
        'sc_performance_dashboard_widget',

        // allow the Google Site Kit widget if the plugin is active
        'googlesitekit-dashboard-widget',
    ];

    /**
     * ContactForms instance
     *
     * @var ContactForms
     */
    private ContactForms $contactForms;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->contactForms = new ContactForms();
    }

    /**
     * Register dashboard hooks
     *
     * @return void
     */
    public function register(): void
    {
        add_action('wp_dashboard_setup', [$this, 'removeDefaultDashboardWidgets']);
        add_action('wp_dashboard_setup', [$this, 'removeAllOtherDashboardWidgets'], 1000);
        add_action('wp_dashboard_setup', [$this, 'addCustomDashboardWidget']);
        add_action('wp_dashboard_setup', [$this, 'addRecentPagesDashboardWidget']);
        add_action('wp_dashboard_setup', [$this, 'addQuickCreateDashboardWidget']);
        add_action('wp_dashboard_setup', [$this, 'addPerformanceDashboardWidget']);

        // Remove WordPress welcome panel ALWAYS - Multiple strategies
        add_action('admin_init', [$this, 'removeWordPressWelcomePanel'], 1);
        add_action('wp_dashboard_setup', [$this, 'removeWordPressWelcomePanelMetabox'], 999);
        // Force disable welcome panel site-wide
        add_filter('show_welcome_panel', '__return_false', 999);
        // Add CSS to hide welcome panel (runs in admin_head, safe for headers)
        add_action('admin_head', [$this, 'hideWelcomePanelWithCSS'], 1);

        // Use priority 5 to ensure notices are added early in the process
        add_action('admin_notices', [$this, 'maybeRenderPluginAutomaticUpdateNotice'], 5);

        // render custom styles for dashboard widgets
        add_action('admin_head-index.php', [$this, 'renderDashboardStyles']);

        // rename the dashboard title
        add_action('admin_head-index.php', [$this, 'renameDashboardTitle']);
    }

    public function renameDashboardTitle(): void
    {
        global $title;
        $title = 'Website Builder Dashboard';
    }

    /**
     * Remove WordPress welcome panel - Multiple strategies to ensure it's always removed
     *
     * @return void
     */
    public function removeWordPressWelcomePanel(): void
    {
        // Remove the welcome panel meta box
        remove_meta_box('welcome_panel', 'dashboard', 'normal');

        // Also remove via user preference
        update_user_meta(get_current_user_id(), 'show_welcome_panel', 0);
    }

    /**
     * Remove WordPress welcome panel metabox (runs on wp_dashboard_setup hook)
     *
     * @return void
     */
    public function removeWordPressWelcomePanelMetabox(): void
    {
        // Remove the welcome panel meta box
        remove_meta_box('welcome_panel', 'dashboard', 'normal');
    }

    /**
     * Hide welcome panel with CSS (runs in admin_head, safe for headers)
     *
     * @return void
     */
    public function hideWelcomePanelWithCSS(): void
    {
        // Force remove via CSS as well (belt and suspenders approach)
        echo '<style>#welcome-panel { display: none !important; }</style>';
    }

    public function maybeRenderPluginAutomaticUpdateNotice(): void
    {
        if (!is_admin()) {
            return;
        }

        // only show this notice to users who can manage options
        if (!UserRoles::isContextAdministrator()) {
            return;
        }

        if (Plugin::isAutomaticUpdatesEnabled() === false) {
            NoticeService::addWarning(
                '<strong>Admin Warning:</strong> Automatic REG121 Connect updates are currently disabled. 
                It is highly recommended to enable automatic updates to ensure the site remains secure and up-to-date.
                Please enable this feature in the Plugins view.',
                true,
                'reg121-auto-update-warning'
            );
        }
    }

    /**
     * Render custom dashboard styles
     *
     * @return void
     */
    public function renderDashboardStyles(): void
    {
        echo '    
            <style>
                #sc_custom_dashboard_widget.postbox {
                    width: 100% !important; /* Make it span the full width (two columns) */
                }

                @media screen and (min-width: 1200px) {
                    #sc_custom_dashboard_widget.postbox {
                        grid-column: span 2 !important; /* For newer WP versions using CSS grid */
                    }
                }

                /* Optional: make it taller */
                #sc_custom_dashboard_widget .inside {
                    min-height: 400px;
                }
            </style>';
    }

    /**
     * Remove default WordPress dashboard widgets
     *
     * @return void
     */
    public function removeDefaultDashboardWidgets(): void
    {
        remove_meta_box('dashboard_quick_press', 'dashboard', 'side');
        remove_meta_box('dashboard_primary', 'dashboard', 'side');
        remove_meta_box('dashboard_activity', 'dashboard', 'normal');
        remove_meta_box('dashboard_right_now', 'dashboard', 'normal');
        remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
        remove_meta_box('dashboard_incoming_links', 'dashboard', 'normal');
        remove_meta_box('dashboard_plugins', 'dashboard', 'normal');
    }

    /**
     * Remove all dashboard widgets except whitelisted ones
     *
     * @return void
     */
    public function removeAllOtherDashboardWidgets(): void
    {
        global $wp_meta_boxes;

        if (isset($wp_meta_boxes['dashboard'])) {
            foreach ($wp_meta_boxes['dashboard'] as $context => $priorities) {
                foreach ($priorities as $priority => $boxes) {
                    foreach ($boxes as $id => $box) {
                        if (!in_array($id, $this->whitelistedWidgets)) {
                            remove_meta_box($id, 'dashboard', $context);
                        }
                    }
                }
            }
        }
    }

    /**
     * Add custom welcome dashboard widget
     *
     * @return void
     */
    public function addCustomDashboardWidget(): void
    {
        wp_add_dashboard_widget(
            'sc_custom_dashboard_widget',
            'REG121 Website Builder Dashboard',
            [$this, 'renderCustomDashboardWidget']
        );
    }

    /**
     * Render custom dashboard widget content
     *
     * @return void
     */
    public function renderCustomDashboardWidget(): void
    {
        echo '<img src="' . esc_url(SC_PLUGIN_URL . 'static/reg121_brand.svg') . '" alt="REG121 Logo" style="width: 250px; height: auto; margin-top: 20px; margin-bottom: 5px;">';
        echo '<p>This dashboard is your control center for managing your website.</p>';

        echo '<h3><b>Basic Site Management</b></h3>';
        echo '<ul>';
        echo '<li><strong>Pages & Posts:</strong> Create, edit, and organize your site content easily.</li>';
        echo '<li><strong>Media Library:</strong> Upload and manage images, videos, and files.</li>';
        echo '<li><strong>Elementor:</strong> Use Elementor to design beautiful pages with drag-and-drop.</li>';
        echo '<li><strong>Settings:</strong> Customize your site appearance and functionality.</li>';
        echo '</ul>';

        echo '<h3><b>Getting Started Tips</b></h3>';
        echo '<ul>';
        echo '<li>Use the "Pages" menu to add new pages like Home, About, or Contact.</li>';
        echo '<li>Upload your logo and images in the Media Library for branding.</li>';
        echo '<li>Explore Elementor to build custom layouts without coding.</li>';
        echo '<li>Regularly update your content to keep your site fresh and engaging.</li>';
        echo '</ul>';

        echo '<p>If you have any questions or need support, please contact your site administrator.</p>';
    }

    /**
     * Add recent pages dashboard widget
     *
     * @return void
     */
    public function addRecentPagesDashboardWidget(): void
    {
        wp_add_dashboard_widget(
            'sc_recent_pages_dashboard_widget',
            'Recent Pages',
            [$this, 'renderRecentPagesDashboardWidget'],
            null,
            null,
            'side',
            'high'
        );
    }

    /**
     * Render recent pages dashboard widget
     *
     * @return void
     */
    public function renderRecentPagesDashboardWidget(): void
    {
        $recentPages = get_posts([
            'post_type'      => 'page',
            'posts_per_page' => 10,
            'orderby'        => 'date',
            'order'          => 'DESC',
        ]);

        if (empty($recentPages)) {
            echo '<p>No recent pages found.</p>';
            return;
        }

        echo '<table style="width: 100%; border-collapse: collapse;">';
        echo '<thead><tr>';
        echo '<th style="text-align:left; padding:4px;">Title</th>';
        echo '<th style="text-align:left; padding:4px;">Published</th>';
        echo '<th style="text-align:left; padding:4px;">Actions</th>';
        echo '</tr></thead><tbody>';

        $hasElementor = Environment::isElementorActive();

        foreach ($recentPages as $page) {
            $editLink = get_edit_post_link($page->ID);
            $publishedDate = get_the_date('', $page->ID);

            if ($hasElementor) {
                $elementorEditLink = \Elementor\Plugin::$instance->documents->get($page->ID)->get_edit_url();
                $buttons = '<a style="width: 150px; text-align: center;" class="button button-primary" href="' . esc_url($elementorEditLink) . '">Edit Page</a>';
            } else {
                $buttons = '<a style="width: 150px; text-align: center;" class="button" href="' . esc_url($editLink) . '">Classic Editor</a>';
            }

            echo '<tr>';
            echo '<td style="padding:4px;"><a href="' . esc_url($editLink) . '">' . esc_html($page->post_title) . '</a></td>';
            echo '<td style="padding:4px;">' . esc_html($publishedDate) . '</td>';
            echo '<td style="padding:4px;">' . $buttons . '</td>';
            echo '</tr>';
        }

        echo '</tbody></table>';
    }

    /**
     * Add quick create dashboard widget
     *
     * @return void
     */
    public function addQuickCreateDashboardWidget(): void
    {
        wp_add_dashboard_widget(
            'sc_quick_create_dashboard_widget',
            'Quick Create',
            [$this, 'renderQuickCreateDashboardWidget'],
            null,
            null,
            'side',
            'high'
        );
    }

    /**
     * Render quick create dashboard widget
     *
     * @return void
     */
    public function renderQuickCreateDashboardWidget(): void
    {
        ?>
        <style>
            .sc-quick-create-btns {
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
                margin-top: 10px;
            }
            .sc-quick-create-btns a.button {
                flex: 1 0 30%;
                text-align: center;
            }
        </style>
        <p>Quickly create content or start editing with REG121 Web BuilderPro:</p>
        <div class="sc-quick-create-btns">
            <a href="<?php echo admin_url('post-new.php?post_type=page'); ?>" class="button button-primary">
              <span style='margin-top: 5.5px;' class="dashicons dashicons-plus"></span> New Page
            </a>
            <a href="<?php echo admin_url('post-new.php'); ?>" class="button">
              <span style='margin-top: 5.5px;' class="dashicons dashicons-plus"></span> New Post
            </a>
            <a href="<?php echo admin_url('post-new.php?post_type=page&action=elementor'); ?>" class="button">
              <span style='margin-top: 5.5px;' class="dashicons dashicons-plus"></span> New Page
            </a>
        </div>
        <?php
    }

    /**
     * Add performance dashboard widget
     *
     * @return void
     */
    public function addPerformanceDashboardWidget(): void
    {
        wp_enqueue_script(
            'apexcharts',
            SC_PLUGIN_URL . 'static/includes/apexcharts/apexcharts.min.js',
            [],
            null,
            false
        );

        wp_add_dashboard_widget(
            'sc_performance_dashboard_widget',
            'Site Performance',
            [$this, 'renderPerformanceDashboardWidget'],
            null,
            null,
            'side'
        );
    }

    /**
     * Get segmented report of contact form submissions
     *
     * @return array
     */
    private function getSegmentedReport(): array
    {
        $contactRequests = $this->contactForms->getSubmissions();
        $segmentedReport = [];

        foreach ($contactRequests as $request) {
            $date = date('Y-m-d', strtotime($request['entry_date']));
            if (!isset($segmentedReport[$date])) {
                $segmentedReport[$date] = 0;
            }
            $segmentedReport[$date]++;
        }

        if (empty($segmentedReport)) {
            return $segmentedReport;
        }

        $dates = array_keys($segmentedReport);
        sort($dates);

        $minDate = new \DateTime($dates[0]);
        $maxDate = new \DateTime(end($dates));

        $minDate->modify('-2 days');
        $maxDate->modify('+2 days');

        $interval = new \DateInterval('P1D');
        $period = new \DatePeriod($minDate, $interval, $maxDate->modify('+1 day'));

        foreach ($period as $dateObj) {
            $dateStr = $dateObj->format('Y-m-d');
            if (!isset($segmentedReport[$dateStr])) {
                $segmentedReport[$dateStr] = 0;
            }
        }

        ksort($segmentedReport);

        return $segmentedReport;
    }

    /**
     * Render chart JavaScript for performance widget
     *
     * @return void
     */
    private function renderChartJs(): void
    {
        $segmentedReport = $this->getSegmentedReport();
        $dates = [];
        $datesValues = [];

        foreach ($segmentedReport as $date => $count) {
            $dates[] = $date;
            $datesValues[] = $count;
        }

        ?>
        <script>
            var series = {
                monthDataSeries1: {
                    prices: [
                        <?php foreach ($datesValues as $value): ?>
                            <?php echo $value; ?>,
                        <?php endforeach; ?>
                    ],
                    dates: [
                        <?php foreach ($dates as $date): ?>
                            "<?php echo $date; ?>",
                        <?php endforeach; ?>
                    ]
                }
            };

            var options = {
                series: [{
                    name: "All Submissions",
                    data: series.monthDataSeries1.prices
                }],
                chart: {
                    type: 'area',
                    height: 350,
                    zoom: {
                        enabled: false
                    }
                },
                dataLabels: {
                    enabled: false
                },
                stroke: {
                    curve: 'straight'
                },
                title: {
                    text: 'Recent Contact Form Submissions By Date',
                    align: 'left'
                },
                subtitle: {
                    text: 'Form Submissions',
                    align: 'left'
                },
                labels: series.monthDataSeries1.dates,
                xaxis: {
                    type: 'datetime',
                },
                yaxis: {
                    opposite: true
                },
                legend: {
                    horizontalAlign: 'left'
                }
            };

            var chart = new ApexCharts(document.querySelector("#chart"), options);
            chart.render();
        </script>
        <?php
    }

    /**
     * Render performance dashboard widget
     *
     * @return void
     */
    public function renderPerformanceDashboardWidget(): void
    {
        $totalCount = count($this->contactForms->getSubmissions());
        $todayCount = count($this->contactForms->getSubmissionsToday());

        $viewContactRequestsUrl = esc_url(admin_url('admin.php?page=sc-contact-requests'));

        echo '<div style="display: flex; gap: 20px;">';

        echo '<div style="flex: 1; padding: 12px 15px; background: #f1f1f1; border-left: 4px solid #0073aa; display: flex; flex-direction: column; justify-content: center;">';
        echo '<h3 style="margin: 0 0 5px; font-size: 16px;">Total Contact Requests</h3>';
        echo '<p style="margin: 0; font-size: 20px; font-weight: bold;">' . $totalCount . '</p>';
        echo '</div>';

        echo '<div style="flex: 1; padding: 12px 15px; background: #f1f1f1; border-left: 4px solid #00a32a; display: flex; flex-direction: column; justify-content: center;">';
        echo '<h3 style="margin: 0 0 5px; font-size: 16px;">Today\'s Contact Requests</h3>';
        echo '<p style="margin: 0; font-size: 20px; font-weight: bold;">' . $todayCount . '</p>';
        echo '</div>';

        echo '</div>';
        ?>

        <br>
        <div id="chart"></div>

        <?php $this->renderChartJs(); ?>
        <?php

        echo '<br>';
        echo '<a href="' . $viewContactRequestsUrl . '" class="button">View Contact Requests</a>';
    }
}
