<?php

namespace _121Digital\Connect\Network\Views\ViewSite;

use _121Digital\Connect\Core\Plugin;
use _121Digital\Connect\Network\Models\SiteDTO;
use _121Digital\Connect\Network\Services\NodeSiteService;

class ViewSite
{
    private $siteId;

    private $siteDetails;

    private $successMessage = '';

    private $errorMessage = '';

    public function register(): void
    {
        if (!\_121Digital\Connect\Core\Environment::isMultisiteNode() ||
           !\_121Digital\Connect\User\UserRoles::isContextAdministrator() ||
           !is_network_admin()) {
            return;
        }

        // Get site ID from URL parameter
        $this->siteId = isset($_GET['site_id']) ? absint($_GET['site_id']) : 0;

        if (!$this->siteId) {
            Plugin::die(__('Invalid site ID.', '121-connect'));
        }

        // Get site details
        $this->siteDetails = get_site($this->siteId);

        if (!$this->siteDetails) {
            Plugin::die(__('Site not found.', '121-connect'));
        }

        // Handle form submission
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_site_nonce'])) {
            $this->handleFormSubmission();
        }

        $this->render();
    }

    private function handleFormSubmission(): void
    {
        // Verify nonce
        if (!wp_verify_nonce($_POST['update_site_nonce'], 'update_site_action_' . $this->siteId)) {
            $this->errorMessage = __('Security check failed. Please try again.', '121-connect');
            return;
        }

        try {
            // Create SiteDTO from form data
            $siteDTO = new SiteDTO(
                siteId: $this->siteId,
                siteName: isset($_POST['site_name']) ? sanitize_text_field($_POST['site_name']) : null,
                domain: null, // Domain cannot be changed
                path: null, // Path cannot be changed
                adminEmail: isset($_POST['admin_email']) ? sanitize_email($_POST['admin_email']) : null,
                siteDescription: isset($_POST['site_description']) ? sanitize_text_field($_POST['site_description']) : null,
                language: isset($_POST['language']) ? sanitize_text_field($_POST['language']) : null,
                visibility: isset($_POST['visibility']) ? sanitize_text_field($_POST['visibility']) : null,
                archived: isset($_POST['archived']) && $_POST['archived'] === '1',
                spam: isset($_POST['spam']) && $_POST['spam'] === '1',
                deleted: isset($_POST['deleted']) && $_POST['deleted'] === '1',
                mature: isset($_POST['mature']) && $_POST['mature'] === '1'
            );

            // Update the site using the DTO
            NodeSiteService::updateSite($siteDTO);

            // Refresh site details
            $this->siteDetails = get_site($this->siteId);

            $this->successMessage = __('Site updated successfully.', '121-connect');
        } catch (\Exception $e) {
            $this->errorMessage = __('Error updating site: ', '121-connect') . $e->getMessage();
        }
    }

    public function render(): void
    {
        $siteId = $this->siteId;
        $siteDetails = $this->siteDetails;
        $successMessage = $this->successMessage;
        $errorMessage = $this->errorMessage;

        // Switch to the site to get additional details
        switch_to_blog($siteId);

        // Get site options
        $siteName = get_option('blogname');
        $siteDescription = get_option('blogdescription');
        $siteLanguage = get_option('WPLANG');
        $siteAdminEmail = get_option('admin_email');
        $publicSetting = get_option('blog_public');

        // Get site users
        $siteUsers = get_users(['blog_id' => $siteId, 'fields' => ['ID', 'display_name', 'user_email']]);

        // Get site info
        $siteUrl = get_home_url($siteId);
        $siteAdminUrl = get_admin_url($siteId);

        // Get theme info
        $currentTheme = wp_get_theme();
        $themeName = $currentTheme->get('Name');

        // Get plugin count
        $allPlugins = get_plugins();
        $activePlugins = get_option('active_plugins', []);
        $pluginCount = count($activePlugins);

        // Get post/page count
        $postCounts = wp_count_posts('post');
        $pageCounts = wp_count_posts('page');

        restore_current_blog();

        // Format dates
        $registeredDate = mysql2date(get_option('date_format') . ' ' . get_option('time_format'), $siteDetails->registered);
        $lastUpdated = mysql2date(get_option('date_format') . ' ' . get_option('time_format'), $siteDetails->last_updated);

        require_once dirname(__FILE__) . '/html/ViewSite.tpl.php';
    }
}
