<?php

declare(strict_types=1);

namespace Duplicator\Addons\ScheduleAddon\Controllers;

use Duplicator\Controllers\SettingsPageController;
use Duplicator\Core\Controllers\ControllersManager;
use Duplicator\Core\Controllers\PageAction;
use Duplicator\Core\Controllers\SubMenuItem;
use Duplicator\Core\Views\TplMng;
use Duplicator\Libs\Snap\SnapUtil;
use Duplicator\Models\ActivityLog\LogEventSettingsChange;
use Duplicator\Models\GlobalEntity;
use Duplicator\Utils\ActivityLog\SettingsChangeTracker;

/**
 * Handles the Schedule tab in Settings page
 */
class ScheduleSettingsController
{
    const L2_SLUG_SCHEDULE     = 'schedule';
    const ACTION_SAVE_SCHEDULE = 'save-schedule';

    /**
     * Register hooks for settings page integration
     *
     * @return void
     */
    public static function register(): void
    {
        $pageSlug = ControllersManager::SETTINGS_SUBMENU_SLUG;

        add_filter('duplicator_sub_menu_items_' . $pageSlug, [self::class, 'addSubMenu']);
        add_filter('duplicator_page_actions_' . $pageSlug, [self::class, 'addPageActions']);
        add_action('duplicator_render_page_content_' . $pageSlug, [self::class, 'renderContent'], 10, 2);
        add_filter('duplicator_settings_change_sub_type_labels', [self::class, 'addSettingsChangeLabel']);
    }

    /**
     * Add schedule submenu to settings page
     *
     * @param SubMenuItem[] $subMenus Existing sub menus
     *
     * @return SubMenuItem[]
     */
    public static function addSubMenu(array $subMenus): array
    {
        $subMenus[] = new SubMenuItem(self::L2_SLUG_SCHEDULE, __('Schedules', 'duplicator-pro'), '', true, 40);
        return $subMenus;
    }

    /**
     * Add schedule save action to settings page
     *
     * @param PageAction[] $actions Existing actions
     *
     * @return PageAction[]
     */
    public static function addPageActions(array $actions): array
    {
        $actions[] = new PageAction(
            self::ACTION_SAVE_SCHEDULE,
            [
                self::class,
                'saveSchedule',
            ],
            [
                ControllersManager::SETTINGS_SUBMENU_SLUG,
                self::L2_SLUG_SCHEDULE,
            ]
        );

        return $actions;
    }

    /**
     * Render schedule settings content
     *
     * @param string[] $currentLevelSlugs Current menu slugs
     * @param string   $innerPage         Current inner page
     *
     * @return void
     */
    public static function renderContent(array $currentLevelSlugs, string $innerPage): void
    {
        if (($currentLevelSlugs[1] ?? '') !== self::L2_SLUG_SCHEDULE) {
            return;
        }

        TplMng::getInstance()->render('scheduleaddon/admin_pages/settings/schedule/schedule');
    }

    /**
     * Save schedule settings
     *
     * @return array<string, mixed>
     */
    public static function saveSchedule(): array
    {
        $result        = ['saveSuccess' => false];
        $changesTraker = new SettingsChangeTracker();
        $global        = GlobalEntity::getInstance();

        // Track email build mode changes
        $newEmailBuildMode     = SnapUtil::sanitizeIntInput(SnapUtil::INPUT_REQUEST, 'send_email_on_build_mode', 1);
        $emailBuildModeOptions = [
            0 => __('Never', 'duplicator-pro'),
            1 => __('On Failure', 'duplicator-pro'),
            2 => __('Always', 'duplicator-pro'),
        ];
        $changesTraker->addChange(
            'send_email_on_build_mode',
            $global->send_email_on_build_mode,
            $newEmailBuildMode,
            'optionChanged',
            $emailBuildModeOptions
        );
        $global->send_email_on_build_mode = $newEmailBuildMode;

        // Track notification email address changes
        $newEmailAddress = sanitize_email(wp_unslash($_REQUEST['notification_email_address']));
        $changesTraker->addChange(
            'notification_email_address',
            $global->notification_email_address,
            $newEmailAddress,
            'fieldChanged'
        );
        $global->notification_email_address = $newEmailAddress;

        if ($global->save()) {
            $result['saveSuccess']    = true;
            $result['successMessage'] = __('Schedule settings updated.', 'duplicator-pro');

            $changesTraker->createLog('schedule');
        } else {
            $result['errorMessage'] = __('Can\'t update schedule settings.', 'duplicator-pro');
        }

        return $result;
    }

    /**
     * Add schedule label to settings change sub-type labels
     *
     * @param array<string, string> $labels Existing labels
     *
     * @return array<string, string>
     */
    public static function addSettingsChangeLabel(array $labels): array
    {
        $labels['schedule'] = __('Schedule', 'duplicator-pro');

        return $labels;
    }
}
