<?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=5'</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=5'</script>";
}

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

// Add new function to delete all records
if (isset($_GET["deleteall"])) {
    $db->delete($table_name, "1=1", []);
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=7'</script>";
}
?>

<style>
/* Consistent with DNS.php styling */
.card {
    border: none;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    margin-bottom: 20px;
}

.card-header {
    border-radius: 8px 8px 0 0 !important;
    padding: 15px 20px;
    font-weight: 600;
    background: linear-gradient(135deg, var(--primary-blue) 0%, var(--dark-blue) 100%) !important;
    color: white;
}

.form-control {
    padding: 10px 15px;
    border-radius: 6px;
    border: 1px solid #ced4da;
}

.btn-sm {
    padding: 6px 12px;
    font-size: 0.875rem;
}

.table thead th {
    background-color: var(--light-blue);
    color: var(--dark-blue);
}

/* MAC address formatting highlight */
#mac {
    background-color: rgba(232, 234, 246, 0.5);
}

/* Alert styles */
.alert {
    border-radius: 8px;
    padding: 15px 20px;
    margin-bottom: 20px;
}

.alert-success {
    background-color: #d4edda;
    border-color: #c3e6cb;
    color: #155724;
}

.alert-dismissible .btn-close {
    right: 0;
    top: 0;
    padding: 15px 20px;
}
</style>

