<?php

/*
 * Million Dollar Script Two
 *
 * @author      Ryan Rhode
 * @copyright   (C) 2025, Ryan Rhode
 * @license     https://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *
 *    Million Dollar Script
 *    Pixels to Profit: Ignite Your Revolution
 *    https://milliondollarscript.com/
 *
 */

namespace MillionDollarScript\Classes\Web;

use MillionDollarScript\Classes\System\Utility;
use MillionDollarScript\Classes\Data\Options;
use MillionDollarScript\Classes\System\Filesystem;

defined( 'ABSPATH' ) or exit;

/**
 * Output dynamic CSS styles for frontend and login pages.
 */
class Styles {

    private const DYNAMIC_CSS_FILENAME = 'dynamic-styles.css';

    /**
     * Get the absolute server path to the dynamic CSS file.
     *
     * @return string
     */
    public static function get_dynamic_css_filepath(): string {
        $upload_path = Utility::get_upload_path(); // e.g., /var/www/html/wp-content/uploads/milliondollarscript/
        return $upload_path . self::DYNAMIC_CSS_FILENAME;
    }

    /**
     * Get the URL to the dynamic CSS file.
     *
     * @return string
     */
    public static function get_dynamic_css_url(): string {
        $upload_dir = wp_upload_dir(); // Gets an array with 'baseurl', 'basedir', etc.
        // Ensure the baseurl does not have a trailing slash before appending our path and filename
        return rtrim( $upload_dir['baseurl'], '/' ) . '/milliondollarscript/' . self::DYNAMIC_CSS_FILENAME;
    }

    /**
     * Generate and save the dynamic CSS to a file.
     *
     * @return bool True on success, false on failure.
     */
    public static function save_dynamic_css_file(): bool {
        $css_content = self::get_dynamic_css();
        $warning_comment = "/*
 * WARNING: Do not edit this file directly.
 * This file is automatically generated and will be overwritten
 * when plugin options are saved.
 */
";
        $file_content = "{$warning_comment}{$css_content}";
        $filepath = self::get_dynamic_css_filepath();

        return Filesystem::put_contents( $filepath, $file_content );
    }

