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

$message = '';
$message_type = '';
$editing_id = (int)($_GET['edit'] ?? 0);
$editing_reseller = $editing_id > 0 ? get_reseller_by_id($editing_id) : null;
$show_form = isset($_GET['novo']) || $editing_reseller;

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

    if ($action === 'create') {
        $display_name = str_in($_POST['display_name'] ?? '');
        $username = str_in($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        $panel_expires_at = str_in($_POST['panel_expires_at'] ?? '');
        $client_limit = (int)($_POST['client_limit'] ?? 0);
        $whatsapp = str_in($_POST['reseller_whatsapp'] ?? '');

        if ($password !== $confirm_password) {
            $message = 'As senhas nao coincidem.';
            $message_type = 'error';
        } else {
            $result = create_reseller($display_name, $username, $password, $panel_expires_at, $client_limit, $whatsapp);
            $message = $result['message'] ?? ($result['ok'] ? 'Revenda criada com sucesso!' : 'Erro ao criar revenda.');
            $message_type = !empty($result['ok']) ? 'success' : 'error';
            if (!empty($result['ok'])) {
                $show_form = false;
            }
        }
    }

    if ($action === 'update') {
        $id = (int)($_POST['id'] ?? 0);
        $display_name = str_in($_POST['display_name'] ?? '');
        $panel_expires_at = str_in($_POST['panel_expires_at'] ?? '');
        $client_limit = (int)($_POST['client_limit'] ?? 0);
        $new_password = $_POST['new_password'] ?? '';
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        $whatsapp = str_in($_POST['reseller_whatsapp'] ?? '');

        $result = update_reseller($id, $display_name, $panel_expires_at, $client_limit, $is_active, $new_password, $whatsapp);
        $message = $result['message'] ?? ($result['ok'] ? 'Revenda atualizada com sucesso!' : 'Erro ao atualizar revenda.');
        $message_type = !empty($result['ok']) ? 'success' : 'error';
        if (!empty($result['ok'])) {
            $editing_id = 0;
            $editing_reseller = null;
            $show_form = false;
        } else {
            $editing_id = $id;
            $editing_reseller = get_reseller_by_id($id);
        }
    }

    if ($action === 'toggle_active') {
        $id = (int)($_POST['id'] ?? 0);
        $is_active = (int)($_POST['is_active'] ?? 0);
        $result = set_reseller_active($id, $is_active);
        $message = $result['message'] ?? 'Acao concluida.';
        $message_type = !empty($result['ok']) ? 'success' : 'error';
        $show_form = false;
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $result = delete_reseller_by_id($id);
        $message = $result['message'] ?? 'Acao concluida.';
        $message_type = !empty($result['ok']) ? 'success' : 'error';
        $show_form = false;
    }
}

$resellers = get_resellers();
?>

