<?php

class html
{
    public function __construct()
    {
        ?>
        <html>

        <head>
            <meta charset="UTF-8">
            <title>Unleashed K9 Solutions</title>
            <link rel="stylesheet" type="text/css" href="styles/styles.css?v=<?php echo rand(0, 10000); ?>">
        </head>

        <body>
            <?php
    }

    public function bacground_emoji()
    {
        ?>
            <div id="emoji-background"></div>
            <script>
                const emojis = [
                    // Dogs
                    '🐶', '🐕', '🦮', '🐕‍🦺', '🐩', '🐾',

                    // Balls & Toys
                    '🎾', '⚽', '🥎',

                    // Bonus Dog Park Things
                    '🦴', '🪵', '🌳', '🌲', '💩', '🍖', '🦴',

                    // Funny extras (if you want humor/whimsy)
                    '🐿️', '🐥'
                ];
                const emojiContainer = document.getElementById('emoji-background');

                function createEmoji() {
                    const emoji = document.createElement('div');
                    emoji.classList.add('floating-emoji');
                    emoji.innerText = emojis[Math.floor(Math.random() * emojis.length)];

                    // Random horizontal position
                    const left = Math.random() * 100; // in vw
                    emoji.style.left = `${left}vw`;

                    // Random size
                    const size = Math.random() * 4.5 + 0.5; // rem
                    emoji.style.fontSize = `${size}rem`;

                    // Random animation duration and delay
                    const duration = Math.random() * 4 + 4; // 4s to 8s
                    const delay = Math.random() * 2; // 0–2s

                    emoji.style.animationDuration = `${duration}s`;
                    emoji.style.animationDelay = `${delay}s`;
                    emoji.style.opacity = 0;

                    // Random horizontal wiggle using translateX
                    const initialX = Math.random() * 40 - 20; // -20px to 20px
                    emoji.style.transform = `translateX(${initialX}px)`;

                    emojiContainer.appendChild(emoji);

                    // Remove after animation
                    setTimeout(() => {
                        emoji.remove();
                    }, (duration + delay) * 1000);
                }

                // 👇 Burst of emojis at page load
                function preloadEmojis(count = 20) {
                    for (let i = 0; i < count; i++) {
                        createEmoji();
                    }
                }

                // 👇 Continuous emoji loop
                function spawnLoop() {
                    createEmoji();
                    const interval = Math.random() * 300 + 200;
                    setTimeout(spawnLoop, interval);
                }

                // Fire both on page load
                window.addEventListener('DOMContentLoaded', () => {
                    preloadEmojis(10); // burst to avoid blank screen
                    spawnLoop();       // then continue looping
                });
            </script>


            <?php

    }



    public function html_end()
    {
        ?>
        </body>

        </html>
        <?php
    }
}
class loading
{

    public function asset_loading_page($assers_array = [], $message = '', $redirect_page = '')
    {
        ?>


        <div class="loader-container">
            <h1><br> <?php echo $message; ?>.</h1>
            <div class="progress-bar-bg">
                <div class="progress-bar-fill" id="progressBar"></div>
            </div>
            <div class="percentage" id="percentageText">0%</div>
        </div>

        <script>
            const assets = [
                <?php
                foreach ($assers_array as $asset) {
                    echo "'$asset',";
                }
                ?>
            ];

            let loaded = 0;

            function updateProgress() {
                loaded++;
                const percent = Math.floor((loaded / assets.length) * 100);
                document.getElementById("percentageText").innerText = percent + "%";
                document.getElementById("progressBar").style.width = percent + "%";

                if (loaded === assets.length) {
                    // All assets loaded
                    setTimeout(() => {
                        if ("<?php echo $redirect_page; ?>" !== "") {
                            window.location.href = "<?php echo $redirect_page; ?>";
                        }
                    }, 500); // small delay to show 100%
                }
            }

            function preloadAsset(url) {
                return new Promise((resolve) => {
                    if (url.endsWith(".mp4")) {
                        const video = document.createElement("video");
                        video.src = url;
                        video.preload = "auto";
                        video.muted = true; // Important for iOS
                        video.setAttribute("playsinline", "true"); // iOS fix
                        video.style.display = "none"; // hide from view
                        document.body.appendChild(video); // <-- Append to DOM

                        video.oncanplaythrough = () => {
                            updateProgress();
                            resolve();
                            video.remove(); // clean up
                        };

                        // Fallback: if oncanplaythrough doesn't fire
                        setTimeout(() => {
                            updateProgress();
                            resolve();
                            video.remove();
                        }, 5000); // max wait
                    } else {
                        const img = new Image();
                        img.src = url;
                        img.onload = () => {
                            updateProgress();
                            resolve();
                        };
                    }
                });
            }


            Promise.all(assets.map(preloadAsset));
        </script>

        <?php
    }