    /**
     * Generate dynamic CSS styles for MDS pages and login.
     * This method now directly returns the CSS string.
     *
     * @return string The generated CSS.
     */
    public static function get_dynamic_css(): string {
        // Get current theme mode
        $theme_mode = Options::get_option( 'theme_mode', 'light' );
        
        // Get theme-aware CSS variables from Options class
        $theme_variables = Options::get_theme_css_variables();
        $accessible_colors = Options::get_accessible_colors( $theme_mode );
        
        // Legacy color options (for backwards compatibility)
        $primary_color    = Options::get_option( 'primary_color', '#ff0000', true );
        $secondary_color  = Options::get_option( 'secondary_color', '#000000', true );
        $background_color = Options::get_option( 'background_color', '#ffffff', true );
        $text_color       = Options::get_option( 'text_color', '#333333', true );

        // Button styling options (theme-independent)
        $button_tertiary_bg      = Options::get_option( 'button_tertiary_bg', '#F6F7F7', true );
        $button_tertiary_text    = Options::get_option( 'button_tertiary_text_color', '#000000', true );
        $button_border_radius    = Options::get_option( 'button_border_radius', '4', true );

        // Build CSS variables string
        $css_vars = [];
        foreach ( $theme_variables as $property => $value ) {
            $css_vars[] = "    {$property}: {$value};";
        }

        // Add accessible color overrides for current theme
        $css_vars[] = "    --mds-accessible-link: {$accessible_colors['link_color']};";
        $css_vars[] = "    --mds-accessible-success: {$accessible_colors['success_color']};";
        $css_vars[] = "    --mds-accessible-error: {$accessible_colors['error_color']};";
        $css_vars[] = "    --mds-accessible-warning: {$accessible_colors['warning_color']};";

        // Legacy variables for backward compatibility
        $css_vars[] = "    --mds-legacy-primary: {$primary_color};";
        $css_vars[] = "    --mds-legacy-secondary: {$secondary_color};";
        $css_vars[] = "    --mds-legacy-background: {$background_color};";
        $css_vars[] = "    --mds-legacy-text: {$text_color};";

        // Theme-independent button variables
        $css_vars[] = "    --mds-btn-tertiary-bg: {$button_tertiary_bg};";
        $css_vars[] = "    --mds-btn-tertiary-text: {$button_tertiary_text};";
        $css_vars[] = "    --mds-btn-border-radius: {$button_border_radius}px;";

        // Scope variables to the MDS container and the WordPress login page to avoid leaking globals
        $css = "/* MDS Dynamic Theme Variables */\n.mds-container, body.login {\n" . implode( "\n", $css_vars ) . "\n}\n\n";

        // Theme-specific body class application
        $css .= "/* Theme Application */\n";
        $css .= ".mds-container {\n";
        $css .= "    background-color: var(--mds-bg-primary);\n";
        $css .= "    color: var(--mds-text-primary);\n";
        $css .= "}\n\n";

        // Base component styling using CSS variables
        $css .= "/* Base Component Styling */\n";
        $css .= ".mds-container p,\n.mds-container label {\n";
        $css .= "    color: var(--mds-text-primary);\n";
        $css .= "}\n\n";

        $css .= ".mds-container a {\n";
        $css .= "    color: var(--mds-accessible-link);\n";
        $css .= "}\n\n";

        $css .= ".mds-container a:hover {\n";
        $css .= "    color: var(--mds-primary-color);\n";
        $css .= "}\n\n";

        // Input styling
        $css .= "/* Form Input Styling */\n";
        $css .= ".mds-container input[type='text'],\n";
        $css .= ".mds-container input[type='password'],\n";
        $css .= ".mds-container input[type='email'],\n";
        $css .= ".mds-container select,\n";
        $css .= ".mds-container textarea {\n";
        $css .= "    background-color: var(--mds-input-bg);\n";
        $css .= "    border: 1px solid var(--mds-input-border);\n";
        $css .= "    color: var(--mds-text-primary) !important;\n";
        $css .= "}\n\n";

        // Button styling
        $css .= "/* Button Styling */\n";
        $css .= "#loginform input[type=\"submit\"],\n";
        $css .= ".mds-register-link,\n";
        $css .= ".mds-container input[type='button'],\n";
        $css .= ".mds-container input[type='submit'],\n";
        $css .= ".mds-button,\n";
        $css .= "a.mds-button {\n";
        $css .= "    background-color: var(--mds-btn-primary-bg);\n";
        $css .= "    color: var(--mds-btn-primary-text);\n";
        $css .= "    border-radius: var(--mds-btn-border-radius);\n";
        $css .= "    border: none;\n";
        $css .= "}\n\n";

        $css .= "#loginform input[type=\"submit\"]:hover,\n";
        $css .= ".mds-register-link:hover,\n";
        $css .= ".mds-container input[type='button']:hover,\n";
        $css .= ".mds-container input[type='submit']:hover,\n";
        $css .= ".mds-button:hover,\n";
        $css .= "a.mds-button:hover {\n";
        $css .= "    background-color: var(--mds-btn-primary-hover-bg, #005a87);\n";
        $css .= "    color: var(--mds-btn-primary-text);\n";
        $css .= "}\n\n";

        $css .= "/* Register Button Specific Styling */\n";
        $css .= ".wp-core-ui .button-register,\n";
        $css .= ".wp-core-ui input[type=\"submit\"].button-register,\n";
        $css .= ".login .mds-register-link {\n";
        $css .= "    background-color: var(--mds-btn-secondary-bg);\n";
        $css .= "    color: var(--mds-btn-secondary-text);\n";
        $css .= "    border: 1px solid var(--mds-border-color);\n";
        $css .= "    text-decoration: none;\n";
        $css .= "    display: inline-block;\n";
        $css .= "    padding: 8px 16px;\n";
        $css .= "    border-radius: var(--mds-btn-border-radius);\n";
        $css .= "}\n\n";

        $css .= ".wp-core-ui .button-register:hover,\n";
        $css .= ".wp-core-ui input[type=\"submit\"].button-register:hover,\n";
        $css .= ".login .mds-register-link:hover {\n";
        $css .= "    background-color: var(--mds-btn-secondary-hover-bg, var(--mds-bg-tertiary));\n";
        $css .= "    color: var(--mds-btn-secondary-hover-text, var(--mds-text-primary));\n";
        $css .= "    border-color: var(--mds-btn-primary-bg);\n";
        $css .= "}\n\n";

        $css .= ".mds-button-secondary {\n";
        $css .= "    background-color: var(--mds-btn-secondary-bg);\n";
        $css .= "    color: var(--mds-btn-secondary-text);\n";
        $css .= "}\n\n";
        $css .= ".mds-button.mds-success,\n";
        $css .= ".mds-container input[type='button'].mds-confirm,\n";
        $css .= ".mds-container input[type='button'].mds-upload,\n";
        $css .= ".mds-container input[type='button'].mds-write,\n";
        $css .= ".mds-container input[type='button'].mds-pay,\n";
        $css .= ".mds-container input[type='button'].mds-continue,\n";
        $css .= ".mds-container input[type='submit'].mds-complete,\n";
        $css .= ".mds-container #submit_button1,\n";
        $css .= ".mds-container #submit_button2 {\n";
        $css .= "    background-color: var(--mds-btn-success-bg);\n";
        $css .= "    color: var(--mds-btn-success-text);\n";
        $css .= "}\n\n";

        $css .= ".mds-button.mds-success:hover,\n";
        $css .= ".mds-container input[type='button'].mds-confirm:hover,\n";
        $css .= ".mds-container input[type='button'].mds-upload:hover,\n";
        $css .= ".mds-container input[type='button'].mds-write:hover,\n";
        $css .= ".mds-container input[type='button'].mds-pay:hover,\n";
        $css .= ".mds-container input[type='button'].mds-continue:hover,\n";
        $css .= ".mds-container input[type='submit'].mds-complete:hover,\n";
        $css .= ".mds-container #submit_button1:hover,\n";
        $css .= ".mds-container #submit_button2:hover {\n";
        $css .= "    filter: brightness(1.1);\n";
        $css .= "}\n\n";

        $css .= ".mds-button.mds-danger,\n";
        $css .= ".mds-container #reset_button {\n";
        $css .= "    background-color: var(--mds-btn-danger-bg);\n";
        $css .= "    color: var(--mds-btn-danger-text);\n";
        $css .= "}\n\n";

        // Message styling
        $css .= "/* Message & Alert Styling */\n";
        $css .= ".mds-success-message {\n";
        $css .= "    background-color: " . ( $theme_mode === 'dark' ? 'rgba(74, 222, 128, 0.1)' : '#DFF2BF' ) . ";\n";
        $css .= "    color: var(--mds-accessible-success);\n";
        $css .= "    border: 1px solid var(--mds-accessible-success);\n";
        $css .= "}\n\n";

        $css .= ".mds-error-message {\n";
        $css .= "    background-color: " . ( $theme_mode === 'dark' ? 'rgba(248, 113, 113, 0.1)' : '#FFE6E6' ) . ";\n";
        $css .= "    color: var(--mds-accessible-error);\n";
        $css .= "    border: 1px solid var(--mds-accessible-error);\n";
        $css .= "}\n\n";

        $css .= ".mds-caution-message {\n";
        $css .= "    background-color: " . ( $theme_mode === 'dark' ? 'rgba(251, 191, 36, 0.1)' : '#FFF3CD' ) . ";\n";
        $css .= "    color: var(--mds-accessible-warning);\n";
        $css .= "    border: 1px solid var(--mds-accessible-warning);\n";
        $css .= "}\n\n";

        $css .= ".mds-info-message {\n";
        $css .= "    background-color: " . ( $theme_mode === 'dark' ? 'rgba(59, 130, 246, 0.1)' : '#d1e9ff' ) . ";\n";
        $css .= "    color: var(--mds-accessible-link);\n";
        $css .= "    border: 1px solid var(--mds-accessible-link);\n";
        $css .= "}\n\n";

        // Menu and navigation styling
        $css .= "/* Menu & Navigation Styling */\n";
        $css .= ".mds-container .menu-bar,\n";
        $css .= ".mds-container .users-menu-bar,\n";
        $css .= ".mds-users-menu {\n";
        $css .= "    background-color: var(--mds-menu-bg);\n";
        $css .= "}\n\n";

        $css .= ".mds-container .users-menu-bar a {\n";
        $css .= "    color: var(--mds-menu-text);\n";
        $css .= "}\n\n";

        $css .= ".mds-container .users-menu-bar a:hover {\n";
        $css .= "    background-color: var(--mds-menu-hover-bg);\n";
        $css .= "    color: var(--mds-text-primary);\n";
        $css .= "}\n\n";

        // Card and container styling
        $css .= "/* Card & Container Styling */\n";
        $css .= ".mds-container .heading,\n";
        $css .= ".stats-container .status,\n";
        $css .= ".mds-order-details .mds-order-details-section,\n";
        $css .= "#loginform {\n";
        $css .= "    background-color: var(--mds-card-bg);\n";
        $css .= "    color: var(--mds-text-primary);\n";
        $css .= "}\n\n";

        $css .= ".stats-container .status {\n";
        $css .= "    border: 1px solid var(--mds-border-color);\n";
        $css .= "}\n\n";

        // Table styling
        $css .= "/* Table Styling */\n";
        $css .= ".mds-container table th {\n";
        $css .= "    background-color: var(--mds-bg-secondary);\n";
        $css .= "    color: var(--mds-text-primary);\n";
        $css .= "}\n\n";

        $css .= ".mds-container .table-row.header {\n";
        $css .= "    background-color: var(--mds-bg-secondary);\n";
        $css .= "    color: var(--mds-text-primary);\n";
        $css .= "}\n\n";

        // Dark mode specific overrides
        if ( $theme_mode === 'dark' ) {
            $css .= "/* Dark Mode Specific Overrides */\n";
            $css .= ".mds-container .select-input {\n";
            $css .= "    background-color: var(--mds-bg-secondary);\n";
            $css .= "    color: var(--mds-text-primary);\n";
            $css .= "    box-shadow: 0 0 5px var(--mds-shadow);\n";
            $css .= "}\n\n";

            $css .= ".mds-pixel-info-container {\n";
            $css .= "    background-color: var(--mds-bg-secondary);\n";
            $css .= "    box-shadow: 0 2px 8px var(--mds-shadow);\n";
            $css .= "}\n\n";

            $css .= ".mds-pixel-info-block {\n";
            $css .= "    background-color: var(--mds-bg-tertiary);\n";
            $css .= "}\n\n";

            // Navigation dark mode styling
            $css .= ".mds-navigation a, .mds-navigation span {\n";
            $css .= "    color: var(--mds-text-primary);\n";
            $css .= "    border: 1px solid var(--mds-border-color);\n";
            $css .= "    background-color: var(--mds-bg-secondary);\n";
            $css .= "}\n\n";

            $css .= ".mds-navigation a:hover {\n";
            $css .= "    background-color: var(--mds-bg-tertiary);\n";
            $css .= "    border-color: var(--mds-primary-color);\n";
            $css .= "}\n\n";

            $css .= ".mds-navigation span {\n";
            $css .= "    background-color: var(--mds-primary-color);\n";
            $css .= "    border-color: var(--mds-primary-color);\n";
            $css .= "}\n\n";
        }

        // Allow filtering of the CSS
        $css = apply_filters( 'mds_dynamic_css', $css );

        return trim( $css );
    }

