<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

include '../includes/header2.php';
require_once '../includes/DNSDatabase.php';
require_once 'sync_mac_consistency.php';

$seller_name = $_SESSION['seller_name'];
$dnsDB = DNSDatabase::getInstance();

$id = isset($_GET['update']) ? intval($_GET['update']) : 0;
if ($id == 0) {
    header('Location: index.php');
    exit();
}

$db = new SQLite3('../a/.eggziedb.db');
$user = $db->query("SELECT * FROM ibo WHERE id = $id");
$user_data = $user->fetchArray(SQLITE3_ASSOC);
if (!$user_data || $user_data['seller'] != $seller_name) {
    echo "<script>alert('Usuário não encontrado ou acesso negado.'); window.location.href='index.php';</script>";
    exit();
}

$today = date('Y-m-d');
$is_expired = ($user_data['expire_date'] < $today && $user_data['is_test'] == 0);
$is_test = ($user_data['is_test'] == 1);

// Edição normal
if (isset($_POST['submit'])) {
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $title = trim($_POST['title']);
    $dns = trim($_POST['dns']);
    $extra = trim($_POST['extra']);

    if (empty($username) || empty($password) || empty($title) || empty($dns) || empty($extra)) {
        echo "<script>alert('Preencha todos os campos!'); window.history.back();</script>";
        exit();
    }

    $sql = "UPDATE ibo SET 
                username = '" . SQLite3::escapeString($username) . "',
                password = '" . SQLite3::escapeString($password) . "',
                title = '" . SQLite3::escapeString($title) . "',
                url = '" . SQLite3::escapeString($dns) . "',
                extra = '" . SQLite3::escapeString($extra) . "'
            WHERE id = $id";
    if ($db->exec($sql)) {
        echo "<script>alert('Usuário atualizado!'); window.location.href='index.php';</script>";
    } else {
        echo "<script>alert('Erro ao atualizar: " . addslashes($db->lastErrorMsg()) . "'); window.history.back();</script>";
    }
    exit();
}

// Transferência (apenas para ativos não teste)
if (!$is_expired && !$is_test && isset($_POST['transfer_submit'])) {
    $new_mac = strtoupper(trim($_POST['new_mac']));
    $old_mac = $user_data['mac_address'];
    $expire_date_old = $user_data['expire_date'];
    $cliente_old = $user_data['extra'];
    $title_old = $user_data['title'];
    $username_old = $user_data['username'];
    $password_old = $user_data['password'];
    $dns_old = $user_data['url'];

    if (empty($new_mac) || !preg_match('/^([0-9A-F]{2}:){7}[0-9A-F]{2}$/', $new_mac)) {
        echo "<script>alert('MAC inválido'); window.history.back();</script>";
        exit();
    }

    $check_dest = $db->query("SELECT id, is_test, expire_date FROM ibo WHERE mac_address = '$new_mac' AND seller = '$seller_name' LIMIT 1");
    $dest_data = $check_dest->fetchArray(SQLITE3_ASSOC);
    if ($dest_data) {
        $is_test_dest = (int)$dest_data['is_test'];
        $expire_dest = $dest_data['expire_date'];
        if ($is_test_dest == 0 && $expire_dest >= $today) {
            echo "<script>alert('MAC destino já possui licença ATIVA ANUAL!'); window.history.back();</script>";
            exit();
        }
    }

    $db->exec('BEGIN IMMEDIATE');
    $expired_date = date('Y-m-d', strtotime('-1 day'));
    $db->exec("UPDATE ibo SET expire_date = '$expired_date', is_test = 0 WHERE mac_address = '$old_mac' AND seller = '$seller_name'");
    if ($dest_data) {
        $db->exec("DELETE FROM ibo WHERE mac_address = '$new_mac' AND seller = '$seller_name'");
    }
    $sql = "UPDATE ibo SET 
                mac_address = '" . SQLite3::escapeString($new_mac) . "',
                expire_date = '$expire_date_old',
                is_test = 0,
                extra = '" . SQLite3::escapeString($cliente_old) . "',
                title = '" . SQLite3::escapeString($title_old) . "',
                username = '" . SQLite3::escapeString($username_old) . "',
                password = '" . SQLite3::escapeString($password_old) . "',
                url = '" . SQLite3::escapeString($dns_old) . "'
            WHERE id = $id";
    if ($db->exec($sql)) {
        syncMacPlaylists($db, $new_mac, $seller_name);
        $db->exec('COMMIT');
        echo "<script>alert('Transferência concluída!'); window.location.href='index.php';</script>";
    } else {
        $db->exec('ROLLBACK');
        echo "<script>alert('Erro ao transferir'); window.history.back();</script>";
    }
    exit();
}

// Renovação (apenas para expirados)
if ($is_expired && isset($_POST['renew_submit'])) {
    // Verificar saldo de MACs
    $saldo_result = $db->query("SELECT macs FROM revenda WHERE usuario = '$seller_name'");
    $saldo_row = $saldo_result->fetchArray(SQLITE3_ASSOC);
    $macs_disponiveis = $saldo_row ? intval($saldo_row['macs']) : 0;

    if ($macs_disponiveis <= 0) {
        echo "<script>alert('Saldo insuficiente para renovar! Você precisa de pelo menos 1 MAC disponível.'); window.history.back();</script>";
        exit();
    }

    $db->exec('BEGIN IMMEDIATE');
    $new_expire = date('Y-m-d', strtotime('+1 year'));
    $sql = "UPDATE ibo SET expire_date = '$new_expire', is_test = 0 WHERE id = $id";
    if ($db->exec($sql)) {
        $new_balance = $macs_disponiveis - 1;
        $db->exec("UPDATE revenda SET macs = $new_balance WHERE usuario = '$seller_name'");
        syncMacPlaylists($db, $user_data['mac_address'], $seller_name);
        $db->exec('COMMIT');
        echo "<script>alert('Licença renovada! Nova validade: $new_expire. Saldo restante: $new_balance MACs.'); window.location.href='index.php';</script>";
    } else {
        $db->exec('ROLLBACK');
        echo "<script>alert('Erro ao renovar: " . addslashes($db->lastErrorMsg()) . "'); window.history.back();</script>";
    }
    exit();
}

