<?php
// OneLauncher - devices.php
require_once 'includes/auth.php';
require_once 'db.php';

$pageTitle = 'Gestão de Dispositivos (MACs)';
$nav = 'devices';
$msg = "";

// Atualizar Vencimento ou Status
if (isset($_POST['update_device'])) {
    $id = (int) $_POST['id'];
    $expiration = $_POST['expiration_date'];
    $active = isset($_POST['active']) ? 1 : 0;
    $note = $_POST['note'];
    $theme_id = (int) ($_POST['theme_id'] ?? 1);
    $autoplay_package = trim($_POST['autoplay_package'] ?? '');

    if (empty($expiration)) {
        $stmt = $conn->prepare("UPDATE devices SET expiration_date = NULL, active = ?, note = ?, theme_id = ?, autoplay_package = ? WHERE id = ?");
        $stmt->bind_param("isssi", $active, $note, $theme_id, $autoplay_package, $id);
    } else {
        $stmt = $conn->prepare("UPDATE devices SET expiration_date = ?, active = ?, note = ?, theme_id = ?, autoplay_package = ? WHERE id = ?");
        $stmt->bind_param("sisssi", $expiration, $active, $note, $theme_id, $autoplay_package, $id);
    }

    if ($stmt->execute()) {
        $msg = "Dispositivo atualizado com sucesso!";
    } else {
        $msg = "Erro ao atualizar dispositivo.";
    }
}

// Excluir Dispositivo
if (isset($_GET['delete'])) {
    $id = (int) $_GET['delete'];
    $conn->query("DELETE FROM devices WHERE id = $id");
    header("Location: devices.php?msg=deleted");
    exit;
}

// Alternar Status Ativo/Inativo (Ativar/Bloquear Launcher)
if (isset($_GET['toggle_active'])) {
    $id = (int) $_GET['toggle_active'];
    $stmt = $conn->prepare("SELECT active FROM devices WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    if ($res) {
        $new_status = $res['active'] ? 0 : 1;
        $stmt_update = $conn->prepare("UPDATE devices SET active = ? WHERE id = ?");
        $stmt_update->bind_param("ii", $new_status, $id);
        if ($stmt_update->execute()) {
            $status_txt = $new_status ? "ativada" : "desativada";
            header("Location: devices.php?msg=status_updated&status_txt=" . $status_txt);
            exit;
        }
    }
}

if (isset($_GET['msg'])) {
    if ($_GET['msg'] == 'deleted') {
        $msg = "Dispositivo removido.";
    }
    if ($_GET['msg'] == 'status_updated') {
        $status_txt = htmlspecialchars($_GET['status_txt'] ?? '');
        $msg = "Launcher " . $status_txt . " com sucesso!";
    }
}

// Ações em Massa (Excluir ou Mensagem)
if (isset($_POST['bulk_delete']) && !empty($_POST['selected_devices'])) {
    $ids = array_map('intval', $_POST['selected_devices']);
    $ids_string = implode(',', $ids);
    if (!empty($ids_string)) {
        $conn->query("DELETE FROM devices WHERE id IN ($ids_string)");
        $msg = count($ids) . " dispositivos removidos com sucesso.";
    }
}

if (isset($_POST['send_message']) && !empty($_POST['selected_devices'])) {
    $title = $_POST['message_title'] ?? '';
    $body = $_POST['message_body'] ?? '';
    $ids = array_map('intval', $_POST['selected_devices']);
    $ids_string = implode(',', $ids);

    if (!empty($ids_string)) {
        $stmt = $conn->prepare("UPDATE devices SET message_title = ?, message_body = ? WHERE id IN ($ids_string)");
        $stmt->bind_param("ss", $title, $body);
        if ($stmt->execute()) {
            $msg = count($ids) . " mensagens enviadas com sucesso.";
        } else {
            $msg = "Erro ao enviar mensagens.";
        }
    }
}

$devices = $conn->query("SELECT * FROM devices ORDER BY last_check DESC");

$themes_res = $conn->query("SELECT * FROM themes ORDER BY id ASC");
$all_themes = [];
while ($t = $themes_res->fetch_assoc()) {
    $all_themes[] = $t;
}

$all_registered_apps = [];
$res_apps_store = $conn->query("SELECT name, package_name FROM app_store WHERE package_name != '' UNION SELECT app_name as name, package_name FROM launcher_apps WHERE package_name != '' ORDER BY name ASC");
if ($res_apps_store) {
    while ($app = $res_apps_store->fetch_assoc()) {
        if (!empty($app['package_name'])) {
            $all_registered_apps[] = $app;
        }
    }
}

include 'includes/head.php';
include 'includes/sidebar.php';
include 'includes/topbar.php';
include 'includes/layout-open.php';
?>

<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">