    public function background_video_with_preloader($message = "Hold tight — we're preparing your tail-wagging schedule!", $videoFiles = [])
    {
        // Ensure videoFiles is an array and not empty
        if (!is_array($videoFiles) || empty($videoFiles)) {
            // Fallback or error handling if no video files are provided
            echo '<div style="background-color: #333; width: 100vw; height: 100vh; position: fixed; top: 0; left: 0; z-index: -2;"></div>';
            echo '<script>console.warn("No video files provided for background_video_with_preloader.");</script>';
            return;
        }
        ?>

        <style>
            .loader-overlay {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.85);
                /* Darker overlay */
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 9999;
                transition: opacity 0.6s ease-out;
                color: #fff;
                text-align: center;
                flex-direction: column;
                gap: 20px;
            }

            .loader-content h1 {
                font-size: 2em;
                margin-bottom: 20px;
            }

            .progress-bar-bg {
                width: 80%;
                max-width: 400px;
                height: 10px;
                background-color: #555;
                border-radius: 5px;
                overflow: hidden;
                margin-bottom: 10px;
            }

            .progress-bar-fill {
                height: 100%;
                width: 0%;
                background-color: #007bff;
                /* Blue progress bar */
                border-radius: 5px;
                transition: width 0.1s linear;
            }

            .percentage {
                font-size: 1.2em;
            }