    /**
     * Enqueue dynamic CSS file after the core or login stylesheet.
     * 
     * Note: With the new page system using WordPress pages + shortcodes,
     * we need to be more permissive about loading the dynamic CSS to ensure
     * dark mode works properly across all MDS pages.
     */
    public static function enqueue_dynamic_styles(): void {
        if ( is_admin() ) {
            return;
        }

        global $pagenow;
        $is_login_page = 'wp-login.php' === $pagenow;
        
        // Load CSS on all frontend pages to ensure dark mode works across WordPress pages with shortcodes
        // This covers shortcode pages, direct MDS pages, and any other potential MDS content
        // The CSS is small and only applies to elements with MDS classes anyway

        $css_filepath = self::get_dynamic_css_filepath();

        if ( ! Filesystem::file_exists( $css_filepath ) ) {
            // Attempt to generate it if it doesn't exist, as a fallback.
            // This is useful for initial activation or if the file was somehow deleted.
            if ( ! self::save_dynamic_css_file() ) {
                // Log error or notify admin if file can't be created/found
                return; // Can't enqueue if file doesn't exist and can't be created
            }
        }

        $handle = 'mds-dynamic-styles';
        $src = self::get_dynamic_css_url();
        $deps = $is_login_page ? [ 'login' ] : [ 'mds' ];
        $version = filemtime( $css_filepath );

        wp_enqueue_style( $handle, $src, $deps, $version );
    }