$expire_date = $user_data['expire_date'];
$days_left = 0;
if ($expire_date && $expire_date != '0000-00-00' && !$is_expired) {
    $today_dt = new DateTime();
    $expire_dt = new DateTime($expire_date);
    $diff = $today_dt->diff($expire_dt);
    $days_left = $diff->days;
}
$dns_options = $dnsDB->getAll('revenda', $seller_name);
?>

<div class="container-fluid">
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-primary">Editar Usuário</h6>
        </div>
        <div class="card-body">
            <div class="alert alert-info">
                <strong>MAC:</strong> <?php echo htmlspecialchars($user_data['mac_address']); ?><br>
                <strong>Validade:</strong> <?php echo $expire_date; ?>
                <?php if (!$is_expired && !$is_test): ?>
                    (<?php echo $days_left; ?> dias restantes)
                <?php elseif ($is_expired): ?>
                    <span class="badge badge-danger">EXPIRADO</span>
                <?php elseif ($is_test): ?>
                    <span class="badge badge-warning">MODO TESTE</span>
                <?php endif; ?>
                <br>
                <?php if (!$is_expired && !$is_test): ?>
                    <button type="button" class="btn btn-info btn-sm mt-2" data-toggle="modal" data-target="#transferModal">Transferir Licença</button>
                <?php elseif ($is_expired): ?>
                    <button type="button" class="btn btn-success btn-sm mt-2" data-toggle="modal" data-target="#renewModal">Renovar Licença (Anual)</button>
                <?php else: ?>
                    <small class="text-muted">Modo teste não permite transferência/renovação.</small>
                <?php endif; ?>
            </div>
            <form method="post">
                <div class="form-group"><label>NOME DO SERVIDOR</label><input type="text" class="form-control" name="title" value="<?php echo htmlspecialchars($user_data['title']); ?>" required></div>
                <div class="form-group">
                    <label>DNS</label>
                    <select class="form-control" name="dns" required>
                        <?php if ($dns_options): while ($dns_row = $dns_options->fetchArray(SQLITE3_ASSOC)): ?>
                            <option value="<?php echo htmlspecialchars($dns_row['dns']); ?>" <?php echo $user_data['url'] == $dns_row['dns'] ? 'selected' : ''; ?>><?php echo htmlspecialchars($dns_row['nome']); ?></option>
                        <?php endwhile; endif; ?>
                    </select>
                </div>
                <div class="form-group"><label>NOME DO CLIENTE</label><input type="text" class="form-control" name="extra" value="<?php echo htmlspecialchars($user_data['extra']); ?>" required></div>
                <div class="form-group"><label>USUÁRIO</label><input type="text" class="form-control" name="username" value="<?php echo htmlspecialchars($user_data['username']); ?>" required></div>
                <div class="form-group"><label>SENHA</label><input type="text" class="form-control" name="password" value="<?php echo htmlspecialchars($user_data['password']); ?>" required></div>
                <button type="submit" name="submit" class="btn btn-primary">Salvar</button>
                <a href="index.php" class="btn btn-secondary">Cancelar</a>
            </form>
        </div>
    </div>
</div>

<!-- Modal Transferência -->
<div class="modal fade" id="transferModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header"><h5>Transferir Licença</h5><button type="button" class="close" data-dismiss="modal">&times;</button></div>
            <form method="post">
                <div class="modal-body">
                    <p>Transferir do MAC <strong><?php echo htmlspecialchars($user_data['mac_address']); ?></strong></p>
                    <div class="form-group"><label>Novo MAC:</label><input type="text" class="form-control" name="new_mac" id="new_mac" placeholder="00:11:22:33:44:55:66:77" required></div>
                </div>
                <div class="modal-footer"><button type="submit" name="transfer_submit" class="btn btn-primary">Transferir</button></div>
            </form>
        </div>
    </div>
</div>

<!-- Modal Renovação -->
<div class="modal fade" id="renewModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-success text-white"><h5>Renovar Licença</h5><button type="button" class="close text-white" data-dismiss="modal">&times;</button></div>
            <form method="post">
                <div class="modal-body">
                    <p>Renovar MAC <strong><?php echo htmlspecialchars($user_data['mac_address']); ?></strong></p>
                    <p>Consumirá <strong>1 MAC</strong> do seu saldo. Nova validade: +1 ano.</p>
                </div>
                <div class="modal-footer"><button type="submit" name="renew_submit" class="btn btn-success">Renovar</button></div>
            </form>
        </div>
    </div>
</div>

<script>
document.getElementById('new_mac')?.addEventListener('input', function(e) {
    var val = e.target.value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();
    if (val.length > 16) val = val.substring(0,16);
    var fmt = "";
    for (var i=0; i<val.length; i++) { fmt += val[i]; if ((i+1)%2===0 && i<val.length-1) fmt += ":"; }
    e.target.value = fmt;
});
</script>
<?php include '../includes/footer2.php'; ?>