<?php
include "classes/class.loader.php";
$html = new html();
$html->bacground_emoji();
$calls = new functions();
$db = new db();
$html->header();
if (!isset($_SESSION['user_id'])) {
    echo "<script>window.location.href='login.php';</script>";
}
?>
<style>
    body {
        background-color: #bebebee7;
        color: white;
    }
</style>

<div class="whatsapp-label">HELP</div>

<!-- Floating button -->
<a class="whatsapp-float" id="whatsappBtn" title="Message us on WhatsApp" target="_blank" rel="noopener noreferrer"
    href="#" aria-label="Open WhatsApp chat">
    <!-- WhatsApp SVG icon (official-looking) -->
    <svg viewBox="0 0 24 24" fill="none" aria-hidden="true" xmlns="http://www.w3.org/2000/svg">
        <path
            d="M20.52 3.48A11.9 11.9 0 0 0 12 0C5.373 0 .003 5.373.003 12 0 13.987.44 15.9 1.27 17.6L0 24l6.66-1.76a11.94 11.94 0 0 0 5.34 1.38h.01c6.627 0 12-5.373 12-12 0-3.19-1.24-6.18-3.48-8.04z"
            fill="#25D366" />
        <path
            d="M17.56 14.1c-.32-.16-1.9-.94-2.2-1.04-.3-.11-.52-.16-.74.16-.22.32-.86 1.04-1.06 1.25-.19.19-.39.21-.72.07-.32-.13-1.37-.51-2.61-1.62-.97-.86-1.62-1.92-1.81-2.24-.19-.32-.02-.49.14-.65.14-.14.32-.36.48-.54.16-.19.21-.32.32-.53.11-.21.05-.39-.03-.55-.08-.16-.74-1.78-1.02-2.44-.27-.64-.55-.55-.74-.56-.19-.01-.41-.01-.63-.01-.22 0-.58.08-.88.39-.3.31-1.15 1.12-1.15 2.73 0 1.6 1.18 3.14 1.34 3.36.16.22 2.32 3.66 5.62 5.12 3.3 1.46 3.3 0.97 3.9 0.91.6-.07 1.92-.78 2.19-1.53.27-.74.27-1.38.19-1.53-.08-.15-.3-.24-.62-.4z"
            fill="#fff" />
    </svg>
</a>

<script>
    // PHONE: user-provided local number (0645010642).
    // For reliable behaviour with wa.me we convert to international format.
    // South Africa country code = 27; remove leading zero from the local number.
    const localNumber = "0645010642";
    const intlNumber = localNumber.replace(/^0+/, ""); // removes leading zero(s)
    // If your country is South Africa, add 27 before the number:
    const countryCode = "27";
    const phoneForWA = countryCode + intlNumber; // -> "27645010642"

    // Prefilled message (exact text provided by user)
    const msg = "Good day Team, Please help with the following:";

    // Build links: prefer whatsapp:// for mobile apps, fallback to https://wa.me/ for web/mobile
    const encodedMsg = encodeURIComponent(msg);
    const waAppLink = "whatsapp://send?phone=" + phoneForWA + "&text=" + encodedMsg;
    const waWebLink = "https://wa.me/" + phoneForWA + "?text=" + encodedMsg;

    // Use web link by default (works on desktop & mobile); on some mobile browsers whatsapp:// may work.
    const anchor = document.getElementById("whatsappBtn");

    // Attempt to open app link on mobile — but final href will be web fallback.
    // We'll set href to web link so it also works in desktop browsers.
    anchor.href = waWebLink;

    // Optional: on mobile, try to open the app first then fallback to web.
    // (We do this by attempting to navigate to app scheme for short time.)
    function openWhatsAppPreferApp(e) {
        // On touch devices, try app; on desktop, just open web
        const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        if (!isMobile) return; // let default anchor behavior open new tab

        e.preventDefault();
        // Try app scheme
        const appUrl = waAppLink;
        const webUrl = waWebLink;

        // Create invisible iframe to try app URL (older technique)
        const start = Date.now();
        let didOpen = false;

        // For modern browsers, direct location change is OK.
        window.location = appUrl;

        // After short delay, navigate to web link (works as fallback)
        setTimeout(function () {
            // If still on the page, open web link
            // We guard to avoid double navigation in some environments
            if (Date.now() - start < 2000) {
                window.location = webUrl;
            }
        }, 1500);
    }

    // Use the mobile-prefer behavior on click
    anchor.addEventListener("click", openWhatsAppPreferApp, { passive: false });
