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

$db = new SQLite3('a/.eggziedb.db');
$db->exec("PRAGMA foreign_keys = ON;");

// TOTAL CLIENTES COM LINK
$totalLinks = $db->querySingle("SELECT COUNT(*) FROM client_links");

// LISTAGEM
$linksResult = $db->query("
    SELECT 
        cl.id AS link_id,
        i.id AS client_id,
        i.title,
        i.mac_address,
        cl.url
    FROM client_links cl
    JOIN ibo i ON i.id = cl.ibo_id
    ORDER BY cl.id DESC
");

// PROCESSAR EXCLUSÃO
if (isset($_GET['delete'])) {
    $id = (int) $_GET['delete'];
    $stmt = $db->prepare("DELETE FROM client_links WHERE id = :id");
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $stmt->execute();
    header("Location: create_link.php");
    exit;
}

// PROCESSAR CADASTRO
$msg = '';
$success = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $mac   = strtolower(trim($_POST['mac'] ?? ''));
    $link  = trim($_POST['link'] ?? '');

    if ($mac && $link) {
        $stmt = $db->prepare("SELECT id FROM ibo WHERE mac_address = :mac LIMIT 1");
        $stmt->bindValue(':mac', $mac, SQLITE3_TEXT);
        $res = $stmt->execute()->fetchArray(SQLITE3_ASSOC);

        if ($res) {
            $stmt = $db->prepare("INSERT INTO client_links (ibo_id, tipo, url) VALUES (:id, 'pagamento', :url)");
            $stmt->bindValue(':id', $res['id'], SQLITE3_INTEGER);
            $stmt->bindValue(':url', $link, SQLITE3_TEXT);
            $stmt->execute();

            $msg = 'Link cadastrado com sucesso';
            $success = true;
        } else {
            $msg = 'Cliente não encontrado com este MAC';
        }
    } else {
        $msg = 'Preencha todos os campos';
    }
}

include 'includes/header.php';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<title>Links de Pagamento</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
    body{ font-family:"Segoe UI",sans-serif; background: radial-gradient(circle at top,#1b2a45,#03040a); color:#f0f4ff; padding:20px; }
    .wrapper{ max-width:1200px; margin:auto; }
    .card{ background:rgba(15,27,52,0.9); padding:25px; border-radius:18px; border:1px solid rgba(114,159,255,0.3); margin-bottom:20px; }
    .input{ width:100%; padding:12px; background:#090e1e; border:1px solid #7191e8; border-radius:8px; color:#fff; margin-bottom:15px; }
    .btn{ padding:12px; width:100%; border:none; border-radius:10px; background:linear-gradient(135deg,#52ffb8,#2fcc8a); font-weight:700; cursor:pointer; color:#050712; }
    table{ width:100%; border-collapse:collapse; margin-top:20px; }
    th,td{ padding:12px; border-bottom:1px solid rgba(114,159,255,.2); text-align:left; }
    .actions a{ margin-right:10px; color:#fff; text-decoration:none; }
    .actions a.delete{ color:#ff6b81; }
    .alert{ padding:15px; border-radius:10px; margin-bottom:20px; font-weight:bold; }
    .alert-success{ background:rgba(82,255,184,0.1); color:#52ffb8; border:1px solid #52ffb8; }
    .alert-danger{ background:rgba(255,82,82,0.1); color:#ff6b81; border:1px solid #ff6b81; }
</style>
</head>
<body>
<div class="wrapper">
    <div class="card">
        <h2><i class="fas fa-link"></i> Criar Link de Pagamento</h2>
        <?php if ($msg): ?>
            <div class="alert <?= $success ? 'alert-success' : 'alert-danger' ?>"><?= htmlspecialchars($msg) ?></div>
        <?php endif; ?>
        <form method="post">
            <label>MAC do Cliente</label>
            <input name="mac" class="input" placeholder="00:00:00:00:00:00" required>
            <label>Link de Pagamento</label>
            <input name="link" class="input" placeholder="https://..." required>
            <button type="submit" class="btn">Cadastrar Link</button>
        </form>
    </div>

    <div class="card">
        <h2><i class="fas fa-list"></i> Links Cadastrados (<?= $totalLinks ?>)</h2>
        <div style="overflow-x:auto;">
            <table>
                <thead>
                    <tr>
                        <th>Cliente</th>
                        <th>MAC</th>
                        <th>Link</th>
                        <th>Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($row = $linksResult->fetchArray(SQLITE3_ASSOC)): ?>
                    <tr>
                        <td><?= htmlspecialchars($row['title'] ?? 'Sem Nome') ?></td>
                        <td><?= htmlspecialchars($row['mac_address']) ?></td>
                        <td><a href="<?= htmlspecialchars($row['url']) ?>" target="_blank" style="color:#7eb4ff;"><?= htmlspecialchars($row['url']) ?></a></td>
                        <td class="actions">
                            <a href="client_link_edit.php?id=<?= $row['link_id'] ?>"><i class="fas fa-edit"></i></a>
                            <a class="delete" href="?delete=<?= $row['link_id'] ?>" onclick="return confirm('Excluir link?')">
                                <i class="fas fa-trash"></i>
                            </a>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>
<?php $db->close(); ?>