<style>
    /* ========== DESIGN SYSTEM ========== */
    :root {
        --bg-primary: #0a0e17;
        --bg-secondary: #111827;
        --bg-tertiary: #1a2235;
        --accent: #3b82f6;
        --accent-hover: #2563eb;
        --accent-glow: rgba(59, 130, 246, 0.15);
        --danger: #ef4444;
        --danger-hover: #dc2626;
        --success: #10b981;
        --warning: #f59e0b;
        --text-primary: #f1f5f9;
        --text-secondary: #94a3b8;
        --text-muted: #64748b;
        --border: rgba(255, 255, 255, 0.08);
        --border-light: rgba(255, 255, 255, 0.05);
        --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.3);
        --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.4);
        --shadow-lg: 0 10px 40px rgba(0, 0, 0, 0.5);
        --radius-sm: 10px;
        --radius-md: 14px;
        --radius-lg: 18px;
        --transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
    }

    /* ========== PAGE HEADER ========== */
    .page-header {
        background: linear-gradient(135deg, rgba(59, 130, 246, 0.05) 0%, rgba(139, 92, 246, 0.05) 100%);
        border: 1px solid var(--border);
        border-radius: var(--radius-lg);
        padding: 1.75rem 2rem;
        margin-bottom: 2rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1rem;
        flex-wrap: wrap;
        box-shadow: var(--shadow-md);
    }

    .page-header-content h2 {
        font-size: 1.5rem;
        font-weight: 700;
        color: var(--text-primary);
        margin-bottom: 0.25rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .page-header-content h2 i {
        font-size: 1.35rem;
        background: linear-gradient(135deg, var(--accent), #8b5cf6);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    .page-header-content p {
        color: var(--text-muted);
        font-size: 0.875rem;
        margin: 0;
    }

    /* ========== ALERTS ========== */
    .alert-custom {
        border-radius: var(--radius-md);
        padding: 1rem 1.5rem;
        margin-bottom: 1.5rem;
        border: none;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        animation: slideDown 0.4s ease;
    }

    .alert-success-custom {
        background: rgba(16, 185, 129, 0.1);
        color: #34d399;
        border-left: 4px solid var(--success);
    }

    @keyframes slideDown {
        from { opacity: 0; transform: translateY(-15px); }
        to { opacity: 1; transform: translateY(0); }
    }

    /* ========== BULK ACTIONS BAR ========== */
    .bulk-actions-bar {
        background: var(--bg-tertiary);
        border: 1px solid rgba(245, 158, 11, 0.3);
        border-radius: var(--radius-md);
        padding: 0.85rem 1.25rem;
        margin-bottom: 1rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
        flex-wrap: wrap;
        animation: slideDown 0.3s ease;
    }

    .bulk-actions-bar .selected-count {
        color: var(--warning);
        font-weight: 700;
        font-size: 0.85rem;
    }

    .btn-warning-custom {
        background: rgba(245, 158, 11, 0.15);
        border: 1px solid rgba(245, 158, 11, 0.3);
        color: var(--warning);
        padding: 0.5rem 1rem;
        border-radius: 50px;
        font-weight: 600;
        font-size: 0.8rem;
        cursor: pointer;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        gap: 0.4rem;
    }

    .btn-warning-custom:hover {
        background: rgba(245, 158, 11, 0.25);
        border-color: rgba(245, 158, 11, 0.5);
    }

    .btn-danger-custom {
        background: rgba(239, 68, 68, 0.15);
        border: 1px solid rgba(239, 68, 68, 0.3);
        color: var(--danger);
        padding: 0.5rem 1rem;
        border-radius: 50px;
        font-weight: 600;
        font-size: 0.8rem;
        cursor: pointer;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        gap: 0.4rem;
    }

    .btn-danger-custom:hover {
        background: rgba(239, 68, 68, 0.25);
        border-color: rgba(239, 68, 68, 0.5);
    }

    /* ========== TABLE CONTAINER ========== */
    .table-container {
        background: var(--bg-secondary);
        border: 1px solid var(--border);
        border-radius: var(--radius-lg);
        overflow: hidden;
        box-shadow: var(--shadow-lg);
    }

    .table-header {
        background: var(--bg-tertiary);
        padding: 1rem 1.5rem;
        border-bottom: 1px solid var(--border);
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .table-header-title {
        color: var(--text-secondary);
        font-size: 0.8rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    /* ========== DataTables OVERRIDES ========== */
    .dataTables_wrapper .dataTables_length select {
        background: var(--bg-primary) !important;
        border: 1px solid var(--border) !important;
        color: var(--text-secondary) !important;
        border-radius: var(--radius-sm) !important;
        padding: 0.4rem 0.75rem !important;
    }

    .dataTables_wrapper .dataTables_filter input {
        background: var(--bg-primary) !important;
        border: 1px solid var(--border) !important;
        color: var(--text-primary) !important;
        border-radius: 50px !important;
        padding: 0.5rem 1rem !important;
        margin-left: 0.5rem !important;
    }

    .dataTables_wrapper .dataTables_filter input:focus {
        outline: none !important;
        border-color: var(--accent) !important;
        box-shadow: 0 0 0 4px var(--accent-glow) !important;
    }

    .dataTables_wrapper .dataTables_paginate .paginate_button {
        border-radius: 50px !important;
        padding: 0.3rem 0.7rem !important;
        margin: 0 0.15rem !important;
    }

    .dataTables_wrapper .dataTables_paginate .paginate_button.current {
        background: linear-gradient(135deg, var(--accent), #4f46e5) !important;
        border-color: transparent !important;
        color: white !important;
        font-weight: 700 !important;
    }

    .dataTables_wrapper .dataTables_paginate .paginate_button:hover {
        background: rgba(59, 130, 246, 0.15) !important;
        border-color: var(--accent) !important;
        color: var(--accent) !important;
    }

    .dataTables_wrapper .dataTables_info {
        color: var(--text-muted) !important;
    }

    /* ========== TABLE CUSTOM COMPACTA E ORGANIZADA ========== */
    .table-custom {
        width: 100% !important;
        border-collapse: separate;
        border-spacing: 0;
    }

    .table-custom thead th {
        background: rgba(255, 255, 255, 0.02);
        color: var(--text-muted);
        font-size: 0.72rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        padding: 0.85rem 0.75rem;
        border-bottom: 2px solid var(--border-light);
        white-space: nowrap;
        vertical-align: middle;
    }

    .table-custom tbody td {
        padding: 0.65rem 0.75rem;
        border-bottom: 1px solid var(--border-light);
        color: var(--text-secondary);
        vertical-align: middle;
        font-size: 0.83rem;
        white-space: nowrap;
    }

    .table-custom tbody tr {
        transition: var(--transition);
    }

    .table-custom tbody tr:hover {
        background: rgba(59, 130, 246, 0.03);
    }

    .table-custom .checkbox-cell {
        width: 40px;
        text-align: center;
    }

    .table-custom .checkbox-cell input {
        cursor: pointer;
        accent-color: var(--accent);
    }

    .autoplay-badge {
        background: rgba(59, 130, 246, 0.12);
        color: #60a5fa;
        border: 1px solid rgba(59, 130, 246, 0.25);
        font-size: 0.75rem;
        padding: 0.35rem 0.6rem;
        border-radius: 6px;
        display: inline-flex;
        align-items: center;
        max-width: 170px;
    }

    .autoplay-badge .truncate-text {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        display: inline-block;
    }

    .action-buttons-group {
        display: inline-flex;
        align-items: center;
        gap: 0.3rem;
        justify-content: flex-end;
        white-space: nowrap;
    }

    /* ========== DEVICE ID ========== */
    .device-id {
        font-weight: 600;
        color: var(--accent);
        font-family: 'Courier New', monospace;
        font-size: 0.85rem;
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }

    .device-id i {
        font-size: 0.9rem;
    }

    /* ========== BADGES ========== */
    .badge-status {
        padding: 0.3rem 0.75rem;
        border-radius: 50px;
        font-size: 0.7rem;
        font-weight: 700;
        letter-spacing: 0.03em;
        display: inline-flex;
        align-items: center;
        gap: 0.35rem;
    }

    .badge-active {
        background: rgba(16, 185, 129, 0.1);
        color: #34d399;
        border: 1px solid rgba(16, 185, 129, 0.3);
    }

    .badge-blocked {
        background: rgba(239, 68, 68, 0.1);
        color: #f87171;
        border: 1px solid rgba(239, 68, 68, 0.3);
    }

    .badge-expired {
        background: rgba(245, 158, 11, 0.1);
        color: #fbbf24;
        border: 1px solid rgba(245, 158, 11, 0.3);
    }

    .badge-lifetime {
        background: rgba(139, 92, 246, 0.1);
        color: #a78bfa;
        border: 1px solid rgba(139, 92, 246, 0.3);
        font-size: 0.7rem;
        padding: 0.2rem 0.6rem;
        border-radius: 50px;
        font-weight: 700;
    }

    /* ========== ACTION BUTTONS ========== */
    .btn-action-custom {
        width: 34px;
        height: 34px;
        border-radius: 50%;
        border: none;
        cursor: pointer;
        transition: var(--transition);
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 0.85rem;
    }

    .btn-msg-custom {
        background: rgba(245, 158, 11, 0.1);
        border: 1px solid rgba(245, 158, 11, 0.3);
        color: var(--warning);
    }

    .btn-msg-custom:hover {
        background: rgba(245, 158, 11, 0.2);
        transform: scale(1.1);
    }

    .btn-edit-custom {
        background: rgba(59, 130, 246, 0.1);
        border: 1px solid rgba(59, 130, 246, 0.3);
        color: var(--accent);
    }

    .btn-edit-custom:hover {
        background: rgba(59, 130, 246, 0.2);
        transform: scale(1.1);
    }

    .btn-delete-custom {
        background: rgba(239, 68, 68, 0.1);
        border: 1px solid rgba(239, 68, 68, 0.3);
        color: var(--danger);
    }

    .btn-delete-custom:hover {
        background: rgba(239, 68, 68, 0.2);
        transform: scale(1.1);
    }

    .btn-active-toggle {
        background: rgba(16, 185, 129, 0.1);
        border: 1px solid rgba(16, 185, 129, 0.3);
        color: var(--success);
    }
    
    .btn-active-toggle:hover {
        background: rgba(16, 185, 129, 0.2);
        transform: scale(1.1);
    }

    .btn-inactive-toggle {
        background: rgba(100, 116, 139, 0.1);
        border: 1px solid rgba(100, 116, 139, 0.3);
        color: var(--text-muted);
    }
    
    .btn-inactive-toggle:hover {
        background: rgba(100, 116, 139, 0.2);
        transform: scale(1.1);
        color: var(--text-secondary);
    }

    /* ========== MODAL ========== */
    .modal-content-custom {
        background: var(--bg-secondary);
        border: 1px solid var(--border);
        border-radius: var(--radius-lg);
        box-shadow: var(--shadow-lg);
    }

    .modal-header-custom {
        padding: 1.5rem;
        border-bottom: 1px solid var(--border);
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .modal-title-custom {
        color: var(--text-primary);
        font-weight: 700;
        font-size: 1.15rem;
        display: flex;
        align-items: center;
        gap: 0.75rem;
    }

    .modal-title-custom i {
        font-size: 1.1rem;
        background: linear-gradient(135deg, var(--accent), #8b5cf6);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
    }

    .modal-body-custom {
        padding: 1.5rem;
    }

    .modal-footer-custom {
        padding: 1rem 1.5rem 1.5rem;
        border-top: 1px solid var(--border);
        display: flex;
        gap: 0.75rem;
    }

    .btn-close-custom {
        background: none;
        border: none;
        color: var(--text-muted);
        font-size: 1.25rem;
        cursor: pointer;
        transition: var(--transition);
        width: 36px;
        height: 36px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .btn-close-custom:hover {
        background: rgba(255, 255, 255, 0.05);
        color: var(--text-primary);
    }

    /* ========== FORM ELEMENTS ========== */
    .form-label-custom {
        color: var(--text-muted);
        font-size: 0.7rem;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        margin-bottom: 0.5rem;
        display: block;
    }

    .form-control-custom {
        background: var(--bg-primary);
        border: 1px solid var(--border);
        border-radius: var(--radius-sm);
        padding: 0.7rem 1rem;
        color: var(--text-primary);
        width: 100%;
        transition: var(--transition);
        font-size: 0.85rem;
    }

    .form-control-custom:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 4px var(--accent-glow);
        background: var(--bg-primary);
        color: var(--text-primary);
    }

    .form-control-custom[readonly] {
        opacity: 0.5;
        cursor: not-allowed;
    }

    .form-select-custom {
        background: var(--bg-primary);
        border: 1px solid var(--border);
        border-radius: var(--radius-sm);
        padding: 0.7rem 1rem;
        color: var(--text-primary);
        width: 100%;
        transition: var(--transition);
        font-size: 0.85rem;
        appearance: none;
        background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%2364748b' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='m2 5 6 6 6-6'/%3e%3c/svg%3e");
        background-repeat: no-repeat;
        background-position: right 0.75rem center;
        background-size: 16px 12px;
    }

    .form-select-custom:focus {
        outline: none;
        border-color: var(--accent);
        box-shadow: 0 0 0 4px var(--accent-glow);
    }

    .form-switch-custom {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        background: var(--bg-primary);
        border: 1px solid var(--border);
        border-radius: var(--radius-sm);
        padding: 1rem;
    }

    .form-switch-custom input {
        width: 48px;
        height: 26px;
        cursor: pointer;
        accent-color: var(--accent);
    }

    .form-switch-custom label {
        color: var(--text-primary);
        font-weight: 600;
        font-size: 0.85rem;
        cursor: pointer;
    }

    .form-hint {
        color: var(--text-muted);
        font-size: 0.75rem;
        margin-top: 0.35rem;
        display: flex;
        align-items: center;
        gap: 0.35rem;
    }

    .btn-outline-custom {
        background: transparent;
        border: 1px solid var(--border);
        color: var(--text-secondary);
        padding: 0.75rem 1.5rem;
        border-radius: 50px;
        font-weight: 600;
        font-size: 0.85rem;
        cursor: pointer;
        transition: var(--transition);
        flex: 1;
    }

    .btn-outline-custom:hover {
        background: rgba(255, 255, 255, 0.03);
        border-color: rgba(255, 255, 255, 0.15);
        color: var(--text-primary);
    }

    .btn-submit-custom {
        background: linear-gradient(135deg, var(--accent), #4f46e5);
        border: none;
        color: white;
        padding: 0.75rem 1.5rem;
        border-radius: 50px;
        font-weight: 600;
        font-size: 0.85rem;
        cursor: pointer;
        transition: var(--transition);
        flex: 1;
        box-shadow: 0 4px 15px rgba(59, 130, 246, 0.3);
    }

    .btn-submit-custom:hover {
        box-shadow: 0 8px 25px rgba(59, 130, 246, 0.4);
        transform: translateY(-1px);
    }

    /* ========== RESPONSIVE - MOBILE CARD LAYOUT ========== */
    @media (max-width: 768px) {
        .page-header {
            flex-direction: column;
            align-items: stretch;
            padding: 1.25rem;
            gap: 1rem;
        }

        .page-header .page-header-content {
            width: 100%;
        }

        .page-header span.badge {
            align-self: flex-start;
        }

        /* Ajuste do wrapper responsivo da tabela */
        .table-responsive {
            overflow-x: visible !important;
            padding: 0 !important;
            margin: 0 !important;
            border: none !important;
            width: 100% !important;
        }

        /* Configurar tabela para se comportar como blocos */
        #devicesTable,
        #devicesTable tbody {
            display: block;
            width: 100% !important;
        }

        /* Esconder cabeçalho da tabela no mobile */
        #devicesTable thead {
            display: none;
        }

        /* Cada linha vira um card */
        #devicesTable tbody tr {
            display: block;
            background: var(--bg-tertiary);
            border: 1px solid var(--border);
            border-radius: var(--radius-md);
            margin-bottom: 0.75rem;
            padding: 0.85rem 1rem;
            width: 100% !important;
            box-sizing: border-box;
        }

        #devicesTable tbody tr:hover {
            background: rgba(59, 130, 246, 0.05);
        }

        /* Cada célula vira uma linha com label */
        #devicesTable tbody td {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0.5rem 0;
            border-bottom: 1px solid var(--border-light);
            font-size: 0.82rem;
            width: 100% !important;
            box-sizing: border-box;
        }

        #devicesTable tbody td:last-child {
            border-bottom: none;
            padding-top: 0.6rem;
            justify-content: flex-end;
            gap: 0.4rem;
        }

        /* Label gerado pelo data-label */
        #devicesTable tbody td::before {
            content: attr(data-label);
            font-size: 0.7rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            color: var(--text-muted);
            flex-shrink: 0;
            margin-right: 0.75rem;
        }

        /* Célula de checkbox no mobile: sem label, centralizada */
        #devicesTable tbody td.checkbox-cell {
            justify-content: flex-start;
            gap: 0.5rem;
        }

        #devicesTable tbody td.checkbox-cell::before {
            content: 'Selecionar';
        }

        /* Ajustes dos controles do DataTables no mobile */
        .dataTables_wrapper .row {
            margin-left: 0 !important;
            margin-right: 0 !important;
            padding: 0 !important;
            width: 100% !important;
        }

        .dataTables_wrapper .col-sm-12,
        .dataTables_wrapper .col-md-6 {
            padding-left: 0 !important;
            padding-right: 0 !important;
            width: 100% !important;
        }

        .dataTables_wrapper .dataTables_filter,
        .dataTables_wrapper .dataTables_length,
        .dataTables_wrapper .dataTables_info,
        .dataTables_wrapper .dataTables_paginate {
            text-align: center;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            margin: 0.5rem 0 !important;
            width: 100% !important;
        }

        .dataTables_wrapper .dataTables_filter input {
            width: 100% !important;
            margin-left: 0 !important;
            margin-top: 0.5rem !important;
        }

        .dataTables_wrapper .dataTables_paginate .paginate_button {
            margin: 0.1rem !important;
            display: inline-block !important;
        }

        .device-id {
            font-size: 0.75rem;
            word-break: break-all;
            text-align: right;
            justify-content: flex-end;
        }

        .bulk-actions-bar {
            flex-direction: column;
            align-items: stretch;
            gap: 0.75rem;
            padding: 1rem;
        }

        .bulk-actions-bar button {
            width: 100%;
            justify-content: center;
        }
    }
