<?php
namespace dpcdCategoryDesign;

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

    /**
     * Get all post status
     *
     * @return boolean
     */
    public static function getPostStatus() {
        return [
            'publish'    => esc_html__( 'Publish','dynamic-product-categories-design' ),
            'pending'    => esc_html__( 'Pending', 'dynamic-product-categories-design' ),
            'draft'      => esc_html__( 'Draft', 'dynamic-product-categories-design' ),
            'auto-draft' => esc_html__( 'Auto draft', 'dynamic-product-categories-design' ),
            'future'     => esc_html__( 'Future', 'dynamic-product-categories-design' ),
            'private'    => esc_html__( 'Private', 'dynamic-product-categories-design' ),
            'inherit'    => esc_html__( 'Inherit', 'dynamic-product-categories-design' ),
            'trash'      => esc_html__( 'Trash', 'dynamic-product-categories-design' ),
        ];
    }

    /**
     * Get all Order By
     *
     * @return boolean
     */
    public static function getOrderBy() {
        return [
                'date'          => esc_html__( 'Date', 'dynamic-product-categories-design' ),
                'ID'            => esc_html__( 'Order by post ID', 'dynamic-product-categories-design' ),
                'author'        => esc_html__( 'Author', 'dynamic-product-categories-design' ),
                'title'         => esc_html__( 'Title', 'dynamic-product-categories-design' ),
                'modified'      => esc_html__( 'Last modified date', 'dynamic-product-categories-design' ),
                'parent'        => esc_html__( 'Post parent ID', 'dynamic-product-categories-design' ),
                'comment_count' => esc_html__( 'Number of comments', 'dynamic-product-categories-design' ),
                'menu_order'    => esc_html__( 'Menu order', 'dynamic-product-categories-design' ),
        ];
    }


    /**
     * Get bootstrap layout class
     *
     * @return string
     */

     public static function get_grid_layout_bootstrap_class($desktop = '1', $tablet = '1', $mobile = '1') {
        // Ensure parameters are strings to prevent unintended behavior
        $desktop = (string) $desktop;
        $tablet  = (string) $tablet;
        $mobile  = (string) $mobile;
    
        // Define layout mappings for different screen sizes
        $layouts = [
            'desktop' => [
                '1' => 'lg-12', '2' => 'lg-6', '3' => 'lg-4', '4' => 'lg-3'
            ],
            'tablet' => [
                '1' => 'md-12', '2' => 'md-6', '3' => 'md-4', '4' => 'md-3'
            ],
            'mobile' => [
                '1' => '12', '2' => '6', '3' => '4', '4' => '3'
            ]
        ];
    
        // Helper function to get class or fallback to default
        $get_class = function($key, $mapping) {
            return $mapping[$key] ?? $mapping['1']; // Default to '1' if invalid key
        };
    
        // Generate class names dynamically
        return sprintf(
            "pcd-col-%s pcd-col-%s pcd-col-%s",
            $get_class($desktop, $layouts['desktop']),
            $get_class($tablet, $layouts['tablet']),
            $get_class($mobile, $layouts['mobile'])
        );
    }

    /**
	 * Render.
	 *
	 * @param string  $view_name View name.
	 * @param array   $args View args.
	 * @param boolean $return View return.
	 *
	 * @return string|void
	 */
	public static function render($view_name, $args = [], $return = false) {
        // Sanitize the template path to prevent directory traversal
        $path = preg_replace('/[^a-zA-Z0-9_\-\/]/', '', str_replace('.', '/', $view_name));
        $template_file = DPCD_PATH . '/pcd-templates/' . $path . '.php';
    
        // Ensure the file exists and prevent unauthorized access
        if (!file_exists($template_file) || !is_readable($template_file)) {
            error_log("Template file not found or inaccessible: " . $template_file);
            return $return ? '' : null;
        }
    
        // Secure variable scope - avoid extract()
        if ($args && is_array($args)) {
            foreach ($args as $key => $value) {
                ${$key} = $value;
            }
        }
    
        if ($return) {
            ob_start();
            try {
                include $template_file;
                return ob_get_clean();
            } catch (Exception $e) {
                ob_end_clean();
                error_log("Error rendering template: " . $e->getMessage());
                return '';
            }
        } else {
            include $template_file;
        }
    }
    
    /**
     * Generate Shortcode for generate css
     *
     * @param integer $scID
     *
     * @return void
    */

    public static function generatorShortcodeCss($scID) {
        global $wp_filesystem;
    
        // Ensure $scID is an integer to prevent path traversal
        $scID = intval($scID);
        if (!$scID) {
            error_log('Invalid shortcode ID received for CSS generation.');
            return;
        }
    
        // Initialize WP Filesystem securely
        if (empty($wp_filesystem)) {
            require_once ABSPATH . '/wp-admin/includes/file.php';
            if (!WP_Filesystem()) {
                error_log('Failed to initialize WP Filesystem.');
                return;
            }
        }
    
        $upload_dir = wp_upload_dir();
        $base_dir   = $upload_dir['basedir'];
        $css_file   = $base_dir . '/dynamic-product-category-design/category-design.css';
    
        // Ensure the directory exists securely
        if (!is_dir($base_dir . '/dynamic-product-category-design')) {
            if (!wp_mkdir_p($base_dir . '/dynamic-product-category-design')) {
                error_log('Failed to create CSS directory: ' . $base_dir . '/dynamic-product-category-design');
                return;
            }
        }
    
        // Render and sanitize CSS output
        $css_content = self::render('style', compact('scID'), true);
        if (!$css_content) {
            error_log('No CSS content generated for shortcode ID: ' . $scID);
            return;
        }
    
        $css_content = sanitize_text_field($css_content); // Ensures no harmful code
        $css_snippet = sprintf('/*wc-pcd-%2$d-start*/%1$s/*wc-pcd-%2$d-end*/', esc_textarea($css_content), $scID);
    
        // Read existing CSS if file exists
        $existing_css = '';
        if ($wp_filesystem->exists($css_file)) {
            $existing_css = $wp_filesystem->get_contents($css_file);
            if ($existing_css && strpos($existing_css, "/*wc-pcd-$scID-start*/") !== false) {
                // Remove old instance securely
                $existing_css = preg_replace("/\/\*wc-pcd-$scID-start\*\/.*?\/\*wc-pcd-$scID-end\*\//s", '', $existing_css);
                $existing_css = trim(preg_replace("/(\r?\n){2,}/", "\n", $existing_css)); // Remove excessive blank lines
            }
        }
    
        // Check if new content is the same as existing to avoid unnecessary writes
        $final_css = trim($existing_css . "\n" . $css_snippet);
        if ($final_css === trim($existing_css)) {
            return; // No changes, no need to write
        }
    
        // Write the updated CSS file securely
        if (!$wp_filesystem->put_contents($css_file, $final_css, FS_CHMOD_FILE)) {
            error_log('Failed to write the CSS file: ' . $css_file);
        }
    }

    /**
     * Generate Shortcode for remove css
     *
     * @param integer $scID
     *
     * @return void
     */
    public static function removeGeneratorShortcodeCss($scID) {
    global $wp_filesystem;

    // Ensure $scID is a valid integer to prevent path traversal
    $scID = intval($scID);
    if (!$scID) {
        error_log('Invalid shortcode ID provided for CSS removal.');
        return;
    }

    // Initialize WP Filesystem if not already set
    if (empty($wp_filesystem)) {
        require_once ABSPATH . '/wp-admin/includes/file.php';
        if (!WP_Filesystem()) {
            error_log('Failed to initialize WP Filesystem.');
            return;
        }
    }

    // Define file path
    $upload_dir = wp_upload_dir();
    $css_file   = $upload_dir['basedir'] . '/dynamic-product-category-design/category-design.css';

    // Check if file exists and read contents securely
    if (!$wp_filesystem->exists($css_file)) {
        return; // File doesn't exist, nothing to remove
    }

    $old_css = $wp_filesystem->get_contents($css_file);
    if (!$old_css || strpos($old_css, "/*wc-pcd-$scID-start*/") === false) {
        return; // No relevant CSS to remove
    }

    // Remove specific shortcode's CSS securely
    $updated_css = preg_replace("/\/\*wc-pcd-$scID-start\*\/.*?\/\*wc-pcd-$scID-end\*\//s", '', $old_css);
    $updated_css = trim(preg_replace("/(\r?\n){2,}/", "\n", $updated_css)); // Remove excessive blank lines

    // Only write to the file if changes were made
    if ($updated_css !== $old_css) {
        if (!$wp_filesystem->put_contents($css_file, $updated_css, FS_CHMOD_FILE)) {
            error_log('Failed to update the CSS file: ' . $css_file);
        }
    }
}

