<?php
ob_start();
require_once __DIR__ . '/includes/header.php';

$message = '';
$message_type = '';
$editing_id = null;
$editing_data = null;
$can_create_client = user_can_create_client($user);
$is_reseller = user_is_reseller($user);
$usage = user_client_usage_summary($user);

function list_dns_can_manage_client(array $loggedUser, int $clientId, ?array &$client = null): bool {
    $client = get_client_by_id($clientId);
    if (!$client) {
        return false;
    }
    return client_belongs_to_user($loggedUser, $client);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update' && isset($_POST['id'])) {
        $id = (int)$_POST['id'];
        if (!list_dns_can_manage_client($user, $id)) {
            $message = 'Cliente nao encontrado nesta conta.';
            $message_type = 'error';
        } else {
            $name = str_in($_POST['name'] ?? '');
            $m3u_url = str_in($_POST['m3u_url'] ?? '');
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            $expires_source = str_in($_POST['expires_source'] ?? 'xtream');
            $expires_at = str_in($_POST['expires_at'] ?? '');

            $result = update_client($id, $name, $m3u_url, $is_active, $expires_source, $expires_at);

            if ($result['ok']) {
                ob_end_clean();
                header('Location: list_dns.php?success=updated');
                exit;
            } else {
                $message = $result['message'];
                $message_type = 'error';
            }
        }
    }
}

if (isset($_GET['action'])) {
    $action = $_GET['action'];
    $id = (int)($_GET['id'] ?? 0);

    switch ($action) {
        case 'deactivate':
            if (list_dns_can_manage_client($user, $id) && deactivate_client_by_id($id)) {
                ob_end_clean();
                header('Location: list_dns.php?success=deactivated');
                exit;
            }
            $message = 'Cliente nao encontrado nesta conta.';
            $message_type = 'error';
            break;

        case 'activate':
            if (list_dns_can_manage_client($user, $id) && activate_client_by_id($id)) {
                ob_end_clean();
                header('Location: list_dns.php?success=activated');
                exit;
            }
            $message = 'Cliente nao encontrado nesta conta.';
            $message_type = 'error';
            break;

        case 'delete':
            if (list_dns_can_manage_client($user, $id) && delete_client_by_id($id)) {
                ob_end_clean();
                header('Location: list_dns.php?success=deleted');
                exit;
            }
            $message = 'Cliente nao encontrado nesta conta.';
            $message_type = 'error';
            break;

        case 'edit':
            if (list_dns_can_manage_client($user, $id, $editing_data)) {
                $editing_id = $id;
            } else {
                $message = 'Cliente não encontrado.';
                $message_type = 'error';
            }
            break;
    }
}

if (isset($_GET['success'])) {
    switch ($_GET['success']) {
        case 'updated':
            $message = 'Cliente atualizado com sucesso!';
            break;
        case 'deactivated':
            $message = 'Cliente desativado com sucesso!';
            break;
        case 'activated':
            $message = 'Cliente ativado com sucesso!';
            break;
        case 'deleted':
            $message = 'Cliente excluído permanentemente!';
            break;
    }
    $message_type = 'success';
}

if (!empty($_GET['cards_error'])) {
    $message = (string)$_GET['cards_error'];
    $message_type = 'error';
}

$clients = get_visible_clients_for_user($user);
?>

