<?php
include "classes/app.class.php";
?>
<div class="app-content-wrapper">
    <h2 class="main-title">Tanks</h2>
    <?php
    if ($_SESSION['tanks'] == 0 && $_SESSION['client_id'] == 0) {
        $sites_res = $db->query("sites", "SELECT * FROM sites  WHERE 1 ORDER BY `name` ASC");
        while ($site = $sites_res->fetch_assoc()) {
            ?>
            <div class="tank-group" id="group-<?php echo $site['name']; ?>">
                <div class="group-header">
                    <span class="group-title"> <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                            stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                            <circle cx="12" cy="10" r="3"></circle>
                        </svg> <?php echo $site['name']; ?></span>
                    <div class="group-chevron">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"
                            stroke-linecap="round" stroke-linejoin="round">
                            <polyline points="6 9 12 15 18 9"></polyline>
                        </svg>
                    </div>
                </div>
                <div class="group-content">
                    <?php
                    $tanks_res = $db->query("tanks", "SELECT * FROM tanks WHERE site_id = " . $site['record_id'] . " ORDER BY `name` ASC");
                    while ($tank = $tanks_res->fetch_assoc()) {
                        renderTankBlock($tank['record_id'], true, true);
                    }
                    ?>
                </div>
            </div>
        <?
        }
        $clients_res = $db->query("clients", "SELECT * FROM clients WHERE 1 ORDER BY `name` ASC");
        while ($clients = $clients_res->fetch_assoc()) {
            ?>
            <div class="tank-group" id="group-<?php echo $clients['name']; ?>">
                <div class="group-header">
                    <span class="group-title">👥 <?php echo $clients['name']; ?></span>
                    <div class="group-chevron">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"
                            stroke-linecap="round" stroke-linejoin="round">
                            <polyline points="6 9 12 15 18 9"></polyline>
                        </svg>
                    </div>
                </div>
                <div class="group-content">
                    <?php
                    $tanks_res = $db->query("tanks", "SELECT * FROM tanks WHERE client_id = " . $clients['record_id'] . "");
                    if ($tanks_res->num_rows > 0) {
                        while ($tank = $tanks_res->fetch_assoc()) {
                            renderTankBlock($tank['record_id'], true, true);
                        }
                    } else {
                        echo "--NO TANKS LOADED--";
                    }
                    ?>
                </div>
            </div>
            <?php
        }


    } else if ($_SESSION['client_id'] != 0) {
        $clients_res = $db->query("clients", "SELECT * FROM clients WHERE record_id = {$_SESSION['client_id']} ORDER BY `name` ASC");
        while ($clients = $clients_res->fetch_assoc()) {
            ?>
                <div class="tank-group" id="group-<?php echo $clients['name']; ?>">
                    <div class="group-header">
                        <span class="group-title">👥 <?php echo $clients['name']; ?></span>
                        <div class="group-chevron">
                            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"
                                stroke-linecap="round" stroke-linejoin="round">
                                <polyline points="6 9 12 15 18 9"></polyline>
                            </svg>
                        </div>
                    </div>
                    <div class="group-content">
                        <?php
                        $tanks_res = $db->query("tanks", "SELECT * FROM tanks WHERE client_id = {$_SESSION['client_id']}");
                        if ($tanks_res->num_rows > 0) {
                            while ($tank = $tanks_res->fetch_assoc()) {
                                renderTankBlock($tank['record_id'], true, true);
                            }
                        } else {
                            echo "--NO TANKS LOADED--";
                        }
                        ?>
                    </div>
                </div>
        <? }
    } else {
        $sites_res = $db->query("sites", "SELECT s.name as name, s.record_id as id FROM sites as s LEFT JOIN tanks as t ON s.record_id = t.site_id WHERE t.record_id IN ({$_SESSION['tanks']}) ");
        $prev_name = "";
        while ($site = $sites_res->fetch_assoc()) {
            if ($site['name'] != $prev_name) {
                $prev_name = $site['name'];
                ?>
                    <div class="tank-group" id="group-<?php echo $site['name']; ?>">
                        <div class="group-header">
                            <span class="group-title"> <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                    stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"></path>
                                    <circle cx="12" cy="10" r="3"></circle>
                                </svg> <?php echo $site['name']; ?></span>
                            <div class="group-chevron">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"
                                    stroke-linecap="round" stroke-linejoin="round">
                                    <polyline points="6 9 12 15 18 9"></polyline>
                                </svg>
                            </div>
                        </div>
                        <div class="group-content">
                            <?php
                            $tanks_res = $db->query("tanks", "SELECT * FROM tanks WHERE site_id = " . $site['id'] . " ORDER BY `name` ASC");
                            while ($tank = $tanks_res->fetch_assoc()) {
                                renderTankBlock($tank['record_id'], true, true);
                            }
                            ?>
                        </div>
                    </div>
            <?php }
        }
        if ($_SESSION['client_ids'] == '' || $_SESSION['client_ids'] == 0 || $_SESSION['client_ids'] == null) {
            $client_search = 0;
        }else{
            $client_search = $_SESSION['client_ids'];
        }
        $clients_res = $db->query("clients", "SELECT c.name as name, c.record_id as id FROM clients as c LEFT JOIN tanks as t ON c.record_id = t.client_id WHERE t.client_id IN ($client_search) ");
        $prev_name = "";
        while ($clients = $clients_res->fetch_assoc()) {
            if ($clients['name'] != $prev_name) {
                $prev_name = $clients['name'];
                ?>
                    <div class="tank-group" id="group-<?php echo $clients['name']; ?>">
                        <div class="group-header">
                            <span class="group-title">👥 <?php echo $clients['name']; ?></span>
                            <div class="group-chevron">
                                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"
                                    stroke-linecap="round" stroke-linejoin="round">
                                    <polyline points="6 9 12 15 18 9"></polyline>
                                </svg>
                            </div>
                        </div>
                        <div class="group-content">
                            <?php
                            $tanks_res = $db->query("tanks", "SELECT * FROM tanks WHERE client_id = " . $clients['id'] . " ORDER BY `name` ASC");
                            while ($tank = $tanks_res->fetch_assoc()) {
                                renderTankBlock($tank['record_id'], true, true);
                            }
                            ?>
                        </div>
                    </div>
            <?php }
        }
    }
    ?>