public static function get_product_category_count( $category ) {
    // Get the term object for the category
    $pcd_term = get_term( $category, 'product_cat' );

    // Check if the term exists and has a valid count property
    if ( ! is_wp_error( $pcd_term ) && isset( $pcd_term->count ) ) {
        // Return the count of products in this category
        return $pcd_term->count;
    }

    // Return 0 if there was an error or no count is available
    return 0;
}


/**
 * Retrieve a list of child categories for a given parent category ID and taxonomy.
 *
 * @param int $parentCatId Parent category ID.
 * @param string $taxonomy Taxonomy to use. Defaults to 'product_cat'.
 *
 * @return string HTML list of child categories.
 */
public static function get_woo_child_category_by_id($parentCatId, $taxonomy = 'product_cat') {
    // Ensure parent category ID is an integer to prevent unexpected behavior
    $parentCatId = intval($parentCatId);
    if (!$parentCatId) {
        return ''; // Return empty if invalid ID
    }

    // Fetch child categories securely
    $terms = get_terms([
        'taxonomy'    => $taxonomy, // Use provided taxonomy
        'hide_empty'  => true,
        'parent'      => $parentCatId
    ]);

    // Ensure $terms is a valid array before processing
    if (empty($terms) || is_wp_error($terms)) {
        return ''; // Return empty if no categories found or there's an error
    }

    $output = '<ul class="pcd-subcategories-list">';
    
    foreach ($terms as $term) {
        $term_link = get_term_link($term, $taxonomy);
        if (!is_wp_error($term_link)) { // Ensure term link is valid
            $output .= sprintf(
                '<li class="%s"><a href="%s">%s</a></li>',
                esc_attr($term->slug),
                esc_url($term_link),
                esc_html($term->name)
            );
        }
    }

    $output .= '</ul>';

    return wp_kses_post($output); // Securely return the HTML
}

}