<style>
    .page-header {
        margin-bottom: 30px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        flex-wrap: wrap;
        gap: 15px;
    }
    
    .page-header h1 {
        font-size: 28px;
        margin: 0;
        background: var(--primary-bg);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    .add-btn {
        background: var(--primary-bg);
        color: #fff;
        padding: 10px 20px;
        border-radius: 6px;
        text-decoration: none;
        font-size: 14px;
        font-weight: 600;
        transition: all 0.2s ease;
        display: inline-block;
    }
    
    .add-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }

    .page-header-actions {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }

    .reseller-summary {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        margin-top: 12px;
    }

    .summary-pill {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 7px 11px;
        border-radius: 999px;
        background: rgba(168, 85, 247, 0.14);
        border: 1px solid rgba(168, 85, 247, 0.35);
        color: #e9ddff;
        font-size: 12px;
        font-weight: 700;
        white-space: nowrap;
    }

    .summary-pill strong {
        color: #fff;
        font-weight: 900;
    }

    .add-btn-outline {
        background: rgba(168, 85, 247, 0.12);
        border: 1px solid rgba(168, 85, 247, 0.55);
        color: #d7c7f6;
    }

    .add-btn-outline:hover {
        background: rgba(168, 85, 247, 0.22);
        color: #fff;
    }
    
    .alert {
        padding: 15px 20px;
        border-radius: 8px;
        margin-bottom: 20px;
        animation: slideIn 0.3s ease;
    }
    
    .alert-success {
        background: rgba(46, 204, 113, 0.2);
        border: 1px solid #2ecc71;
        color: #2ecc71;
    }
    
    .alert-error {
        background: rgba(231, 76, 60, 0.2);
        border: 1px solid #e74c3c;
        color: #e74c3c;
    }
    
    .edit-form {
        background: #1a1a1a;
        padding: 25px;
        border-radius: 12px;
        border: 2px solid var(--primary-bg);
        margin-bottom: 25px;
        animation: slideDown 0.3s ease;
    }
    
    @keyframes slideDown {
        from {
            opacity: 0;
            transform: translateY(-20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .edit-form h2 {
        font-size: 14px;
        margin-bottom: 20px;
        color: #fff;
    }
    
    .form-grid {
        display: grid;
        grid-template-columns: minmax(160px, 1fr) minmax(280px, 2fr) minmax(180px, 1fr) minmax(150px, 1fr) auto;
        gap: 15px;
        margin-bottom: 15px;
        align-items: end;
    }
    
    .form-group {
        display: flex;
        flex-direction: column;
    }
    
    .form-group label {
        margin-bottom: 6px;
        color: #fff;
        font-weight: 500;
        font-size: 13px;
    }
    
    .form-group input,
    .form-group select {
        width: 100%;
        box-sizing: border-box;
        padding: 10px 12px;
        background: #111;
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 6px;
        color: #fff;
        font-size: 14px;
        min-height: 42px;
        color-scheme: dark;
    }

    .form-group select option {
        background-color: #111 !important;
        color: #fff !important;
    }

    .form-group select option:checked {
        background-color: #6d28d9 !important;
        color: #fff !important;
    }
    
    .form-group input:focus,
    .form-group select:focus {
        outline: none;
        border-color: var(--primary-bg);
    }

    .form-group input:disabled {
        opacity: 0.45;
        cursor: not-allowed;
    }
    
    .checkbox-group {
        display: flex;
        align-items: center;
        gap: 8px;
        min-height: 42px;
    }
    
    .checkbox-group input[type="checkbox"] {
        width: 18px;
        height: 18px;
        cursor: pointer;
    }
    
    .form-actions {
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }
    
    .btn {
        padding: 10px 20px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
        text-decoration: none;
        display: inline-block;
    }
    
    .btn-primary {
        background: var(--primary-bg);
        color: #fff;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }
    
    .btn-secondary {
        background: #555;
        color: #fff;
    }
    
    .btn-secondary:hover {
        background: #666;
    }
    
    .table-container {
        background: var(--card-bg);
        border-radius: 12px;
        border: 1px solid var(--border-color);
        overflow-x: auto;
        overflow-y: hidden;
        max-width: 100%;
        -webkit-overflow-scrolling: touch;
        scrollbar-width: thin;
        scrollbar-color: rgba(168, 85, 247, 0.85) rgba(255, 255, 255, 0.06);
        box-shadow: inset -18px 0 24px rgba(115, 48, 255, 0.10);
    }

    .table-container::-webkit-scrollbar {
        height: 8px;
    }

    .table-container::-webkit-scrollbar-track {
        background: rgba(255, 255, 255, 0.06);
        border-radius: 50px;
    }

    .table-container::-webkit-scrollbar-thumb {
        background: var(--primary-bg);
        border-radius: 50px;
    }

    .code-cell {
        font-family: 'Courier New', monospace;
        font-weight: 700;
        letter-spacing: 2px;
        color: #d7c7f6;
        white-space: nowrap;
    }

    .expiry-stack {
        display: inline-flex;
        flex-direction: column;
        gap: 4px;
    }

    .expiry-date {
        color: #fff;
        font-weight: 700;
        white-space: nowrap;
    }

    .expiry-date.expired {
        color: #ff8a8a;
    }

    .expiry-date.unknown {
        color: #b7a8d8;
    }

    .expiry-source {
        display: inline-block;
        width: max-content;
        padding: 3px 8px;
        border-radius: 999px;
        font-size: 10px;
        font-weight: 700;
        background: rgba(168, 85, 247, 0.16);
        border: 1px solid rgba(168, 85, 247, 0.35);
        color: #e9ddff;
        white-space: nowrap;
    }

    .mobile-scroll-tip {
        display: none;
        margin: 0 0 10px;
        padding: 10px 14px;
        border-radius: 12px;
        color: #e9ddff;
        font-size: 13px;
        border: 1px solid rgba(168, 85, 247, 0.35);
        background: rgba(76, 29, 149, 0.32);
    }
    
    .dns-table {
        width: 100%;
        min-width: 760px;
        border-collapse: collapse;
    }
    
    .dns-table thead {
        background: #0a0a0a;
    }
    
    .dns-table th {
        padding: 15px;
        text-align: left;
        font-size: 14px;
        font-weight: 600;
        color: #fff;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    }
    
    .dns-table td {
        padding: 15px;
        font-size: 14px;
        color: #ccc;
        border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    }
    
    .dns-table tbody tr {
        transition: background 0.2s ease;
    }
    
    .dns-table tbody tr:hover {
        background: rgba(255, 255, 255, 0.02);
    }
    
    .dns-table tbody tr.inactive {
        opacity: 0.6;
    }
    
    .dns-table tbody tr.editing {
        background: rgba(192, 57, 43, 0.1);
        border-left: 3px solid var(--primary-bg);
    }
    
    .status-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }
    
    .status-active {
        background: rgba(46, 204, 113, 0.2);
        color: #2ecc71;
    }
    
    .status-inactive {
        background: rgba(231, 76, 60, 0.2);
        color: #e74c3c;
    }
    
    .action-btns {
        display: flex;
        gap: 6px;
        flex-wrap: wrap;
    }
    
    .action-btn {
        padding: 6px 12px;
        border-radius: 4px;
        font-size: 12px;
        text-decoration: none;
        display: inline-block;
        transition: all 0.2s ease;
        border: 1px solid;
        white-space: nowrap;
    }
    
    .btn-edit {
        background: rgba(52, 152, 219, 0.1);
        color: #3498db;
        border-color: #3498db;
    }
    
    .btn-edit:hover {
        background: #3498db;
        color: #fff;
    }
    
    .btn-activate {
        background: rgba(46, 204, 113, 0.1);
        color: #2ecc71;
        border-color: #2ecc71;
    }
    
    .btn-activate:hover {
        background: #2ecc71;
        color: #fff;
    }
    
    .btn-deactivate {
        background: rgba(243, 156, 18, 0.1);
        color: #f39c12;
        border-color: #f39c12;
    }
    
    .btn-deactivate:hover {
        background: #f39c12;
        color: #fff;
    }
    
    .btn-delete {
        background: rgba(231, 76, 60, 0.1);
        color: #e74c3c;
        border-color: #e74c3c;
    }
    
    .btn-delete:hover {
        background: #e74c3c;
        color: #fff;
    }

    .btn-card {
        background: rgba(168, 85, 247, 0.12);
        color: #c084fc;
        border-color: #a855f7;
        cursor: pointer;
        font-family: inherit;
    }

    .btn-card:hover {
        background: #a855f7;
        color: #fff;
    }

    .card-modal {
        display: none;
        position: fixed;
        inset: 0;
        z-index: 9999;
        align-items: center;
        justify-content: center;
        padding: 20px;
    }

    .card-modal.open {
        display: flex;
    }

    .card-modal-backdrop {
        position: absolute;
        inset: 0;
        background: rgba(0, 0, 0, 0.72);
        backdrop-filter: blur(4px);
    }

    .card-modal-dialog {
        position: relative;
        z-index: 1;
        width: min(100%, 420px);
        background: #1a1a1a;
        border: 1px solid rgba(168, 85, 247, 0.45);
        border-radius: 16px;
        padding: 24px 22px 22px;
        box-shadow: 0 24px 60px rgba(0, 0, 0, 0.55);
        animation: slideDown 0.25s ease;
    }

    .card-modal-close {
        position: absolute;
        top: 12px;
        right: 14px;
        width: 32px;
        height: 32px;
        border: none;
        border-radius: 8px;
        background: rgba(255, 255, 255, 0.08);
        color: #ccc;
        font-size: 22px;
        line-height: 1;
        cursor: pointer;
    }

    .card-modal-close:hover {
        background: rgba(255, 255, 255, 0.15);
        color: #fff;
    }

    .card-modal-dialog h3 {
        margin: 0 0 8px;
        color: #fff;
        font-size: 18px;
    }

    .card-modal-code {
        margin: 0 0 18px;
        text-align: center;
        font-size: 15px;
    }

    .card-modal-image-wrap {
        display: flex;
        justify-content: center;
        margin-bottom: 18px;
    }

    .card-modal-image-wrap img {
        width: min(100%, 200px);
        border-radius: 14px;
        box-shadow: 0 14px 36px rgba(0, 0, 0, 0.45);
        border: 1px solid rgba(255, 255, 255, 0.1);
    }

    .card-modal-actions {
        display: flex;
        gap: 10px;
        justify-content: center;
        flex-wrap: wrap;
    }
    
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #999;
    }
    
    .empty-state h3 {
        color: #fff;
        margin: 15px 0 10px;
    }
    
    @media (max-width: 768px) {
        .page-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .page-header h1 {
            font-size: 24px;
        }

        .edit-form {
            padding: 16px;
            border-radius: 10px;
            margin-left: -4px;
            margin-right: -4px;
        }

        .edit-form h2 {
            font-size: 14px;
            line-height: 1.3;
        }
        
        .form-grid {
            grid-template-columns: 1fr;
            gap: 12px;
            align-items: stretch;
        }

        .form-group input,
        .form-group select {
            min-width: 0;
            font-size: 15px;
        }

        .checkbox-group {
            min-height: 0;
            margin-top: 2px;
        }

        .form-actions {
            flex-direction: column;
        }

        .form-actions .btn {
            width: 100%;
            text-align: center;
        }
        
        .mobile-scroll-tip {
            display: none;
        }

        .table-container {
            background: transparent;
            border: none;
            box-shadow: none;
            overflow: visible;
            border-radius: 0;
            margin-left: -4px;
            margin-right: -4px;
        }
        
        .dns-table {
            display: block;
            min-width: 0;
            width: 100%;
            border-collapse: separate;
            font-size: 14px;
        }

        .dns-table thead {
            display: none;
        }

        .dns-table tbody {
            display: grid;
            gap: 8px;
        }

        .dns-table tr {
            display: grid;
            grid-template-columns: 1fr auto auto;
            grid-template-areas:
                "nome vencimento status"
                "codigo codigo codigo"
                "acoes acoes acoes";
            align-items: center;
            gap: 8px 10px;
            padding: 10px;
            border-radius: 10px;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
        }

        .dns-table tbody tr.editing {
            border-left: 3px solid var(--primary-bg);
        }

        .dns-table tbody tr.inactive {
            opacity: 0.72;
        }
        
        .dns-table td {
            display: block;
            padding: 0;
            white-space: normal;
            border-bottom: none;
            text-align: left;
        }

        .dns-table td::before {
            display: none;
        }

        .dns-table td[data-label="Nome"] {
            grid-area: nome;
            font-weight: 800;
            color: #fff;
            min-width: 0;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .dns-table td[data-label="Vencimento"] {
            grid-area: vencimento;
            justify-self: end;
            white-space: nowrap;
        }

        .dns-table td[data-label="Status"] {
            grid-area: status;
            justify-self: end;
        }

        .dns-table td[data-label="Codigo"] {
            grid-area: codigo;
            padding-top: 4px;
            color: #d7c7f6;
            font-size: 13px;
            letter-spacing: 1px;
        }

        .dns-table td[data-label="Codigo"]::before {
            content: "Cod: ";
            display: inline;
            color: #b9a7dd;
            font-family: inherit;
            font-weight: 700;
            letter-spacing: 0;
        }

        .dns-table td[data-label="Acoes"] {
            grid-area: acoes;
            overflow-x: auto;
            padding-top: 2px;
            -webkit-overflow-scrolling: touch;
        }

        .expiry-stack {
            display: inline-flex;
            flex-direction: row;
            align-items: center;
            gap: 6px;
        }

        .expiry-date {
            font-size: 13px;
        }

        .expiry-source {
            padding: 2px 6px;
            font-size: 9px;
        }

        .status-badge {
            padding: 3px 8px;
            font-size: 11px;
        }

        .action-btns {
            display: flex;
            flex-wrap: nowrap;
            gap: 6px;
            min-width: max-content;
        }
        
        .action-btn {
            width: auto;
            min-width: 74px;
            text-align: center;
            padding: 6px 9px;
            box-sizing: border-box;
            font-size: 11px;
        }

        .code-cell {
            letter-spacing: 1px;
            white-space: normal;
            word-break: break-word;
        }
    }

    @media (max-width: 420px) {
        .dns-table tr {
            grid-template-columns: 1fr auto;
            grid-template-areas:
                "nome status"
                "vencimento vencimento"
                "codigo codigo"
                "acoes acoes";
            gap: 6px 8px;
        }

        .dns-table td[data-label="Vencimento"] {
            justify-self: start;
        }
    }
</style>

<div class="page-header">
    <div>
        <h2>Meus Clientes</h2>
        <?php if ($is_reseller): ?>
            <div class="reseller-summary">
                <span class="summary-pill">🗓️Vencimento: <strong><?php echo htmlspecialchars(user_panel_expiry_label($user)); ?></strong></span>
                <span class="summary-pill">🧑‍🧒‍🧒Clientes: <strong><?php echo (int)$usage['used']; ?> / <?php echo (int)$usage['contracted']; ?> usados</strong></span>
            </div>
        <?php endif; ?>
    </div>
    <div class="page-header-actions">
        <?php if (user_is_admin($user)): ?>
            <a href="all_clients.php" class="add-btn add-btn-outline">Todos clientes</a>
        <?php endif; ?>
        <?php if ($can_create_client): ?>
            <a href="dns.php?novo=1" class="add-btn">+ Cliente</a>
        <?php else: ?>
            <span class="add-btn" style="opacity:.45; cursor:not-allowed;">+ Cliente</span>
        <?php endif; ?>
    </div>
</div>

<?php if ($is_reseller && !$can_create_client): ?>
    <div class="alert alert-error">
        ⚠️Aingiu o limite de clientes contratados! Para criar novos clientes, aumente seu plano.
    </div>
<?php endif; ?>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $message_type; ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<?php if ($editing_id && $editing_data): ?>
    <div class="edit-form">

        <form method="POST">
            <input type="hidden" name="action" value="update">
            <input type="hidden" name="id" value="<?php echo $editing_id; ?>">

            <div class="form-grid edit-client-grid">
                <div class="form-group">
                    <label>Nome</label>
                    <input type="text"
                           name="name"
                           value="<?php echo htmlspecialchars($editing_data['name']); ?>"
                           required>
                </div>

                <div class="form-group">
                    <label>URL M3U</label>
                    <input type="text"
                           name="m3u_url"
                           value="<?php echo htmlspecialchars($editing_data['m3u_url']); ?>"
                           required>
                </div>

                <div class="form-group">
                    <label>Vencimento</label>
                    <select name="expires_source" id="expires_source">
                        <?php $editing_source = normalize_client_expires_source((string)($editing_data['expires_source'] ?? 'xtream')); ?>
                        <option value="xtream" <?php echo $editing_source === 'xtream' ? 'selected' : ''; ?>>Xtream</option>
                        <option value="manual" <?php echo $editing_source === 'manual' ? 'selected' : ''; ?>>Manual</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Data manual</label>
                    <input type="date"
                           name="expires_at"
                           id="expires_at"
                           value="<?php echo htmlspecialchars(client_expires_input_value($editing_data)); ?>">
                </div>

<input type="hidden"
       name="is_active"
       value="<?php echo $editing_data['is_active']; ?>">
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">Salvar</button>
                <a href="list_dns.php" class="btn btn-secondary">Cancelar</a>
            </div>
        </form>
    </div>
<?php endif; ?>

<div class="mobile-scroll-tip">Arraste a tabela para o lado para ver vencimento, codigo, status e acoes.</div>

<div class="table-container">
    <?php if (empty($clients)): ?>
        <div class="empty-state">
            <div style="font-size: 64px;"></div>
            <h3>Nenhum cliente cadastrado</h3>
        
            <?php if ($can_create_client): ?>
                <a href="dns.php?novo=1" class="add-btn" style="margin-top:15px; display:inline-block;">novo Cliente</a>
            <?php endif; ?>
        </div>
    <?php else: ?>
        <table class="dns-table">
            <thead>
                <tr>
                    <th>Nome</th>
                    <th>Vencimento</th>
                    <th>Código</th>
                    <th>Status</th>
                    <th>Ações</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($clients as $client): ?>
                    <?php $expiry = format_client_expiry_for_panel($client); ?>
                    <tr class="<?php echo !$client['is_active'] ? 'inactive' : ''; ?> <?php echo $editing_id == $client['id'] ? 'editing' : ''; ?>">
                        <td data-label="Nome"><?php echo htmlspecialchars($client['name']); ?></td>
                        <td data-label="Vencimento">
                            <span class="expiry-stack">
                                <span class="expiry-date <?php echo htmlspecialchars($expiry['class']); ?>"><?php echo htmlspecialchars($expiry['date']); ?></span>
                                <span class="expiry-source"><?php echo htmlspecialchars($expiry['source']); ?></span>
                            </span>
                        </td>
                        <td data-label="Codigo" class="code-cell"><?php echo htmlspecialchars(format_activation_code($client['activation_code'] ?? '')); ?></td>
                        <td data-label="Status">
                            <span class="status-badge <?php echo $client['is_active'] ? 'status-active' : 'status-inactive'; ?>">
                                <?php echo $client['is_active'] ? 'Ativo' : 'Inativo'; ?>
                            </span>
                        </td>
                        <td data-label="Acoes">
                            <div class="action-btns">
                                <a href="?action=edit&id=<?php echo $client['id']; ?>"
                                   class="action-btn btn-edit"
                                   title="Editar">
                                    Editar
                                </a>

                                <?php if ($client['is_active']): ?>
                                    <a href="?action=deactivate&id=<?php echo $client['id']; ?>"
                                       class="action-btn btn-deactivate"
                                       onclick="return confirm('Desativar este cliente?')"
                                       title="Desativar">
                                        Desativar
                                    </a>
                                <?php else: ?>
                                    <a href="?action=activate&id=<?php echo $client['id']; ?>"
                                       class="action-btn btn-activate"
                                       title="Ativar">
                                        Ativar
                                    </a>
                                <?php endif; ?>

                                <a href="?action=delete&id=<?php echo $client['id']; ?>"
                                   class="action-btn btn-delete"
                                   onclick="return confirm('⚠️ ATENÇÃO! Excluir permanentemente este cliente?\n\nEsta ação NÃO pode ser desfeita!')"
                                   title="Excluir permanentemente">
                                    Excluir
                                </a>

                                <button type="button"
                                        class="action-btn btn-card"
                                        onclick="showClientCard(<?php echo (int)$client['id']; ?>, '<?php echo htmlspecialchars(format_activation_code($client['activation_code'] ?? ''), ENT_QUOTES); ?>', '<?php echo htmlspecialchars(format_client_expiry_for_panel($client)['date'], ENT_QUOTES); ?>')"
                                        title="Exibir card">
                                    Exibir card
                                </button>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<div id="cardModal" class="card-modal" aria-hidden="true">
    <div class="card-modal-backdrop" onclick="closeClientCard()"></div>
    <div class="card-modal-dialog" role="dialog" aria-modal="true" aria-labelledby="cardModalTitle">
        <button type="button" class="card-modal-close" onclick="closeClientCard()" aria-label="Fechar">&times;</button>

        <p id="cardModalExpiry" class="card-modal-code" style="margin-bottom:6px;"></p>
        <p id="cardModalCode" class="card-modal-code code-cell"></p>
        <div class="card-modal-image-wrap">
            <img id="cardModalImage" alt="Card de recarga do cliente">
        </div>
        <div class="card-modal-actions">
            <a id="cardModalDownload" href="#" class="btn btn-primary">Baixar card</a>
            <button type="button" id="cardModalShare" class="btn btn-primary" onclick="shareClientCard()">Compartilhar</button>
            <button type="button" class="btn btn-secondary" onclick="closeClientCard()">Fechar</button>
        </div>
    </div>
</div>

<script>
function syncExpiresSourceFields() {
    var source = document.getElementById('expires_source');
    var dateInput = document.getElementById('expires_at');
    if (!source || !dateInput) return;

    var manual = source.value === 'manual';
    dateInput.disabled = !manual;
    dateInput.required = manual;
}

document.addEventListener('DOMContentLoaded', function() {
    var source = document.getElementById('expires_source');
    if (source) {
        source.addEventListener('change', syncExpiresSourceFields);
        syncExpiresSourceFields();
    }
});

function showClientCard(id, code, expiry) {
    var modal = document.getElementById('cardModal');
    var img = document.getElementById('cardModalImage');
    var download = document.getElementById('cardModalDownload');
    var codeEl = document.getElementById('cardModalCode');
    var expiryEl = document.getElementById('cardModalExpiry');
    var shareBtn = document.getElementById('cardModalShare');
    var cardUrl = 'client_card.php?id=' + id + '&v=' + Date.now();

    expiryEl.textContent = 'Vencimento: ' + (expiry || '--/--/----');
    codeEl.textContent = code;
    img.src = cardUrl;
    download.href = 'client_card.php?id=' + id + '&download=1';
    shareBtn.setAttribute('data-card-url', 'client_card.php?id=' + id + '&download=1&share=1');
    shareBtn.setAttribute('data-card-code', code);
    shareBtn.setAttribute('data-card-expiry', expiry || '--/--/----');

    modal.classList.add('open');
    modal.setAttribute('aria-hidden', 'false');
    document.body.style.overflow = 'hidden';
}

async function shareClientCard() {
    var shareBtn = document.getElementById('cardModalShare');
    if (!shareBtn) return;

    var url = shareBtn.getAttribute('data-card-url');
    var code = shareBtn.getAttribute('data-card-code') || '';
    var expiry = shareBtn.getAttribute('data-card-expiry') || '--/--/----';

    if (!navigator.share || !navigator.canShare || !url) {
        alert('Compartilhamento nativo indisponivel neste navegador. Use o botao de baixar card PNG.');
        return;
    }

    try {
        shareBtn.disabled = true;
        shareBtn.textContent = 'Preparando...';

        var response = await fetch(url, { credentials: 'same-origin' });
        if (!response.ok) {
            throw new Error('Falha ao gerar a imagem do card.');
        }

        var blob = await response.blob();
        var file = new File([blob], 'card-tvexpress-' + code.replace(/\W+/g, '-') + '.png', { type: 'image/png' });
        var payload = {
            title: 'Card TVExpress',
            text: 'Codigo: ' + code + ' | Vencimento: ' + expiry,
            files: [file]
        };

        if (!navigator.canShare(payload)) {
            throw new Error('Este navegador nao suporta compartilhar imagem diretamente.');
        }

        await navigator.share(payload);
    } catch (error) {
        alert(error && error.message ? error.message : 'Nao foi possivel compartilhar o card.');
    } finally {
        shareBtn.disabled = false;
        shareBtn.textContent = 'Compartilhar';
    }
}

function closeClientCard() {
    var modal = document.getElementById('cardModal');
    modal.classList.remove('open');
    modal.setAttribute('aria-hidden', 'true');
    document.body.style.overflow = '';
    document.getElementById('cardModalImage').src = '';
    document.getElementById('cardModalShare').removeAttribute('data-card-url');
}

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeClientCard();
    }
});
</script>

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