<?php
// devices.php - dispositivos vinculados aos codigos de ativacao
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/header.php';

$message = '';
$pdo = db();
$is_admin = user_is_admin($user);
$user_id = (int)($user['id'] ?? 0);

function devices_date($value): string {
    if (empty($value)) return '-';
    $dt = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', (string)$value, new DateTimeZone('UTC'));
    if (!$dt) {
        $ts = strtotime((string)$value);
        if (!$ts) return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
        $dt = (new DateTimeImmutable('@' . $ts))->setTimezone(new DateTimeZone('UTC'));
    }
    return $dt->setTimezone(new DateTimeZone('America/Sao_Paulo'))->format('d/m/Y H:i');
}

if (isset($_POST['delete_id'])) {
    $id = (int)$_POST['delete_id'];
    if ($id > 0) {
        if ($is_admin) {
            $stmt = $pdo->prepare("DELETE FROM app_client_devices WHERE id = ?");
            $deleted = $stmt->execute([$id]);
        } else {
            $stmt = $pdo->prepare("
                DELETE FROM app_client_devices
                 WHERE id = ?
                   AND client_id IN (
                       SELECT id
                         FROM app_clients
                        WHERE reseller_user_id = ?
                   )
            ");
            $deleted = $stmt->execute([$id, $user_id]) && $stmt->rowCount() > 0;
        }

        if ($deleted) {
            $message = '<div class="panel-alert success">Vinculo liberado. Esse codigo podera ser usado por outro dispositivo.</div>';
        } else {
            $message = '<div class="panel-alert error">Erro ao liberar dispositivo.</div>';
        }
    }
}

if ($is_admin) {
    $stmt = $pdo->query("
        SELECT
            d.id,
            d.device_id,
            d.activation_code,
            d.first_seen_at,
            d.last_seen_at,
            c.name AS client_name,
            c.is_active
          FROM app_client_devices d
     LEFT JOIN app_clients c ON c.id = d.client_id
      ORDER BY d.last_seen_at DESC, d.id DESC
    ");
    $devices = $stmt ? $stmt->fetchAll(PDO::FETCH_ASSOC) : [];
} else {
    $stmt = $pdo->prepare("
        SELECT
            d.id,
            d.device_id,
            d.activation_code,
            d.first_seen_at,
            d.last_seen_at,
            c.name AS client_name,
            c.is_active
          FROM app_client_devices d
          JOIN app_clients c ON c.id = d.client_id
         WHERE c.reseller_user_id = ?
      ORDER BY d.last_seen_at DESC, d.id DESC
    ");
    $stmt->execute([$user_id]);
    $devices = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
}
?>

<style>
    .devices-page { width: 100%; }
    .devices-title { margin-bottom: 22px; }
    .devices-title h1 { margin: 0; font-size: 30px; color: #fff; }
    .devices-title p { margin: 8px 0 0; color: var(--text-secondary, #f6c7c7); }
    .devices-card {
        border: 1px solid var(--border-color, rgba(255, 205, 205, .16));
        border-radius: 22px;
        background: rgba(49, 3, 3, .78);
        overflow: hidden;
        box-shadow: var(--shadow, 0 22px 65px rgba(0, 0, 0, .38));
    }
    .devices-table-wrap { width: 100%; overflow-x: auto; }
    .devices-table { width: 100%; min-width: 980px; border-collapse: collapse; color: #fff; }
    .devices-table th {
        background: rgba(150, 22, 22, .88);
        padding: 17px 18px;
        text-align: left;
        white-space: nowrap;
    }
    .devices-table td {
        padding: 18px;
        border-bottom: 1px solid rgba(255, 205, 205, .12);
        vertical-align: middle;
    }
    .devices-table tr:last-child td { border-bottom: 0; }
    .device-id {
        display: inline-block;
        max-width: 340px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        color: #ff7878;
        font-family: Consolas, "Courier New", monospace;
        font-weight: 800;
    }
    .pill {
        display: inline-flex;
        border-radius: 999px;
        padding: 8px 12px;
        font-size: 13px;
        font-weight: 800;
        white-space: nowrap;
    }
    .pill-code {
        background: rgba(255, 92, 92, .16);
        border: 1px solid rgba(255, 92, 92, .32);
        color: #fff;
        font-family: Consolas, "Courier New", monospace;
        letter-spacing: .08em;
    }
    .pill-active { background: rgba(28, 214, 120, .15); color: #28f08b; }
    .pill-inactive { background: rgba(255, 77, 109, .15); color: #ff7b95; }
    .date-text { color: var(--text-secondary, #d7c7f6); white-space: nowrap; }
    .devices-footer {
        padding: 16px 18px 20px;
        color: var(--text-secondary, #f6c7c7);
        border-top: 1px solid rgba(255, 205, 205, .10);
    }
    .btn-release-device {
        border: 0;
        border-radius: 14px;
        background: linear-gradient(135deg, #ff5c5c 0%, #ff2c2c 100%);
        color: #fff;
        font-weight: 900;
        padding: 11px 16px;
        cursor: pointer;
    }
    .empty-state { padding: 46px 20px; text-align: center; color: var(--text-secondary, #f6c7c7); }
    .empty-state h3 { margin-bottom: 8px; color: #fff; }
    .panel-alert {
        border-radius: 16px;
        padding: 14px 16px;
        margin-bottom: 18px;
        font-weight: 800;
    }
    .panel-alert.success { background: rgba(28, 214, 120, .14); border: 1px solid rgba(28, 214, 120, .28); color: #5dffa4; }
    .panel-alert.error { background: rgba(255, 77, 109, .14); border: 1px solid rgba(255, 77, 109, .28); color: #ff8ca1; }
</style>

<div class="devices-page">
    <div class="devices-title">

     
    </div>

    <?php echo $message; ?>

    <div class="devices-card">
        <?php if (count($devices) > 0): ?>
            <div class="devices-table-wrap">
                <table class="devices-table">
                    <thead>
                        <tr>
                            
                            <th>Dispositivo</th>
                            <th>Cliente</th>
                            <th>Codigo</th>
                            <th>Acesso</th>
                    
                            <th>Acao</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($devices as $d): ?>
                            <tr>
                             
                                <td>
                                    <span class="device-id" title="<?php echo htmlspecialchars($d['device_id'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                                        <?php echo htmlspecialchars($d['device_id'] ?? '', ENT_QUOTES, 'UTF-8'); ?>
                                    </span>
                                </td>
                                <td><?php echo htmlspecialchars($d['client_name'] ?: 'Cliente removido', ENT_QUOTES, 'UTF-8'); ?></td>
                                <td><span class="pill pill-code"><?php echo htmlspecialchars(format_activation_code($d['activation_code'] ?? ''), ENT_QUOTES, 'UTF-8'); ?></span></td>
                                <td><span class="date-text"><?php echo devices_date($d['last_seen_at'] ?? ''); ?></span></td>

                                <td>
                                    <form method="post" onsubmit="return confirm('Liberar este codigo para outro dispositivo?');">
                                        <input type="hidden" name="delete_id" value="<?php echo (int)$d['id']; ?>">
                                        <button type="submit" class="btn-release-device">Deslogar</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <div class="devices-footer">
                <strong>Total:</strong> <?php echo count($devices); ?> dispositivos.
            </div>
        <?php else: ?>
            <div class="empty-state">
                <h3>Nenhum dispositivo.</h3>

            </div>
        <?php endif; ?>
    </div>
</div>

</main>
</body>
</html>