            #bg-video-container {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                z-index: -1;
                /* Background */
                overflow: hidden;
                background-color: #000;
                /* Fallback background */
            }

            .bg-video {
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                object-fit: cover;
                opacity: 0;
                /* Hidden by default, controlled by JS */
                transition: opacity 1.5s ease;
            }
        </style>

        <div id="video-loader" class="loader-overlay">
            <div class="loader-content">
                <h1><?php echo $message; ?></h1>
                <div class="progress-bar-bg">
                    <div class="progress-bar-fill" id="progressFill"></div>
                </div>
                <div class="percentage" id="progressText">0%</div>
            </div>
        </div>

        <div id="bg-video-container">
        </div>

        <script>
            document.addEventListener("DOMContentLoaded", () => {
                const videoSources = <?php echo json_encode($videoFiles); ?>;
                const loader = document.getElementById("video-loader");
                const progressFill = document.getElementById("progressFill");
                const progressText = document.getElementById("progressText");
                const videoContainer = document.getElementById("bg-video-container");

                let currentVideoElement = null; // Currently playing video element
                let nextVideoElement = null; // Next video element to load
                let currentIndex = -1; // Index of the currently playing video source
                let videoElements = []; // Store the two video elements (for A/B switching)

                // Create two persistent video elements for seamless transitions
                for (let i = 0; i < 2; i++) {
                    const video = document.createElement("video");
                    video.className = "bg-video";
                    video.muted = true;
                    video.autoplay = true;
                    video.playsInline = true;
                    video.preload = "auto"; // 'auto' is generally good for background videos
                    videoContainer.appendChild(video);
                    videoElements.push(video);
                }

                // Initially, videoElements[0] will be the first active one
                currentVideoElement = videoElements[0];
                nextVideoElement = videoElements[1];

                function updateProgress(val) {
                    progressFill.style.width = val + "%";
                    progressText.innerText = val + "%";
                }

                function preloadVideo(url) {
                    return new Promise((resolve, reject) => {
                        const tempVideo = document.createElement("video");
                        tempVideo.src = url;
                        tempVideo.preload = "auto";
                        tempVideo.muted = true;
                        tempVideo.playsInline = true; // Crucial for iOS preloading and autoplay
                        tempVideo.autoplay = false; // Don't autoplay temp video

                        // Use oncanplaythrough for more reliable "ready" state
                        tempVideo.oncanplaythrough = () => {
                            resolve();
                            tempVideo.remove(); // Clean up the temporary element
                        };

                        // Handle errors during preloading (e.g., file not found)
                        tempVideo.onerror = (e) => {
                            console.error(`Error preloading video ${url}:`, e);
                            resolve(); // Resolve even on error to not block the preloader
                            tempVideo.remove();
                        };

                        // Fallback timeout in case oncanplaythrough doesn't fire
                        setTimeout(() => {
                            console.warn(`Preload timeout for video: ${url}`);
                            resolve();
                            tempVideo.remove();
                        }, 10000); // 10 seconds timeout
                    });
                }

                // Preload all videos
                Promise.all(videoSources.map((src, i) =>
                    preloadVideo(src).then(() =>
                        updateProgress(Math.floor(((i + 1) / videoSources.length) * 100))
                    )
                )).then(() => {
                    // Preloading complete, fade out loader and start video
                    loader.style.opacity = 0;
                    setTimeout(() => {
                        loader.style.display = "none";
                        initializeVideoPlayback();
                    }, 600);
                }).catch(error => {
                    console.error("Error during video preloading:", error);
                    // If preloading fails, still hide loader and try to play what's available
                    loader.style.opacity = 0;
                    setTimeout(() => {
                        loader.style.display = "none";
                        initializeVideoPlayback();
                    }, 600);
                });

                function getNextIndex() {
                    let next;
                    if (videoSources.length <= 1) {
                        return 0; // If only one video, always return 0
                    }
                    do {
                        next = Math.floor(Math.random() * videoSources.length);
                    } while (next === currentIndex);
                    currentIndex = next;
                    return next;
                }

                function playVideo(videoElement, sourceIndex) {
                    videoElement.src = videoSources[sourceIndex];
                    videoElement.currentTime = 0; // Ensure playback starts from beginning

                    return new Promise((resolve, reject) => {
                        // Set oncanplaythrough before loading to ensure event fires
                        videoElement.oncanplaythrough = () => {
                            console.log(`Video ${sourceIndex} can play through.`);
                            // Attempt to play
                            videoElement.play()
                                .then(() => {
                                    console.log(`Video ${sourceIndex} started playing.`);
                                    resolve();
                                })
                                .catch(err => {
                                    console.warn(`Autoplay blocked for video ${sourceIndex}:`, err.name, err.message);
                                    // On iOS, if autoplay is blocked, we still want to resolve
                                    // and potentially allow a user interaction to start it.
                                    resolve(); // Resolve even if autoplay blocked, to proceed
                                });
                            videoElement.oncanplaythrough = null; // Remove handler
                        };

                        videoElement.onerror = (e) => {
                            console.error(`Error loading or playing video ${sourceIndex}:`, e);
                            reject(e); // Reject the promise on error
                            videoElement.onerror = null; // Remove handler
                        };

                        videoElement.load(); // Start loading the video
                    });
                }

                function initializeVideoPlayback() {
                    const initialIndex = getNextIndex();
                    playVideo(currentVideoElement, initialIndex)
                        .then(() => {
                            currentVideoElement.style.opacity = 1; // Show the first video

                            // Set up the ending listener for the current video
                            currentVideoElement.onended = () => {
                                console.log(`Video ${currentIndex} ended. Transitioning.`);
                                startNextVideoTransition();
                            };

                            // If video doesn't play (e.g., iOS autoplay blocked), try a fallback
                            // This timeout will ensure the transition happens even if 'onended'
                            // doesn't fire due to non-playback.
                            // However, for iOS, a user interaction is usually key.
                            setTimeout(() => {
                                if (currentVideoElement.paused && currentVideoElement.currentTime < 1) {
                                    console.warn("Video did not auto-play. Consider adding a user interaction prompt.");
                                    // Optionally, show a "Tap to play" message here.
                                    // For now, we'll just ensure the loop continues if possible
                                    // without user interaction for the first play.
                                    // The loop attribute for the first video helps here.
                                }
                            }, 3000); // Wait 3 seconds after play attempt

                        })
                        .catch(err => {
                            console.error("Failed to initialize first video playback:", err);
                            // Fallback to static background or a message
                            videoContainer.style.backgroundColor = "#000";
                        });

                    // For a single video, just loop it.
                    if (videoSources.length === 1) {
                        currentVideoElement.loop = true;
                    }
                }


                function startNextVideoTransition() {
                    const nextIndex = getNextIndex();

                    // Swap current and next video elements
                    const temp = currentVideoElement;
                    currentVideoElement = nextVideoElement;
                    nextVideoElement = temp;

                    // Load and prepare the new next video
                    playVideo(currentVideoElement, nextIndex)
                        .then(() => {
                            // Once the next video is ready to play, start the fade
                            currentVideoElement.style.opacity = 1; // Fade in new video
                            nextVideoElement.style.opacity = 0; // Fade out old video

                            // Set onended listener for the newly active video
                            currentVideoElement.onended = () => {
                                console.log(`Video ${currentIndex} ended. Transitioning.`);
                                startNextVideoTransition();
                            };

                            // Ensure the old video's onended is cleared
                            nextVideoElement.onended = null;
                            nextVideoElement.pause(); // Pause the old video after transition
                            nextVideoElement.src = ''; // Clear source to free resources
                        })
                        .catch(err => {
                            console.error(`Error during transition to video ${nextIndex}:`, err);
                            // If transition fails, try to continue the loop or show fallback
                            currentVideoElement.style.opacity = 0; // Hide broken video
                            nextVideoElement.style.opacity = 1; // Keep old one if possible
                            // Or, just set a static background
                            videoContainer.style.backgroundColor = "#000";
                        });
                }

                // --- iOS Specific Autoplay Fix Attempt ---
                // This is a common workaround for iOS.
                // It tries to play the video on the first 'touchend' event.
                // You might want to display a "Tap to start" message if autoplay fails.

                let hasInteracted = false;
                document.addEventListener('touchend', function forceVideoPlay() {
                    if (hasInteracted) return; // Only run once
                    hasInteracted = true;

                    // Attempt to play the currently active video
                    if (currentVideoElement && currentVideoElement.paused) {
                        currentVideoElement.play().then(() => {
                            console.log("Video resumed by user interaction.");
                            document.removeEventListener('touchend', forceVideoPlay); // Remove listener
                        }).catch(e => {
                            console.warn("User interaction play failed:", e);
                        });
                    }
                }, { once: true }); // Use { once: true } for modern browsers
                // For older browsers, manually removeEventListener as above.
            });
        </script>
        <?php
    }

}

