<?php

namespace DEVELUXSCT\Options;

if (!defined('ABSPATH')) {
    exit;
}

class Plugin_Main_Options_Page
{
    private string $translateDomain = 'devellux-sales-countdown-timer-builder';

    public function __construct()
    {
        //Setup main plugin page
        add_action('admin_menu', [$this, 'create_page']);

        // Fix active sub menu on builder page
        add_filter('parent_file', [$this, 'fix_parent_menu']);
        add_filter('submenu_file', [$this, 'fix_submenu_item']);

        if (class_exists('WooCommerce')) {
            new Timer_CPT();
        }
    }

    public function create_page(): void
    {
        // Timer
        add_submenu_page('woocommerce',
            esc_html__('Single Timer Builder', 'devellux-sales-countdown-timer-builder'),
            '',
            'manage_options',
            'develux-timer-builder',
            [$this, 'plugin_timer_builder']
        );
        add_submenu_page(
            'woocommerce',
            esc_html__('Sale Timer Builder', 'devellux-sales-countdown-timer-builder'),
            esc_html__('Sale Timer Builder', 'devellux-sales-countdown-timer-builder'),
            'manage_options',
            'develux-timer',
            [$this, 'plugin_timers']
        );
    }

    public function plugin_timers(): void
    {
        $label_editor = new Timer_Editor();
        $label_editor->display_timers();
    }

    public function plugin_timer_builder(): void
    {
        $label_editor = new Timer_Editor();
        $label_editor->display_builder_form();
    }

    public function fix_parent_menu($parent_file)
    {
        global $current_screen;

        if ($current_screen && $current_screen->id === 'woocommerce_page_develux-timer-builder') {
            return 'woocommerce';
        }

        return $parent_file;
    }

    public function fix_submenu_item($submenu_file)
    {
        global $current_screen, $submenu;

        if (isset($submenu['woocommerce'])) {
            foreach ($submenu['woocommerce'] as $i => $item) {
                if ($item[2] === 'develux-timer-builder') {
                    unset($submenu['woocommerce'][$i]);
                }
            }
            $submenu['woocommerce'] = array_values($submenu['woocommerce']);
        }

        if ($current_screen && $current_screen->id === 'woocommerce_page_develux-timer-builder') {
            return 'develux-timer';
        }

        return $submenu_file;
    }
}