</style>

<div class="container-fluid">


    <!-- Header da Página -->
    <div class="page-header">
        <div class="page-header-content">
            <h2>
                <i class="bi bi-shield-check"></i>
                Gestão de Dispositivos
            </h2>
            <p>Controle o bloqueio e acesso das Launchers</p>
        </div>
        <span class="badge bg-primary bg-opacity-10 text-primary rounded-pill px-3 py-2" style="font-size: 0.85rem; border: 1px solid rgba(59, 130, 246, 0.3);">
            <i class="bi bi-tv me-2"></i><?php echo $devices->num_rows; ?> Dispositivos
        </span>
    </div>

    <!-- Tabela -->
    <div class="table-container">
        <div class="table-header">
            <span class="table-header-title">
                <i class="bi bi-list-ul me-2"></i>Dispositivos Cadastrados
            </span>
        </div>

        <!-- Ações em Massa -->
        <div id="bulkActions" class="bulk-actions-bar" style="display: none;">
            <i class="bi bi-check-square" style="color: var(--warning);"></i>
            <span class="selected-count">
                <span id="bulkCount">0</span> selecionado(s)
            </span>
            <button type="button" class="btn-warning-custom" data-bs-toggle="modal" data-bs-target="#bulkMessageModal">
                <i class="bi bi-chat-dots"></i> Enviar Mensagem
            </button>
            <button type="button" class="btn-danger-custom" onclick="confirmBulkDelete()">
                <i class="bi bi-trash"></i> Remover
            </button>
        </div>

        <form method="POST" id="bulkDeleteForm">
            <div class="table-responsive">
                <table id="devicesTable" class="table-custom w-100">
                    <thead>
                        <tr>
                            <th class="checkbox-cell" style="width: 40px;">
                                <input type="checkbox" class="form-check-input" id="selectAll">
                            </th>
                            <th style="width: 170px;">Android ID</th>
                            <th>Nota / Cliente</th>
                            <th style="width: 110px;">Vencimento</th>
                            <th style="width: 160px;">AutoPlay</th>
                            <th style="width: 110px;">Status</th>
                            <th style="width: 150px;" class="text-end">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while ($dev = $devices->fetch_assoc()): ?>
                                <?php
                                $isExpired = false;
                                if ($dev['expiration_date'] && $dev['expiration_date'] < date('Y-m-d H:i:s')) {
                                    $isExpired = true;
                                }
                                ?>
                                <tr>
                                    <td class="checkbox-cell">
                                        <input type="checkbox" name="selected_devices[]" value="<?php echo $dev['id']; ?>" class="form-check-input device-checkbox">
                                    </td>
                                    <td data-label="Android ID">
                                        <div class="device-id" title="<?php echo htmlspecialchars($dev['device_id']); ?>">
                                            <i class="bi bi-cpu"></i>
                                            <?php echo htmlspecialchars($dev['device_id']); ?>
                                        </div>
                                    </td>
                                    <td data-label="Nota / Cliente">
                                        <?php if ($dev['note']): ?>
                                                <span style="color: var(--text-primary); font-weight: 500;"><?php echo htmlspecialchars($dev['note']); ?></span>
                                        <?php else: ?>
                                                <span style="color: var(--text-muted); font-style: italic;">Sem nota</span>
                                        <?php endif; ?>
                                    </td>
                                    <td data-label="Vencimento">
                                        <?php if ($dev['expiration_date']): ?>
                                                <span style="color: <?php echo $isExpired ? 'var(--danger)' : 'var(--text-secondary)'; ?>; font-weight: <?php echo $isExpired ? '700' : '400'; ?>;">
                                                    <i class="bi bi-calendar3 me-1"></i>
                                                    <?php echo date('d/m/Y', strtotime($dev['expiration_date'])); ?>
                                                </span>
                                        <?php else: ?>
                                                <span class="badge-lifetime">
                                                    <i class="bi bi-infinity me-1"></i> VITALÍCIO
                                                </span>
                                        <?php endif; ?>
                                    </td>
                                    <td data-label="AutoPlay">
                                        <?php if (!empty($dev['autoplay_package'])): ?>
                                                <span class="badge autoplay-badge" title="<?php echo htmlspecialchars($dev['autoplay_package']); ?>">
                                                    <i class="bi bi-play-circle-fill me-1"></i>
                                                    <span class="truncate-text"><?php echo htmlspecialchars($dev['autoplay_package']); ?></span>
                                                </span>
                                        <?php else: ?>
                                                <span style="color: var(--text-muted); font-size: 0.8rem; font-style: italic;">Sem AutoPlay</span>
                                        <?php endif; ?>
                                    </td>
                                    <td data-label="Status">
                                        <?php if ($dev['active'] && !$isExpired): ?>
                                                <span class="badge-status badge-active">
                                                    <i class="bi bi-check-circle-fill"></i> ATIVO
                                                </span>
                                        <?php elseif ($isExpired): ?>
                                                <span class="badge-status badge-expired">
                                                    <i class="bi bi-clock-history"></i> EXPIRADO
                                                </span>
                                        <?php else: ?>
                                                <span class="badge-status badge-blocked">
                                                    <i class="bi bi-x-circle-fill"></i> BLOQUEADO
                                                </span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end" data-label="Ações">
                                        <div class="action-buttons-group">
                                            <a href="javascript:void(0)" onclick="confirmToggleActive(<?php echo $dev['id']; ?>, <?php echo $dev['active'] ? 'true' : 'false'; ?>)" class="btn-action-custom <?php echo $dev['active'] ? 'btn-active-toggle' : 'btn-inactive-toggle'; ?>" title="<?php echo $dev['active'] ? 'Bloquear/Desativar Launcher' : 'Ativar Launcher'; ?>">
                                                <i class="bi <?php echo $dev['active'] ? 'bi-toggle-on' : 'bi-toggle-off'; ?>" style="font-size: 1.1rem;"></i>
                                            </a>
                                            <button type="button" class="btn-action-custom btn-msg-custom" data-bs-toggle="modal" data-bs-target="#messageModal<?php echo $dev['id']; ?>" title="Enviar Mensagem">
                                                <i class="bi bi-chat-dots"></i>
                                            </button>
                                            <button type="button" class="btn-action-custom btn-edit-custom" data-bs-toggle="modal" data-bs-target="#editModal<?php echo $dev['id']; ?>" title="Editar">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button type="button" class="btn-action-custom btn-delete-custom" onclick="confirmDelete(<?php echo $dev['id']; ?>)" title="Excluir">
                                                <i class="bi bi-trash3"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            <?php
                            $device_list[] = $dev;
                        endwhile;
                        ?>
                    </tbody>
                </table>
            </div>
        </form>
    </div>