class input
{

    public $type;
    public $name;
    public $value;
    public $id;
    public $class;
    public $placeholder = "";
    public $required = "";
    public $disabled = "";
    public $checked = "";

    public $width = "100%";
    public $height = "auto";

    function type($type = 'text')
    {
        $this->type = $type;
    }

    function name($name)
    {
        $this->name = $name;
    }

    function value($value)
    {
        $this->value = $value;
    }

    function id($id)
    {
        $this->id = $id;
    }
    function width($width)
    {
        $this->width = $width;
    }
    function height($height)
    {
        $this->height = $height;
    }
    function class($class = 'input')
    {
        $this->class = $class;
    }

    function placeholder($placeholder)
    {
        $this->placeholder = $placeholder;
    }

    function required()
    {
        $this->required = "required";
    }

    function disabled()
    {
        $this->disabled = "disabled";
    }

    function checked()
    {
        $this->checked = "checked";
    }

    function add()
    {
        echo "<input type='$this->type' name='$this->name' style='width:$this->width;height:$this->height' value='$this->value' id='$this->id' class='$this->class' placeholder='$this->placeholder' $this->required $this->disabled $this->checked>";
    }

}

class button
{

    public $name;
    public $width;
    public $height;
    public $value;
    public $id;
    public $class = "button";
    public $type = "button";
    public $style = "";

    function name($name)
    {
        $this->name = $name;
    }

    function width($width)
    {
        $this->width = $width;
    }
    function height($height)
    {
        $this->height = $height;
    }
    function value($value)
    {
        $this->value = $value;
    }

    function id($id)
    {
        $this->id = $id;
    }

    function class($class)
    {
        $this->class = $class;
    }

    function type($type)
    {
        $this->type = $type;
    }

    function style($style)
    {
        $this->style = $style;
    }

    function add()
    {
        echo "<button type='$this->type' name='$this->name' style='width:$this->width;height:$this->height' value='$this->value' id='$this->id' class='$this->class' style='$this->style'>$this->value</button>";
    }

}