    /**
     * Get theme-aware body classes for frontend
     *
     * @return array Array of body classes
     */
    public static function get_theme_body_classes(): array {
        $theme_mode = Options::get_option( 'theme_mode', 'light' );

        // Default: do not add any MDS classes to <body> to prevent style leakage.
        // If a site explicitly opts in, re-enable legacy behavior via filter.
        $enable_legacy = apply_filters( 'mds_enable_legacy_body_classes', false );

        if ( $enable_legacy ) {
            return [
                'mds-container',
                "mds-theme-{$theme_mode}",
                'mds-theme-active',
            ];
        }

        // No body classes by default.
        return [];
    }

    /**
     * Add theme classes to body class
     *
     * @param array $classes Existing body classes
     * @return array Modified body classes
     */
    public static function add_theme_body_classes( array $classes ): array {
        // Only add theme classes on MDS pages
        if ( Utility::is_mds_page() ) {
            $theme_classes = self::get_theme_body_classes();
            $classes = array_merge( $classes, $theme_classes );
        }
        
        return $classes;
    }

    /**
     * Initialize theme body class hooks
     */
    public static function init_theme_hooks(): void {
        // Add theme body classes to frontend
        add_filter( 'body_class', [ self::class, 'add_theme_body_classes' ] );
        
        // Add theme classes to admin body (for admin pages)
        add_filter( 'admin_body_class', [ self::class, 'get_admin_theme_classes' ] );
    }

    /**
     * Get admin theme classes
     *
     * @param string $classes Existing admin body classes
     * @return string Modified admin body classes
     */
    public static function get_admin_theme_classes( string $classes ): string {
        $theme_mode = Options::get_option( 'theme_mode', 'light' );
        
        // Add theme class to admin for MDS pages
        if ( isset( $_GET['page'] ) && strpos( $_GET['page'], 'mds-' ) === 0 ) {
            $classes .= " mds-admin-theme-{$theme_mode}";
        }
        
        return $classes;
    }
}