<?php
include "includes/header.php";
$table_name = "playlist";
$res = $db->select($table_name, "*", "", "");

if (isset($_POST["submit"])) {
    unset($_POST["submit"]);
    $db->insert($table_name, $_POST);
    $db->close();
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=1'</script>";
}

$resU = @$db->select($table_name, "*", "id = :id", "", [":id" => $_GET["update"]]);

if (isset($_POST["submitU"])) {
    unset($_POST["submitU"]);
    $updateData = $_POST;
    $db->update($table_name, $updateData, "id = :id", [":id" => $_GET["update"]]);
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=1'</script>";
}

if (isset($_GET["delete"])) {
    $db->delete($table_name, "id = :id", [":id" => $_GET["delete"]]);
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=2'</script>";
}

// Modal de confirmação
echo '
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Confirm</h2>
            </div>
            <div class="modal-body">
                Do you really want to delete?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <a class="btn btn-danger btn-ok">Delete</a>
            </div>
        </div>
    </div>
</div>
';

// Formulário criar/editar
if (isset($_GET["create"]) || isset($_GET["update"])) {
    $isUpdate = isset($_GET["update"]);
    $data = $isUpdate ? $resU[0] : ['username'=>'','password'=>'','mac_address'=>'','pin'=>'0000','dns_id'=>''];
    $actionName = $isUpdate ? 'Edit Current User' : 'Add User';
    $buttonName = $isUpdate ? 'submitU' : 'submit';

    echo "
    <div class='col-md-8 mx-auto'>
        <div class='card-body'>
            <div class='card bg-primary text-white'>
                <div class='card-header card-header-warning text-center'>
                    <h2><i class='icon icon-bullhorn'></i> {$actionName}</h2>
                </div>
                <div class='card-body'>
                    <form method='post'>
                        <div class='form-group'>
                            <label for='dns_id'>DNS</label>
                            <select class='form-control' name='dns_id'>";
                                $dnss = $db->select("dns", "*", "", "");
                                foreach ($dnss as $dns) {
                                    $selected = $dns['id']==$data['dns_id'] ? "selected" : "";
                                    echo "<option value='{$dns['id']}' {$selected}>{$dns['title']}</option>";
                                }
    echo "              </select>
                        </div>
                        <div class='form-group'>
                            <label for='mac_address'>MAC Address</label>
                            <input class='form-control' id='mac' name='mac_address' placeholder='MAC Address' type='text' value='{$data['mac_address']}'/>
                        </div>
                        <script>
                            document.getElementById('mac').addEventListener('keyup', function() {
                                this.value = (this.value.toUpperCase().replace(/[^\\d|A-Z]/g, '').match(/.{1,2}/g)||[]).join(':');
                            });
                        </script>
                        <div class='form-group'>
                            <label for='username'>Username</label>
                            <input class='form-control' name='username' placeholder='Username' type='text' value='{$data['username']}'/>
                        </div>
                        <div class='form-group'>
                            <label for='password'>Password</label>
                            <input class='form-control' name='password' placeholder='Password' type='text' value='{$data['password']}'/>
                        </div>
                        <div class='form-group'>
                            <label for='pin'>Parental Pin</label>
                            <input class='form-control' name='pin' placeholder='Parental Pin' type='text' value='{$data['pin']}'/>
                        </div>
                        <div class='form-group text-center'>
                            <button class='btn btn-info' name='{$buttonName}' type='submit'><i class='icon icon-check'></i> Submit</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>";
} else {
    // Lista com busca e paginação
    echo "
    <div class='col-md-12 mx-auto'>
        <div class='card-body'>
            <div class='card bg-primary text-white'>
                <div class='card-header card-header-warning text-center'>
                    <h2><i class='icon icon-commenting'></i> Current Users</h2>
                </div>
                <div class='card-body'>
                    <div class='mb-3 text-center'>
                        <a href='./".basename($_SERVER["SCRIPT_NAME"])."?create' class='btn btn-info'>Create User</a>
                    </div>
                    <div class='mb-3 text-center'>
                        <input type='text' id='searchInput' placeholder='Search username or MAC' class='form-control d-inline-block' style='width:250px;'>
                    </div>
                    <div class='table-responsive'>
                        <table class='table table-striped table-sm' id='usersTable'>
                            <thead style='color:white!important'>
                                <tr>
                                    <th>DNS ID</th>
                                    <th>MAC Address</th>
                                    <th>Username</th>
                                    <th>Password</th>
                                    <th>Parental Pin</th>
                                    <th>Edit&nbsp;&nbsp;Delete</th>
                                </tr>
                            </thead>
                            <tbody>";
                                foreach ($res as $row) {
                                    echo "<tr>
                                        <td>{$row['dns_id']}</td>
                                        <td>{$row['mac_address']}</td>
                                        <td>{$row['username']}</td>
                                        <td>{$row['password']}</td>
                                        <td>{$row['pin']}</td>
                                        <td>
                                            <a class='btn btn-info btn-ok' href='./".basename($_SERVER["SCRIPT_NAME"])."?update={$row['id']}'><i class='fa fa-pencil-square-o'></i></a>
                                            &nbsp;&nbsp;&nbsp;
                                            <a class='btn btn-danger btn-ok' href='#' data-href='./".basename($_SERVER["SCRIPT_NAME"])."?delete={$row['id']}' data-toggle='modal' data-target='#confirm-delete'><i class='fa fa-trash-o'></i></a>
                                        </td>
                                    </tr>";
                                }
    echo "              </tbody>
                        </table>
                    </div>
                    <nav aria-label='Page navigation' class='mt-3 text-center'>
                        <ul class='pagination justify-content-center' id='pagination'></ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>";
}

include "includes/footer.php";
?>

<script>
// Paginação e busca
const rowsPerPage = 10;
let currentPage = 1;
const table = document.getElementById('usersTable').getElementsByTagName('tbody')[0];
const allRows = Array.from(table.getElementsByTagName('tr'));
const pagination = document.getElementById('pagination');

function renderTable(){
    const search = document.getElementById('searchInput').value.toLowerCase();
    const filteredRows = allRows.filter(row => {
        const username = row.cells[2].textContent.toLowerCase();
        const mac = row.cells[1].textContent.toLowerCase();
        return username.includes(search) || mac.includes(search);
    });
    const totalPages = Math.ceil(filteredRows.length / rowsPerPage);
    const start = (currentPage-1)*rowsPerPage;
    const end = start+rowsPerPage;

    allRows.forEach(r=>r.style.display='none');
    filteredRows.slice(start,end).forEach(r=>r.style.display='table-row');

    renderPagination(totalPages);
}

function renderPagination(totalPages){
    pagination.innerHTML='';
    if(totalPages<=1) return;
    for(let i=1;i<=totalPages;i++){
        const li=document.createElement('li');
        li.className='page-item '+(i===currentPage?'active':'');
        const a=document.createElement('a');
        a.className='page-link';
        a.href='#';
        a.textContent=i;
        a.addEventListener('click',e=>{
            e.preventDefault();
            currentPage=i;
            renderTable();
        });
        li.appendChild(a);
        pagination.appendChild(li);
    }
}

document.getElementById('searchInput').addEventListener('input', ()=>{
    currentPage=1;
    renderTable();
});

renderTable();
</script>