<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <title><?= htmlspecialchars($tournament['name']) ?></title>
    <link rel="stylesheet" href="../public/css/style.css">
    <link rel="stylesheet" href="../public/css/tournament.css">
</head>

<body>
    <div class="wb">
        <div class="head">
            <div class="tittle"><?= htmlspecialchars($tournament['name']) ?></div>
            <a href="../public/index.php">
                <div class="pic img iClose"></div>
            </a>
        </div>
        <div class="scroll-container">
            <section class="section" id="info">
                <div class="tittle">Información</div>
                <form action="../public/tournament.php?action=<?= isset($tournament) ? 'update' : 'store' ?>&id=<?= htmlspecialchars($tournament['id']) ?>" method="POST" class="form" id="tournamentForm">
                    <div class="formItem">
                        <input type="text" class="formInput" id="name" placeholder="Nombre" required="" autocomplete="off" name="name" value="<?= htmlspecialchars($tournament['name']) ?>" />
                        <label for="name" class="formLabel">Nombre</label>
                    </div>
                    <div class="formItem">
                        <textarea class="formInput" id="desc" placeholder="Descripción" required="" autocomplete="off" name="description"><?= htmlspecialchars($tournament['description']) ?></textarea>
                        <label for="desc" class="formLabel">Descripción</label>
                    </div>
                    <div class="formItem">
                        <label for="date" class="formLabel">Fecha</label>
                        <input type="date" class="formInput" id="date" placeholder="Descripción" required="" autocomplete="off" name="date" value="<?= htmlspecialchars($tournament['date']) ?>" />
                    </div>
                    <input type="hidden" name="id" value="<?= htmlspecialchars($tournament['id']) ?>" />
                    <button class="button-85" role="button" value="Submit" type="submit">Guardar</button>
                </form>
                <button id="calculateStandingsBtn" class="button-85" data-tournament-id="<?= htmlspecialchars($tournament['id']) ?>">Calcular Posiciones</button>
            </section>

            <section class="section" id="games">
                <div class="tittle">Juegos</div>
                <a href="../public/game.php?action=create&tournament=<?= $tournament['id'] ?>" class="">Crear Juego</a>
                <?php if (!empty($games)): ?>
                    <?php foreach ($games as $game): ?>
                        <?php
                        $setsT1 = ($game['s1t1'] > $game['s1t2']) + ($game['s2t1'] > $game['s2t2']) + ($game['s3t1'] > $game['s3t2']);
                        $setsT2 = ($game['s1t1'] < $game['s1t2']) + ($game['s2t1'] < $game['s2t2']) + ($game['s3t1'] < $game['s3t2']);
                        $winner = $setsT1 > $setsT2;
                        ?>
                        <a href="../public/game.php?id=<?= $game['id'] ?>&tournament=<?= $tournament['id'] ?>">
                            <div class="gameCard">
                                <div class="gameCardHead displayRow">
                                    <img class="padelBall" loading="lazy" src="../../app/public/img/padelBall.webp">
                                    <div class="info displayColumn">
                                        <div class="date"><?= htmlspecialchars($game['date']) ?></div>
                                        <div class="name"><?= htmlspecialchars($game['desc']) ?></div>
                                    </div>
                                </div>
                                <div class="gameCardBody displayRowSpaceBetween">
                                    <div class="players displayColumn">
                                        <?php for ($i = 1; $i <= 2; $i++): ?>
                                            <div class="team displayRow">
                                                <div class="pics displayRow">
                                                    <img class="pic radiusCircle" src="../../app/public/img/user/<?= $game['p' . ($i * 2 - 1) . '_pic'] ? 'player_' . htmlspecialchars($game['p' . ($i * 2 - 1) . '_pic']) . '.webp' : 'user.png' ?>" loading="lazy">
                                                    <img class="pic radiusCircle" src="../../app/public/img/user/<?= $game['p' . ($i * 2) . '_pic'] ? 'player_' . htmlspecialchars($game['p' . ($i * 2) . '_pic']) . '.webp' : 'user.png' ?>" loading="lazy">
                                                </div>
                                                <div class="names displayColumn">
                                                    <div class="name <?= $i === 1 ? ($winner ? 'winner' : '') : ($winner ? '' : 'winner') ?>">
                                                        <?= htmlspecialchars($game['p' . ($i * 2 - 1) . '_pNombre']) . ' ' . htmlspecialchars($game['p' . ($i * 2 - 1) . '_pApellido']) ?>
                                                    </div>
                                                    <div class="name <?= $i === 1 ? ($winner ? 'winner' : '') : ($winner ? '' : 'winner') ?>">
                                                        <?= htmlspecialchars($game['p' . ($i * 2) . '_pNombre']) . ' ' . htmlspecialchars($game['p' . ($i * 2) . '_pApellido']) ?>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endfor; ?>
                                    </div>
                                    <div class="sets displayColumn">
                                        <div class="set <?= $winner ? 'winner' : '' ?>"><?= $game['s1t1'] . ' ' . $game['s2t1'] . ' ' . $game['s3t1']; ?></div>
                                        <div class="set <?= $winner ? '' : 'winner' ?>"><?= $game['s1t2'] . ' ' . $game['s2t2'] . ' ' . $game['s3t2']; ?></div>
                                    </div>
                                </div>
                            </div>
                        </a>
                    <?php endforeach; ?>
                <?php endif; ?>
                <!-- <?php if (!empty($games)): ?>
                    <?php foreach ($games as $game): ?>
                        <a href="../public/game.php?action=edit&id=<?= $game['id'] ?>&tournament=<?= $tournament['id'] ?>">
                            <div class="mainCard">
                                <div class="tittle"> <?= htmlspecialchars($game['desc']) ?> </div>
                                <div class="date"> <?= htmlspecialchars($game['date']) ?> </div>
                            </div>
                        </a>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p>No hay juegos para este torneo.</p>
                <?php endif; ?> -->
            </section>
            <style>
                #sortable-list {
                    list-style: none;
                    padding: 0;
                    width: 300px;
                    margin: 0 auto;
                    user-select: none;
                    /* Prevent text selection */
                }

                #sortable-list li {
                    background-color: #f4f4f4;
                    border: 1px solid #ccc;
                    padding: 10px;
                    margin-bottom: 5px;
                    cursor: move;
                    text-align: center;
                    transition: background-color 0.3s ease;
                }

                #sortable-list li.dragging {
                    background-color: #e0e0e0;
                    opacity: 0.7;
                }

                #sortable-list li.over {
                    border: 2px dashed #007bff;
                    background-color: #f0f8ff;
                }

                #sortable-list .draggable {
                    color: black;
                }

                @media (hover: none) {

                    /* For touch devices, adjust for better touch interactions */
                    #sortable-list li {
                        cursor: grab;
                    }

                    #sortable-list li:active {
                        cursor: grabbing;
                    }
                }
            </style>
            <section class="section" id="teams">
                <div class="tittle">Parejas</div>
                <a href="../public/team.php?action=create&tournament=<?= $tournament['id'] ?>">Crear Pareja</a>
                <?php if (!empty($teams)): ?>
                    <?php foreach ($teams as $team): ?>
                        <a href="../public/team.php?action=edit&id=<?= $team['id'] ?>&tournament=<?= $tournament['id'] ?>">
                            <div class="mainCard">
                                <div class="tittle"><?= htmlspecialchars($team['p1_lastname']) ?> / <?= htmlspecialchars($team['p2_lastname']) ?></div>
                            </div>
                        </a>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p>No hay Parejas para este torneo.</p>
                <?php endif; ?>
            </section>

            <section class="section" id="section4">
                <div class="tittle">Sponsors</div>
                <h2>Sortable List</h2>
                <ul id="sortable-list">
                    <li draggable="true" class="draggable">Item 1</li>
                    <li draggable="true" class="draggable">Item 2</li>
                    <li draggable="true" class="draggable">Item 3</li>
                    <li draggable="true" class="draggable">Item 4</li>
                    <li draggable="true" class="draggable">Item 5</li>
                </ul>
                <?php if (!empty($ads)): ?>
                    <ul>
                        <?php foreach ($ads as $ad): ?>
                            <li><?= htmlspecialchars($ad['sponsor_name']) ?> <?= htmlspecialchars($ad['description']) ?></li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p>No hay Sponsors para este torneo.</p>
                <?php endif; ?>
            </section>
        </div>
    </div>