</script>
<form action="book.php" method="post" id="form">
    <input type="text" name="booking_type" value="PARK" hidden />
    <div class="home_container">
        <div class="container_wide" id="dogs_container">
            <h1>SELECT THE DOGS YOU WISH TO GO TO THE PARK WITH:</h1>
            <div class="line"></div>
            <h3>CLICK TO SELECT</h3>
            <div class="data_container_for_adding">
                <?php
                $dog_res = $db->query("SELECT * FROM user_animals WHERE user_id = {$_SESSION['user_id']}");
                if ($dog_res->num_rows > 0) {
                    while ($dog = $dog_res->fetch_assoc()) {
                        ?>
                        <div class="dogs_data_row" onclick="select_unselect(this,'dog_<?php echo $dog['record_id']; ?>')">
                            <div class="dogs_data_row_number">
                                <input type="text" value="0" hidden name="selected_dogs[]"
                                    id="dog_<?php echo $dog['record_id']; ?>" />
                                <input type="text" name="dog_id[]" value="<?php echo $dog['record_id']; ?>" hidden />
                                <label id="dog_form">NAME</label>
                                <input type="text" id="name" <?php if ($dog['name'] != '') {
                                    echo 'readonly';
                                } ?>
                                    onchange="change_dog_info(this, 'user_animals', '<?php echo $dog['record_id']; ?>')"
                                    name="name" value="<?php echo @$dog['name']; ?>" />
                                <label>BREED</label>
                                <input type="text" id="breed" <?php if ($dog['name'] != '') {
                                    echo 'readonly';
                                } ?>
                                    onchange="change_dog_info(this, 'user_animals', '<?php echo $dog['record_id']; ?>')"
                                    name="breed" value="<?php echo @$dog['breed']; ?>" />
                            </div>
                        </div>
                    <?php }
                } else {
                    echo "<h2>NO DOGS ADDED YET</h2>";
                }
                ?>
            </div>
            <br>
            <button onclick="add_row_dogs()">ADD NEW DOG</button>
            <script>
                function select_unselect(button, input) {
                    input = document.getElementById(input);
                    if (input.value == 0) {
                        input.value = 1;
                        button.style.backgroundColor = "green";
                    } else {
                        input.value = 0;
                        button.style.backgroundColor = "#5c5c5c";
                    }
                }
                function add_row_dogs() {
                    event.preventDefault();
                    if (event.keyCode === 13) {
                        event.preventDefault();
                        return;
                    }
                    if (event.keyCode === 13) {
                        return;
                    }
                    if (event.target.tagName === "BUTTON") {
                        var xhr = new XMLHttpRequest();
                        xhr.open('POST', 'ajax/add_new_dog.php', true);
                        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === XMLHttpRequest.DONE) {
                                if (xhr.status === 200) {
                                    console.log(xhr.responseText);
                                    if (xhr.responseText == 1) {
                                        window.location.assign("profile.php#dogs_container");
                                        window.location.reload();
                                    } else if (xhr.responseText == 2) {
                                        alert("PLEASE FILL IN THE NEW DOGS INFORMATION");
                                        document.getElementById("dog_form").focus();

                                    } else {
                                        alert("SOMETHING WENT WRONG");

                                    }
                                }
                            }
                        };
                        xhr.send();
                    }
                }
                function change_dog_info(input, table_name, dog_id) {
                    var value = input.value;
                    var column = input.id;
                    var where = "user_id = <?php echo $_SESSION['user_id']; ?> AND record_id = " + dog_id;

                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', 'ajax/database_update_inputs.php', true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === XMLHttpRequest.DONE) {
                            if (xhr.status === 200) {
                                console.log(xhr.responseText);
                                if (xhr.responseText === '1') {
                                    input.style.border = "2px solid green";
                                } else {
                                    input.style.border = "2px solid red";

                                }
                            }
                        }
                    };
                    xhr.send('value=' + encodeURIComponent(value) + '&column=' + encodeURIComponent(column) + '&table_name=' + encodeURIComponent(table_name) + '&where=' + encodeURIComponent(where));
                }

                document.addEventListener("keypress", function (event) {
                    if (event.keyCode === 13) {
                        event.preventDefault();
                    }
                });

            </script>



        </div>
        <div class="container_wide" id="calendar_container">
            <h2>SELECT THE DATES YOU WISH TO TRAIN WITH:</h2>
            <div class="data_container_for_adding">
                <?php
                for ($i = 1; $i < 30; $i++) {
                    $date = new DateTime();
                    $date->add(new DateInterval('P' . $i . 'D'));
                    ?>
                    <div class="booking_time_date_row" id="date_<?php echo $date->format('Y-m-d'); ?>"
                        style="overflow:hidden;">
                        <a onclick="show_hide('date_<?php echo $date->format('Y-m-d'); ?>')">
                            <?php echo $date->format('Y M jS'); ?></a>
                        <?php
                        $booked_index = 0;
                        for ($time = 9; $time < 17; $time++) {
                            $booking_check_res = $db->query("SELECT * FROM bookings WHERE date_of_booking = '" . $date->format('Y-m-d') . "' AND time_start <= " . $time . " AND time_end >= " . ($time + 1) . " AND (`status` != 3)");
                            if ($booking_check_res->num_rows == 0) {
                                $time_slot = $time . ':00';
                                ?>
                                <div class="booking_time_row"
                                    onclick="select_slot(this, 'selected_<?php echo $date->format('Y-m-d') . '_' . $time_slot . '-' . ($time + 1) . ':00'; ?>')">
                                    <p><?php echo $time_slot . ' - ' . ($time + 1) . ':00'; ?></p>
                                    <input hidden type="text" name="booking_slot[]"
                                        value="<?php echo $date->format('Y-m-d') . '_' . $time_slot . '-' . ($time + 1) . ':00' ?>" />
                                    <input type="text" hidden name="selected[]" value="0"
                                        id="selected_<?php echo $date->format('Y-m-d') . '_' . $time_slot . '-' . ($time + 1) . ':00'; ?>" />
                                </div>
                                <?php
                            } else {
                                $booked_index++;
                            }
                        }
                        ?>


                    </div>
                    <?php
                    if ($booked_index >= 8) {
                        $booked_index = 0;
                        echo "<script>document.getElementById('date_" . $date->format('Y-m-d') . "').style.display = 'none';</script>";
                    }
                }
                ?>
                <script>
                    function show_hide(id) {
                        if (document.getElementById(id).style.height == '') {
                            document.getElementById(id).style.height = 'auto';
                        } else {
                            document.getElementById(id).style.height = '';
                        }
                    }
                    function select_slot(button, input) {


                        input = document.getElementById(input);
                        if (input.value == 0) {
                            input.value = 1;
                            var selected = document.getElementsByName('selected[]');
                            var count = 0;
                            for (var i = 0; i < selected.length; i++) {
                                if (selected[i].value == 1) {
                                    count++;
                                }
                            }
                            if (count > 1) {
                                alert("Only one slot can be selected at a time");
                                input.value = 0;
                                return;
                            } else {
                                button.style.backgroundColor = "green";
                            }
                        } else {
                            input.value = 0;
                            button.style.backgroundColor = "#3a3a3a";
                        }
                    }
                </script>
            </div>
            <br>
            <div class="container_wide" id="calendar_container">
                <h2>PLEASE SELECT ADDITIONAL SERVICES:</h2>
                <div class="data_container_for_adding">
                    <select name="services" class="input" style="color:white;background-color:black">
                        <option value="0">NONE</option>
                        <?php
                        $services_res = $db->query("SELECT * FROM services");
                        while ($service = $services_res->fetch_assoc()) {
                            echo "<option value='" . $service['record_id'] . "'>" . $service['name'] . "</option>";
                        }
                        ?>

                    </select>
                </div>

            </div>


            <div class="container_wide">
                <button onclick="submit_from()">BOOK NOW</button>
                <script>
                    function submit_from() {
                        event.preventDefault();
                        document.getElementById('overlay').style.display = 'none';

                        var selected_dogs = document.getElementsByName('selected_dogs[]');
                        var selected_count = 0;
                        for (var i = 0; i < selected_dogs.length; i++) {
                            if (selected_dogs[i].value == 1) {
                                selected_count++;
                            }
                        }
                        if (selected_count == 0) {
                            alert("At least one dog must be selected");
                            return;
                        }
                        var selected_slots = document.getElementsByName('selected[]');
                        var selected_slot_count = 0;
                        for (var i = 0; i < selected_slots.length; i++) {
                            if (selected_slots[i].value == 1) {
                                selected_slot_count++;
                            }
                        }
                        if (selected_slot_count == 0) {
                            alert("At least one time slot must be selected");
                            return;
                        }

                        document.getElementById('form').submit();

                    }
                </script>
            </div>
            <div id="overlay"
                style="display:none;position:fixed;top:0;left:0;width:100vw;height:100%;background-color:rgba(0,0,0,0.5);z-index:9999;">
                <div style="position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);text-align:center;">
                    <p style="color:white;font-size:1.5em;">Loading...</p>
                </div>
            </div>
        </div>

</form>