<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-bottom: 8px;
        background: var(--primary-bg);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
    
    .page-header p {
        color: #999;
        font-size: 14px;
    }
    
    .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;
    }
    
    .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);
    }

    .content-grid {
        display: block;
        width: 100%;
    }
    
    .card {
        background: #1a1a1a;
        padding: 30px;
        border-radius: 12px;
        border: 1px solid rgba(255, 255, 255, 0.1);
    }

    .form-card {
        max-width: 760px;
        margin-bottom: 25px;
    }

    .table-card {
        width: 100%;
        overflow: hidden;
    }

    .table-scroll {
        width: 100%;
        overflow-x: auto;
        -webkit-overflow-scrolling: touch;
    }
    
    .card h2 {
        font-size: 18px;
        margin-bottom: 20px;
        padding-bottom: 15px;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        color: #fff;
    }
    
    .form-group {
        margin-bottom: 20px;
    }
    
    .form-group label {
        display: block;
        margin-bottom: 8px;
        color: #fff;
        font-weight: 500;
        font-size: 14px;
    }
    
    .form-group input {
        width: 100%;
        padding: 12px 15px;
        background: #111;
        border: 1px solid rgba(255, 255, 255, 0.2);
        border-radius: 6px;
        color: #fff;
        font-size: 14px;
        transition: all 0.2s ease;
    }
    
    .form-group input:focus {
        outline: none;
        border-color: var(--primary-bg);
        box-shadow: 0 0 0 3px rgba(192, 57, 43, 0.1);
    }
    
    .submit-btn {
        background: var(--primary-bg);
        color: #fff;
        padding: 12px 30px;
        border: none;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s ease;
        width: 100%;
    }
    
    .submit-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }
    
    .users-table {
        width: 100%;
        min-width: 720px;
        border-collapse: collapse;
    }
    
    .users-table thead {
        background: #0a0a0a;
    }
    
    .users-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);
    }
    
    .users-table td {
        padding: 15px;
        font-size: 14px;
        color: #ccc;
        border-bottom: 1px solid rgba(255, 255, 255, 0.05);
    }
    
    .users-table tbody tr {
        transition: background 0.2s ease;
    }
    
    .users-table tbody tr:hover {
        background: rgba(255, 255, 255, 0.02);
    }
    
    .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;
    }

    .edit-link {
        color: #fff;
        text-decoration: none;
        font-weight: 700;
    }

    .action-btns {
        display: flex;
        gap: 6px;
        flex-wrap: wrap;
        align-items: center;
    }

    .action-btn {
        padding: 7px 12px;
        border-radius: 8px;
        font-size: 12px;
        text-decoration: none;
        display: inline-block;
        transition: all 0.2s ease;
        border: 1px solid;
        white-space: nowrap;
        font-weight: 800;
        cursor: pointer;
        font-family: inherit;
        line-height: 1.2;
    }

    .btn-edit {
        background: rgba(52, 152, 219, 0.1);
        color: #3498db;
        border-color: #3498db;
    }

    .btn-activate {
        background: rgba(46, 204, 113, 0.1);
        color: #2ecc71;
        border-color: #2ecc71;
    }

    .btn-deactivate {
        background: rgba(243, 156, 18, 0.1);
        color: #f39c12;
        border-color: #f39c12;
    }

    .btn-delete {
        background: rgba(231, 76, 60, 0.1);
        color: #e74c3c;
        border-color: #e74c3c;
    }

    .inline-action-form {
        display: inline;
        margin: 0;
    }
    
    @media (max-width: 768px) {
        .card {
            padding: 18px;
        }

        .users-table {
            font-size: 12px;
            min-width: 650px;
        }
        
        .users-table th,
        .users-table td {
            padding: 10px 8px;
        }
    }
</style>

<div class="page-header">
    <div>
        <h2>Revendas</h2>
 </div>
    <div>
        <?php if (!$show_form): ?>
            <a href="user_create.php?novo=1" class="add-btn">+ Revenda</a>
        <?php else: ?>
            <a href="user_create.php" class="add-btn">Ver revendas</a>
        <?php endif; ?>
    </div>
</div>

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