</body>
<script>
    const listItems = document.querySelectorAll('.draggable');
    const list = document.getElementById('sortable-list');
    let draggedItem = null;
    let touchDragging = false; // Flag to check if touch dragging is happening
    let placeholder = null; // Placeholder for drag target

    // Desktop Drag and Drop Events
    listItems.forEach(item => {
        // When drag starts (desktop)
        item.addEventListener('dragstart', function() {
            draggedItem = item;
            setTimeout(() => item.classList.add('dragging'), 0);
        });

        // When drag ends (desktop)
        item.addEventListener('dragend', function() {
            setTimeout(() => {
                item.classList.remove('dragging');
                draggedItem = null;
            }, 0);
        });

        // When item is dragged over another item (desktop)
        item.addEventListener('dragover', function(e) {
            e.preventDefault();
        });

        // When item enters another item's space (desktop)
        item.addEventListener('dragenter', function(e) {
            e.preventDefault();
            item.classList.add('over');
        });

        // When item leaves another item's space (desktop)
        item.addEventListener('dragleave', function() {
            item.classList.remove('over');
        });

        // When item is dropped (desktop)
        item.addEventListener('drop', function() {
            if (draggedItem !== this) {
                const allItems = [...listItems]; // Convert NodeList to array
                const draggedIndex = allItems.indexOf(draggedItem);
                const dropIndex = allItems.indexOf(this);

                if (draggedIndex < dropIndex) {
                    list.insertBefore(draggedItem, this.nextSibling);
                } else {
                    list.insertBefore(draggedItem, this);
                }
            }

            item.classList.remove('over');
        });
    });

    // Touch Events for Mobile Support
    listItems.forEach(item => {
        // Start touch dragging
        item.addEventListener('touchstart', function(e) {
            touchDragging = true;
            draggedItem = item;
            placeholder = document.createElement('li');
            placeholder.className = 'placeholder';
            placeholder.style.height = `${item.offsetHeight}px`; // Maintain size for a smooth experience
            item.classList.add('dragging');
        });

        // Move the dragged item
        item.addEventListener('touchmove', function(e) {
            if (!touchDragging) return;
            e.preventDefault(); // Prevent scrolling

            const touch = e.touches[0];
            const targetElement = document.elementFromPoint(touch.clientX, touch.clientY);

            if (targetElement && targetElement.tagName === 'LI' && targetElement !== draggedItem) {
                targetElement.classList.add('over');

                const allItems = [...listItems];
                const draggedIndex = allItems.indexOf(draggedItem);
                const targetIndex = allItems.indexOf(targetElement);

                if (draggedIndex < targetIndex) {
                    list.insertBefore(draggedItem, targetElement.nextSibling);
                } else {
                    list.insertBefore(draggedItem, targetElement);
                }
            }
        });

        // End touch dragging
        item.addEventListener('touchend', function() {
            touchDragging = false;
            draggedItem.classList.remove('dragging');
            placeholder.remove();
            draggedItem = null;

            // Remove all over classes after touch ends
            listItems.forEach(i => i.classList.remove('over'));
        });

        // Ensure the list stays interactive after touch leaves
        item.addEventListener('touchcancel', function() {
            touchDragging = false;
            draggedItem.classList.remove('dragging');
            placeholder.remove();
            draggedItem = null;

            listItems.forEach(i => i.classList.remove('over'));
        });
    });

    document.getElementById('calculateStandingsBtn').addEventListener('click', function() {
        const tournamentId = this.getAttribute('data-tournament-id');
        console.log(`../controllers/StandingsController.php?id=${tournamentId}`)
        fetch(`../controllers/StandingsController.php?id=${tournamentId}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    console.log('Standings calculados:', data.standings);
                } else {
                    console.error('Error al calcular standings:', data.message);
                }
            })
            .catch(error => console.error('Error en la solicitud:', error));
    });
</script>

</html>