<div class="container-fluid py-4">
    <?php if (isset($_GET["create"])): ?>
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card shadow-sm">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0"><i class="fas fa-user-plus me-2"></i>Adicionar usuário</h4>
                            <a href="<?= basename($_SERVER["SCRIPT_NAME"]) ?>" class="btn btn-sm btn-light">
                                <i class="fas fa-arrow-left me-1"></i> Voltar
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <div class="mb-3">
                                <label class="form-label" for="dns_id">DNS</label>
                                <select class="form-control" name="dns_id" required>
                                    <option value="" selected disabled>Escolha um</option>
                                    <?php 
                                    $dnss = $db->select("dns", "*", "", "");
                                    foreach ($dnss as $dns): ?>
                                        <option value="<?= $dns["id"] ?>"><?= htmlspecialchars($dns["title"]) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="mac">Endereço MAC</label>
                                <input class="form-control" id="mac" name="mac_address" placeholder="00:11:22:33:44:55" required/>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="username">Nome de usuário</label>
                                <input class="form-control" id="username" name="username" placeholder="Username" required/>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="password">Senha</label>
                                <input class="form-control" id="password" name="password" placeholder="Password" required/>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="pin">Parental Pin</label>
                                <input class="form-control" id="pin" name="pin" placeholder="0000" value="0000"/>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="link">Link</label>
                                <input class="form-control" id="link" name="link" placeholder="Optional link"/>
                            </div>
                            <div class="text-center mt-4">
                                <button type="submit" name="submit" class="btn btn-primary px-4">
                                    <i class="fas fa-save me-2"></i>Salvar usuário
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    
    <?php elseif (isset($_GET["update"])): ?>
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card shadow-sm">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0"><i class="fas fa-user-edit me-2"></i>Editar usuário</h4>
                            <a href="<?= basename($_SERVER["SCRIPT_NAME"]) ?>" class="btn btn-sm btn-light">
                                <i class="fas fa-arrow-left me-1"></i> Voltar
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <form method="post">
                            <div class="mb-3">
                                <label class="form-label" for="id">ID do usuário</label>
                                <input class="form-control" id="id" name="id" value="<?= $resU[0]["id"] ?>" readonly/>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="dns_id">DNS</label>
                                <select class="form-control" name="dns_id" required>
                                    <?php 
                                    $dnss = $db->select("dns", "*", "", "");
                                    foreach ($dnss as $dns): ?>
                                        <option value="<?= $dns["id"] ?>" <?= $dns["id"] == $resU[0]["dns_id"] ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($dns["title"]) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="mac_address">Endereço MAC</label>
                                <input class="form-control" id="mac_address" name="mac_address" value="<?= htmlspecialchars($resU[0]["mac_address"]) ?>" required/>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="username">Nome de usuário</label>
                                <input class="form-control" id="username" name="username" value="<?= htmlspecialchars($resU[0]["username"]) ?>" required/>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="password">Senha</label>
                                <input class="form-control" id="password" name="password" value="<?= htmlspecialchars($resU[0]["password"]) ?>" required/>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="pin">Parental Pin</label>
                                <input class="form-control" id="pin" name="pin" value="<?= htmlspecialchars($resU[0]["pin"]) ?>"/>
                            </div>
                            <div class="mb-3">
                                <label class="form-label" for="link">Link</label>
                                <input class="form-control" id="link" name="link" value="<?= htmlspecialchars($resU[0]["link"]) ?>"/>
                            </div>
                            <div class="text-center mt-4">
                                <button type="submit" name="submitU" class="btn btn-primary px-4">
                                    <i class="fas fa-save me-2"></i>Atualizar usuário
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    
    <?php else: ?>
        <div class="row">
            <div class="col-12">
                <?php if (isset($_GET["status"])): ?>
                    <?php if ($_GET["status"] == 5): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i> O usuário foi salvo com sucesso.
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php elseif ($_GET["status"] == 6): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i> O usuário foi excluído com sucesso.
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php elseif ($_GET["status"] == 7): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle me-2"></i> Todos os usuários foram excluídos com sucesso.
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php endif; ?>
                <?php endif; ?>
                
                <div class="card shadow-sm">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="mb-0"><i class="fas fa-users me-2"></i>Gerenciamento de usuários</h4>
                            <div>
                                <?php if (count($res) > 0): ?>
                                <a href="<?= basename($_SERVER["SCRIPT_NAME"]) ?>?deleteall=1" class="btn btn-sm btn-danger me-2" onclick="return confirm('Tem certeza de que deseja excluir TODOS os usuários? Esta ação não pode ser desfeita.');">
                                    <i class="fas fa-trash-alt me-1"></i> Remover tudo
                                </a>
                                <?php endif; ?>
                                <a href="<?= basename($_SERVER["SCRIPT_NAME"]) ?>?create=1" class="btn btn-sm btn-light">
                                    <i class="fas fa-plus me-1"></i> Adicionar novo
                                </a>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <?php if (count($res) > 0): ?>
                        <div class="table-responsive">
                            <table class="table table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th>DNS ID</th>
                                        <th>Endereço MAC</th>
                                        <th>Nome de usuário</th>
                                        <th>Senha</th>
                                        <th>Parental Pin</th>
                                        <th>Link</th>
                                        <th class="text-center">Ações</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($res as $row): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($row["dns_id"]) ?></td>
                                        <td><code><?= htmlspecialchars($row["mac_address"]) ?></code></td>
                                        <td><?= htmlspecialchars($row["username"]) ?></td>
                                        <td><?= htmlspecialchars($row["password"]) ?></td>
                                        <td><?= htmlspecialchars($row["pin"]) ?></td>
                                        <td><?= htmlspecialchars($row["link"]) ?></td>
                                        <td class="text-center">
                                            <a href="<?= basename($_SERVER["SCRIPT_NAME"]) ?>?update=<?= $row["id"] ?>" class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-edit"></i>
                                            </a>
                                            <a href="<?= basename($_SERVER["SCRIPT_NAME"]) ?>?delete=<?= $row["id"] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Are you sure you want to delete this user?');">
                                                <i class="fas fa-trash-alt"></i>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php else: ?>
                        <div class="text-center py-4">
                            <i class="fas fa-users fa-3x text-muted mb-3"></i>
                            <p class="text-muted">Nenhum usuário encontrado. Clique em "Adicionar novo" para criar um.</p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>

<script>
// MAC address auto-formatting
document.getElementById("mac")?.addEventListener("input", function() {
    this.value = this.value.toUpperCase().replace(/[^\dA-Z]/g, "")
        .replace(/(.{2})(?!$)/g, '$1:')
        .substring(0, 17);
});

// Auto close alerts after 3 seconds
setTimeout(function() {
    document.querySelectorAll('.alert').forEach(function(alert) {
        var closeButton = alert.querySelector('.btn-close');
        if (closeButton) {
            closeButton.click();
        }
    });
}, 3000);
</script>

<?php 
include "includes/footer.php";
?>