<div class="content-grid">
    <?php if ($show_form): ?>
    <div class="card form-card">
        <h2><?php echo $editing_reseller ? 'Editar Revenda' : 'Criar Revenda'; ?></h2>
        <form method="POST">
            <input type="hidden" name="action" value="<?php echo $editing_reseller ? 'update' : 'create'; ?>">
            <?php if ($editing_reseller): ?>
                <input type="hidden" name="id" value="<?php echo (int)$editing_reseller['id']; ?>">
            <?php endif; ?>

            <div class="form-group">
                <label for="display_name">Nome</label>
                <input type="text"
                       id="display_name"
                       name="display_name"
                       value="<?php echo htmlspecialchars($editing_reseller['display_name'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                       placeholder="Ex: Revenda Centro"
                       autocomplete="off"
                       required>
            </div>

            <div class="form-group">
                <label for="username">Usuario</label>
                <input type="text"
                       id="username"
                       name="username"
                       value="<?php echo htmlspecialchars($editing_reseller['username'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                       placeholder="Digite o login da revenda"
                       autocomplete="off"
                       minlength="3"
                       <?php echo $editing_reseller ? 'disabled' : ''; ?>
                       required>
            </div>
            
            <div class="form-group">
                <label for="password"><?php echo $editing_reseller ? 'Nova senha (opcional)' : 'Senha'; ?></label>
                <input type="password"
                       id="password"
                       name="<?php echo $editing_reseller ? 'new_password' : 'password'; ?>"
                       placeholder="<?php echo $editing_reseller ? 'Preencha apenas se quiser trocar' : 'Digite a senha'; ?>"
                       autocomplete="new-password"
                       minlength="6"
                       <?php echo $editing_reseller ? '' : 'required'; ?>>
            </div>

            <?php if (!$editing_reseller): ?>
                <div class="form-group">
                    <label for="confirm_password">Confirmar senha</label>
                    <input type="password"
                           id="confirm_password"
                           name="confirm_password"
                           placeholder="Digite novamente a senha"
                           autocomplete="new-password"
                           minlength="6"
                           required>
                </div>
            <?php endif; ?>

            <div class="form-group">
                <label for="panel_expires_at">Vencimento do painel</label>
                <input type="date"
                       id="panel_expires_at"
                       name="panel_expires_at"
                       value="<?php echo htmlspecialchars(!empty($editing_reseller['panel_expires_at']) ? date('Y-m-d', strtotime((string)$editing_reseller['panel_expires_at'])) : '', ENT_QUOTES, 'UTF-8'); ?>"
                       required>
            </div>

            <div class="form-group">
                <label for="client_limit">Limites Clientes/cards</label>
                <input type="number"
                       id="client_limit"
                       name="client_limit"
                       min="0"
                       value="<?php echo (int)($editing_reseller['client_limit'] ?? 0); ?>"
                       required>
            </div>

            <div class="form-group">
                <label for="reseller_whatsapp">WhatsApp da revenda</label>
                <input type="text"
                       id="reseller_whatsapp"
                       name="reseller_whatsapp"
                       value="<?php echo htmlspecialchars($editing_reseller['reseller_whatsapp'] ?? '', ENT_QUOTES, 'UTF-8'); ?>"
                       placeholder="Ex: 5571999999999"
                       autocomplete="off">
            </div>

            <?php if ($editing_reseller): ?>
                <div class="form-group">
                    <label style="display:flex; align-items:center; gap:8px;">
                        <input type="checkbox" name="is_active" value="1" <?php echo !empty($editing_reseller['is_active']) ? 'checked' : ''; ?> style="width:auto;">
                        Revenda ativa
                    </label>
                </div>
            <?php endif; ?>
            
            <button type="submit" class="submit-btn"><?php echo $editing_reseller ? 'Salvar revenda' : 'Criar revenda'; ?></button>
        </form>
    </div>
    <?php endif; ?>
    
    <div class="card table-card">
        <h2>Lista de Revendas</h2>
        <div class="table-scroll">
        <table class="users-table">
            <thead>
                <tr>
                    <th>Revenda</th>
                    <th>Login</th>
                    <th>WhatsApp</th>
                    <th>Vence</th>
                    <th>Uso</th>
                    <th>Status</th>
                    <th>Acao</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($resellers)): ?>
                    <tr>
                        <td colspan="7" style="text-align: center; padding: 40px; color: #666;">
                            Nenhuma revenda cadastrada.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($resellers as $u): ?>
                        <?php $summary = user_client_usage_summary($u); ?>
                        <tr>
                            <td><?php echo htmlspecialchars(user_display_name($u)); ?></td>
                            <td><?php echo htmlspecialchars($u['username']); ?></td>
                            <td><?php echo htmlspecialchars($u['reseller_whatsapp'] ?: '-'); ?></td>
                            <td><?php echo htmlspecialchars(user_panel_expiry_label($u)); ?></td>
                            <td><?php echo (int)$summary['used']; ?> / <?php echo (int)$summary['contracted']; ?></td>
                            <td>
                                <span class="status-badge <?php echo (!user_panel_is_expired($u) && $u['is_active']) ? 'status-active' : 'status-inactive'; ?>">
                                    <?php echo user_panel_is_expired($u) ? 'Vencido' : ($u['is_active'] ? 'Ativo' : 'Inativo'); ?>
                                </span>
                            </td>
                            <td>
                                <div class="action-btns">
                                    <a class="action-btn btn-edit" href="user_create.php?edit=<?php echo (int)$u['id']; ?>">Editar</a>

                                    <form method="post" class="inline-action-form">
                                        <input type="hidden" name="action" value="toggle_active">
                                        <input type="hidden" name="id" value="<?php echo (int)$u['id']; ?>">
                                        <input type="hidden" name="is_active" value="<?php echo !empty($u['is_active']) ? 0 : 1; ?>">
                                        <button type="submit" class="action-btn <?php echo !empty($u['is_active']) ? 'btn-deactivate' : 'btn-activate'; ?>">
                                            <?php echo !empty($u['is_active']) ? 'Desativar' : 'Ativar'; ?>
                                        </button>
                                    </form>

                                    <form method="post" class="inline-action-form" onsubmit="return confirm('Deletar esta revenda? Os clientes vinculados serao desativados.');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo (int)$u['id']; ?>">
                                        <button type="submit" class="action-btn btn-delete">Deletar</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
        </div>
    </div>
</div>

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