</div>
<script>
    // 1. Core Logic: Toggle Groups
    function initGroups() {
        document.querySelectorAll('.tank-group').forEach(group => {
            const header = group.querySelector('.group-header');
            const groupId = group.id;
            const state = localStorage.getItem(groupId);

            if (state === null || state === 'true') {
                group.classList.add('collapsed');
            }

            header.addEventListener('click', () => {
                group.classList.toggle('collapsed');
                const isCollapsed = group.classList.contains('collapsed');
                localStorage.setItem(groupId, isCollapsed ? 'true' : 'false');
            });
        });
    }

    // 2. Modified Refresh Logic (Targeting the specific element)
    function refreshTankElement(tankId, wrapper) {
        if (!wrapper) return;
        wrapper.classList.add('is-loading');

        fetch('ajax/refresh_tank.php?id=' + tankId)
            .then(response => response.text())
            .then(html => {
                wrapper.innerHTML = html;
                wrapper.classList.remove('is-loading');
            })
            .catch(err => {
                console.error('Refresh failed for tank ' + tankId, err);
                wrapper.classList.remove('is-loading');
            });
    }

    // 3. New Function to trigger all tanks at once
    function refreshAllTanks() {
        document.querySelectorAll('.tank-wrapper').forEach(wrapper => {
            const id = wrapper.getAttribute('data-id');
            refreshTankElement(id, wrapper);
        });
    }

    // 4. Initialize everything
    document.addEventListener('DOMContentLoaded', () => {
        initGroups();

        // KICK OFF IMMEDIATELY on page load
        refreshAllTanks();

        // Then repeat every 30 seconds
        setInterval(refreshAllTanks, 30000);
    });
</script>