</div>

<!-- Modais de Edição -->
<?php if (isset($device_list)):
    foreach ($device_list as $dev): ?>
            <div class="modal fade" id="editModal<?php echo $dev['id']; ?>" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content modal-content-custom">
                        <div class="modal-header-custom">
                            <h5 class="modal-title-custom">
                                <i class="bi bi-pencil"></i>
                                Editar Dispositivo
                            </h5>
                            <button type="button" class="btn-close-custom" data-bs-dismiss="modal">
                                <i class="bi bi-x-lg"></i>
                            </button>
                        </div>
                        <form method="POST">
                            <div class="modal-body-custom">
                                <input type="hidden" name="id" value="<?php echo $dev['id']; ?>">
                        
                                <div class="mb-3">
                                    <label class="form-label-custom">Android ID</label>
                                    <input type="text" class="form-control-custom" value="<?php echo htmlspecialchars($dev['device_id']); ?>" readonly>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label-custom">Nota / Nome do Cliente</label>
                                    <input type="text" name="note" class="form-control-custom" value="<?php echo htmlspecialchars($dev['note']); ?>" placeholder="Ex: João da Silva">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label-custom">Data de Vencimento</label>
                                    <input type="date" name="expiration_date" class="form-control-custom" value="<?php echo $dev['expiration_date'] ? date('Y-m-d', strtotime($dev['expiration_date'])) : ''; ?>">
                                    <p class="form-hint">
                                        <i class="bi bi-info-circle"></i> Deixe vazio para acesso Vitalício.
                                    </p>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label-custom">Tema Visual</label>
                                    <select name="theme_id" class="form-select-custom">
                                        <?php foreach ($all_themes as $t): ?>
                                                <option value="<?php echo $t['id']; ?>" <?php echo ($dev['theme_id'] ?? 1) == $t['id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($t['name']); ?>
                                                </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label-custom">AutoPlay no Boot (Abrir App Automático)</label>
                                    <select class="form-select-custom mb-2 autoplay-selector" data-target-input="autoplay_pkg_<?php echo $dev['id']; ?>">
                                        <option value="" <?php echo empty($dev['autoplay_package']) ? 'selected' : ''; ?>>-- Nenhum (Desativado) --</option>
                                        <?php foreach ($all_registered_apps as $reg_app): ?>
                                            <option value="<?php echo htmlspecialchars($reg_app['package_name']); ?>" <?php echo ($dev['autoplay_package'] == $reg_app['package_name']) ? 'selected' : ''; ?>>
                                                📱 <?php echo htmlspecialchars($reg_app['name']); ?> (<?php echo htmlspecialchars($reg_app['package_name']); ?>)
                                            </option>
                                        <?php endforeach; ?>
                                        <option value="custom" <?php echo (!empty($dev['autoplay_package']) && !in_array($dev['autoplay_package'], array_column($all_registered_apps, 'package_name'))) ? 'selected' : ''; ?>>
                                            ✍️ Digitar Package Name Manualmente...
                                        </option>
                                    </select>
                                    <input type="text" name="autoplay_package" id="autoplay_pkg_<?php echo $dev['id']; ?>" class="form-control-custom" value="<?php echo htmlspecialchars($dev['autoplay_package'] ?? ''); ?>" placeholder="Ex: com.google.android.youtube.tv">
                                    <p class="form-hint">
                                        <i class="bi bi-info-circle"></i> O app selecionado iniciará automaticamente quando o OneLauncher abrir nesta Box.
                                    </p>
                                </div>

                                <div class="form-switch-custom">
                                    <input class="form-check-input" type="checkbox" name="active" id="active<?php echo $dev['id']; ?>" <?php echo $dev['active'] ? 'checked' : ''; ?>>
                                    <label for="active<?php echo $dev['id']; ?>">Status Ativo (Liberado)</label>
                                </div>
                            </div>
                            <div class="modal-footer-custom">
                                <button type="button" class="btn-outline-custom" data-bs-dismiss="modal">Cancelar</button>
                                <button type="submit" name="update_device" class="btn-submit-custom">
                                    <i class="bi bi-check-lg me-2"></i> Salvar Alterações
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
    
            <!-- Modal Mensagem Individual -->
            <div class="modal fade" id="messageModal<?php echo $dev['id']; ?>" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content modal-content-custom">
                        <div class="modal-header-custom" style="border-bottom-color: rgba(245, 158, 11, 0.2);">
                            <h5 class="modal-title-custom">
                                <i class="bi bi-chat-dots" style="background: linear-gradient(135deg, var(--warning), #f97316); -webkit-background-clip: text; -webkit-text-fill-color: transparent;"></i>
                                Enviar Mensagem
                            </h5>
                            <button type="button" class="btn-close-custom" data-bs-dismiss="modal">
                                <i class="bi bi-x-lg"></i>
                            </button>
                        </div>
                        <form method="POST">
                            <div class="modal-body-custom">
                                <input type="hidden" name="selected_devices[]" value="<?php echo $dev['id']; ?>">
                        
                                <div class="mb-3">
                                    <label class="form-label-custom">Dispositivo Alvo</label>
                                    <input type="text" class="form-control-custom" value="<?php echo htmlspecialchars($dev['device_id'] . ($dev['note'] ? ' (' . $dev['note'] . ')' : '')); ?>" readonly>
                                </div>
                        
                                <div class="mb-3">
                                    <label class="form-label-custom" style="color: var(--warning);">Título da Mensagem</label>
                                    <input type="text" name="message_title" class="form-control-custom" value="<?php echo htmlspecialchars($dev['message_title'] ?? ''); ?>" placeholder="Ex: Aviso Importante" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label-custom" style="color: var(--warning);">Corpo da Mensagem</label>
                                    <textarea name="message_body" class="form-control-custom" rows="3" placeholder="Ex: Seu plano vence amanhã..." required><?php echo htmlspecialchars($dev['message_body'] ?? ''); ?></textarea>
                                </div>
                                <p class="form-hint">
                                    <i class="bi bi-info-circle"></i> A mensagem aparecerá na tela do cliente.
                                </p>
                            </div>
                            <div class="modal-footer-custom">
                                <button type="button" class="btn-outline-custom" data-bs-dismiss="modal">Cancelar</button>
                                <button type="submit" name="send_message" class="btn-submit-custom" style="background: linear-gradient(135deg, var(--warning), #f97316); box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3);">
                                    <i class="bi bi-send me-2"></i> Enviar Mensagem
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
    <?php endforeach; endif; ?>

<!-- Modal Mensagem em Massa -->
<div class="modal fade" id="bulkMessageModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-content-custom">
            <div class="modal-header-custom" style="border-bottom-color: rgba(245, 158, 11, 0.2);">
                <h5 class="modal-title-custom">
                    <i class="bi bi-chat-dots" style="background: linear-gradient(135deg, var(--warning), #f97316); -webkit-background-clip: text; -webkit-text-fill-color: transparent;"></i>
                    Enviar Mensagem em Massa
                </h5>
                <button type="button" class="btn-close-custom" data-bs-dismiss="modal">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
            <div class="modal-body-custom">
                <div class="mb-3">
                    <label class="form-label-custom" style="color: var(--warning);">Título da Mensagem</label>
                    <input type="text" id="bulk_message_title" class="form-control-custom" placeholder="Ex: Aviso Geral" required>
                </div>
                <div class="mb-3">
                    <label class="form-label-custom" style="color: var(--warning);">Corpo da Mensagem</label>
                    <textarea id="bulk_message_body" class="form-control-custom" rows="3" placeholder="Ex: Estamos em manutenção..." required></textarea>
                </div>
            </div>
            <div class="modal-footer-custom">
                <button type="button" class="btn-outline-custom" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" onclick="submitBulkMessage()" class="btn-submit-custom" style="background: linear-gradient(135deg, var(--warning), #f97316); box-shadow: 0 4px 15px rgba(245, 158, 11, 0.3);">
                    <i class="bi bi-send me-2"></i> Enviar para Selecionados
                </button>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function() {
        var table = $('#devicesTable').DataTable({
            "language": {
                "url": "//cdn.datatables.net/plug-ins/1.13.6/i18n/pt-BR.json"
            },
            "order": [[5, "desc"]],
            "pageLength": 10,
            "lengthMenu": [5, 10, 25, 50],
            "columnDefs": [
                { "orderable": false, "targets": 0 },
                { "orderable": false, "targets": 6 }
            ],
            "dom": '<"d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3"<"dataTables_length_wrapper"l><"dataTables_filter_wrapper"f>>rt<"d-flex justify-content-between align-items-center flex-wrap gap-2 mt-3"<"dataTables_info_wrapper"i><"dataTables_paginate_wrapper"p>>'
        });

        $('#selectAll').on('click', function() {
            var rows = table.rows({ 'search': 'applied' }).nodes();
            $('input[type="checkbox"].device-checkbox', rows).prop('checked', this.checked);
            toggleBulkActions();
        });

        $('#devicesTable tbody').on('change', 'input[type="checkbox"].device-checkbox', function() {
            toggleBulkActions();
        });
        
        function toggleBulkActions() {
            var selected = table.$('input[type="checkbox"].device-checkbox:checked').length;
            if (selected > 0) {
                $('#bulkCount').text(selected);
                $('#bulkActions').slideDown(200);
            } else {
                $('#bulkActions').slideUp(200);
            }
        }
    });

    function confirmBulkDelete() {
        var selected = $('#devicesTable').DataTable().$('input[type="checkbox"].device-checkbox:checked').length;
        
        Swal.fire({
            title: 'Remover selecionados?',
            html: `<strong>${selected} dispositivo(s)</strong> serão removidos permanentemente!`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#3b82f6',
            confirmButtonText: 'Sim, excluir',
            cancelButtonText: 'Cancelar',
            background: '#111827',
            color: '#f1f5f9'
        }).then((result) => {
            if (result.isConfirmed) {
                var form = $('#bulkDeleteForm');
                var table = $('#devicesTable').DataTable();
                
                table.$('input[type="checkbox"].device-checkbox:checked').each(function(){
                    if(!$.contains(document, this)){
                        form.append(
                            $('<input>')
                                .attr('type', 'hidden')
                                .attr('name', this.name)
                                .val(this.value)
                        );
                    }
                });
                
                form.append('<input type="hidden" name="bulk_delete" value="1">');
                form.submit();
            }
        });
    }

    function submitBulkMessage() {
        var form = $('#bulkDeleteForm');
        var table = $('#devicesTable').DataTable();
        var title = $('#bulk_message_title').val();
        var body = $('#bulk_message_body').val();
        
        form.find('input[type="hidden"][name="selected_devices[]"]').remove();
        
        table.$('input[type="checkbox"].device-checkbox:checked').each(function(){
            if(!$.contains(document, this)){
                form.append(
                    $('<input>')
                        .attr('type', 'hidden')
                        .attr('name', this.name)
                        .val(this.value)
                );
            }
        });
        
        form.append('<input type="hidden" name="send_message" value="1">');
        form.append($('<input>').attr('type', 'hidden').attr('name', 'message_title').val(title));
        form.append($('<input>').attr('type', 'hidden').attr('name', 'message_body').val(body));
        form.submit();
    }

    function confirmDelete(id) {
        Swal.fire({
            title: 'Tem certeza?',
            text: "Esta ação não pode ser revertida!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#ef4444',
            cancelButtonColor: '#3b82f6',
            confirmButtonText: 'Sim, excluir!',
            cancelButtonText: 'Cancelar',
            background: '#111827',
            color: '#f1f5f9'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = 'devices.php?delete=' + id;
            }
        });
    }

    function confirmToggleActive(id, currentStatus) {
        const actionText = currentStatus ? 'desativar' : 'ativar';
        Swal.fire({
            title: `Deseja ${actionText} este dispositivo?`,
            text: `O launcher será ${currentStatus ? 'bloqueado' : 'liberado'} para este dispositivo.`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#0066FF',
            cancelButtonColor: '#3085d6',
            confirmButtonText: `Sim, ${actionText}!`,
            cancelButtonText: 'Cancelar',
            background: '#111827',
            color: '#f1f5f9'
        }).then((result) => {
            if (result.isConfirmed) {
                window.location.href = `devices.php?toggle_active=${id}`;
            }
        });
    }

    $(document).on('change', '.autoplay-selector', function() {
        var targetId = $(this).data('target-input');
        var val = $(this).val();
        if (val !== 'custom') {
            $('#' + targetId).val(val);
        }
    });
</script>

<?php
include 'includes/layout-close.php';
include 'includes/footer.php';
?>