<?php

namespace GriffinForms\Admin;

class Pages extends \GriffinForms\Admin\Format
{
    public $menu_pages = array();
    public $internal_pages = array();
    public $settings_pages = array();
    protected static $instance;
    
    protected function getItemFiles()
    {
        $indexed_files = array();
        $unindexed_files = array();
        $dir = plugin_dir_path(__FILE__) . 'views/';
    
        if (!is_dir($dir)) {
            // Handle error: Directory does not exist
            $this->log->add('error', 'pages', 0, get_current_user_id(), "Directory not found: $dir", 'data');
            return;
        }
    
        $files = glob($dir . '*.php');
    
        if ($files === false) {
            // Handle error: Failed to read directory
            $this->log->add('error', 'pages', 0, get_current_user_id(), "Failed to read directory: $dir", 'data');
            return;
        }
    
        foreach ($files as $file_path) {
            $file_name = basename($file_path, '.php');
            $split_filename = explode('_', $file_name, 2);
    
            if (isset($split_filename[1]) && is_numeric($split_filename[0])) {
                $index = absint($split_filename[0]);
                $indexed_files[$index] = $split_filename[1];
            } else {
                $unindexed_files[] = $split_filename[0];
            }
        }
    
        // Sort the arrays
        ksort($indexed_files);
        sort($unindexed_files);
    
        $this->menu_pages = $indexed_files;
        $this->internal_pages = $unindexed_files;
    }

    /**
     * Populates the $settings_pages array with available settings page slugs.
     *
     * The function scans the 'views/settings/' directory for PHP files. It allows for an optional
     * custom ordering of known setting slugs via the $ordered array. Files listed in this array
     * are added first to $settings_pages in that order. Any remaining files found in the directory
     * that are not in the ordered list are added afterward in the order they are discovered.
     *
     * This approach preserves the ease of adding new settings pages by simply placing new PHP files
     * into the directory, while also supporting manual tab ordering for specific pages.
     */
    protected function getSettingsFiles()
    {
        $settings_files = [];
        $dir = plugin_dir_path(__FILE__) . 'views/settings/';
        $ordered = ['general', 'ai', 'compliance', 'mail', 'payments', 'capabilitymatrix', 'antispam']; // define desired order

        if (!is_dir($dir)) {
            $this->log->add('error', 'pages', 0, get_current_user_id(), "Directory not found: $dir", 'data');
            return;
        }

        $files = glob($dir . '*.php');
        if ($files === false) {
            $this->log->add('error', 'pages', 0, get_current_user_id(), "Failed to read directory: $dir", 'data');
            return;
        }

        $all_found = [];
        foreach ($files as $file_path) {
            $file_name = basename($file_path, '.php');
            if (!$this->shouldIncludeSettingsPage($file_name)) {
                continue;
            }
            $all_found[] = $file_name;
        }

        // Add ordered files first
        foreach ($ordered as $slug) {
            if (in_array($slug, $all_found)) {
                $this->settings_pages[] = $slug;
            }
        }

        // Add remaining files that weren't in the ordered list
        foreach ($all_found as $slug) {
            if (!in_array($slug, $this->settings_pages)) {
                $this->settings_pages[] = $slug;
            }
        }

        if (($license_index = array_search('license', $this->settings_pages, true)) !== false) {
            unset($this->settings_pages[$license_index]);
            $this->settings_pages[] = 'license';
            $this->settings_pages = array_values($this->settings_pages);
        }
    }

    protected function shouldIncludeSettingsPage(string $slug): bool
    {
        $slug = sanitize_key($slug);

        if ($slug === 'license' && class_exists('\GriffinForms\Admin\Menu')) {
            return \GriffinForms\Admin\Menu::isProEnabled();
        }

        return true;
    }
    
    public static function getInstance()
    {
        if (self::$instance == null)
        {
            self::$instance = new Pages();
        }
        
        return self::$instance;
    }
    
    private function __construct()
    {
        $this->getItemFiles();
        $this->getSettingsFiles();
    }
}
