<?php
session_start();
if (!isset($_SESSION['eggzie_iboPlayer'])) {
    header('location:login.php');
    exit();
}

$db = new SQLite3('./a/.eggziedb.db');
$db->exec("CREATE TABLE IF NOT EXISTS gestor_clientes (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    nome VARCHAR(150) NOT NULL,
    usuario VARCHAR(100) NOT NULL,
    senha VARCHAR(100) NOT NULL,
    vencimento VARCHAR(10) NOT NULL,
    whatsapp VARCHAR(30) DEFAULT '',
    criado_em DATETIME DEFAULT CURRENT_TIMESTAMP
)");

function h($v) {
    return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

$mensagem = '';
$tipo = 'success';

if (isset($_GET['excluir'])) {
    $id = (int)$_GET['excluir'];
    $stmt = $db->prepare('DELETE FROM gestor_clientes WHERE id = :id');
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $stmt->execute();
    header('Location: gestor.php?msg=excluido');
    exit();
}

if (isset($_POST['salvar'])) {
    $id = (int)($_POST['id'] ?? 0);
    $nome = trim($_POST['nome'] ?? '');
    $usuario = trim($_POST['usuario'] ?? '');
    $senha = trim($_POST['senha'] ?? '');
    $vencimento = trim($_POST['vencimento'] ?? '');
    $whatsapp = trim($_POST['whatsapp'] ?? '');

    if ($nome === '' || $usuario === '' || $senha === '' || $vencimento === '') {
        $mensagem = 'Preencha nome, usuário, senha e vencimento.';
        $tipo = 'danger';
    } else {
        if ($id > 0) {
            $stmt = $db->prepare('UPDATE gestor_clientes SET nome=:nome, usuario=:usuario, senha=:senha, vencimento=:vencimento, whatsapp=:whatsapp WHERE id=:id');
            $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        } else {
            $stmt = $db->prepare('INSERT INTO gestor_clientes (nome, usuario, senha, vencimento, whatsapp) VALUES (:nome,:usuario,:senha,:vencimento,:whatsapp)');
        }
        $stmt->bindValue(':nome', $nome, SQLITE3_TEXT);
        $stmt->bindValue(':usuario', $usuario, SQLITE3_TEXT);
        $stmt->bindValue(':senha', $senha, SQLITE3_TEXT);
        $stmt->bindValue(':vencimento', $vencimento, SQLITE3_TEXT);
        $stmt->bindValue(':whatsapp', $whatsapp, SQLITE3_TEXT);
        $stmt->execute();
        header('Location: gestor.php?msg=' . ($id > 0 ? 'editado' : 'adicionado'));
        exit();
    }
}

if (isset($_GET['msg'])) {
    $mensagens = [
        'adicionado' => 'Cliente adicionado com sucesso!',
        'editado' => 'Cliente atualizado com sucesso!',
        'excluido' => 'Cliente excluído com sucesso!'
    ];
    if (isset($mensagens[$_GET['msg']])) $mensagem = $mensagens[$_GET['msg']];
}

$editar = null;
if (isset($_GET['editar'])) {
    $id = (int)$_GET['editar'];
    $stmt = $db->prepare('SELECT * FROM gestor_clientes WHERE id=:id');
    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
    $result = $stmt->execute();
    $editar = $result->fetchArray(SQLITE3_ASSOC) ?: null;
}

$busca = trim($_GET['busca'] ?? '');
if ($busca !== '') {
    $stmt = $db->prepare("SELECT * FROM gestor_clientes
        WHERE nome LIKE :busca OR usuario LIKE :busca OR vencimento LIKE :busca
        ORDER BY id DESC");
    $stmt->bindValue(':busca', '%' . $busca . '%', SQLITE3_TEXT);
    $result = $stmt->execute();
} else {
    $result = $db->query('SELECT * FROM gestor_clientes ORDER BY id DESC');
}

$clientes = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) $clientes[] = $row;

$total_clientes = (int)$db->querySingle('SELECT COUNT(*) FROM gestor_clientes');

include 'includes/header.php';
?>

<style>
.gestor-hero{background:linear-gradient(135deg,#0f172a,#0c4a6e);border:1px solid #164e63;border-radius:18px;padding:24px;box-shadow:0 12px 35px rgba(0,0,0,.25)}
.gestor-card{border-radius:18px!important;overflow:hidden}
.gestor-stat{border-radius:16px;padding:20px;background:linear-gradient(135deg,#0f172a,#172554);border:1px solid #1e3a8a}
.gestor-stat .num{font-size:30px;font-weight:800}
.gestor-table th{font-size:.75rem;text-transform:uppercase;color:#94a3b8!important;border-top:0!important}
.gestor-table td{vertical-align:middle!important;border-color:#1e293b!important}
.client-avatar{width:42px;height:42px;border-radius:12px;display:inline-flex;align-items:center;justify-content:center;background:rgba(14,165,233,.12);color:#38bdf8;font-weight:800}
.action-btn{width:38px;height:38px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;margin:2px}
.form-control{border-radius:10px!important}
</style>

<div class="container-fluid">
    <div class="gestor-hero mb-4">
        <div class="d-flex align-items-center justify-content-between flex-wrap">
            <div>
                <div class="text-info text-uppercase small font-weight-bold mb-1"><i class="fas fa-user-shield mr-1"></i> Gestão de Clientes</div>
                <h1 class="h3 mb-1 text-white">GESTOR</h1>
                <p class="mb-0 text-light">Cadastre, edite, exclua e acompanhe seus clientes em um só lugar.</p>
            </div>
            <div class="gestor-stat mt-3 mt-md-0">
                <div class="text-info small font-weight-bold">TOTAL DE CLIENTES</div>
                <div class="num text-white"><?= $total_clientes ?></div>
            </div>
        </div>
    </div>

    <?php if ($mensagem): ?>
        <div class="alert alert-<?= $tipo ?> shadow-sm"><?= h($mensagem) ?></div>
    <?php endif; ?>

    <div class="row">
        <div class="col-xl-4 mb-4">
            <div class="card gestor-card shadow">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-info">
                        <i class="fas fa-user-plus mr-2"></i><?= $editar ? 'Editar Cliente' : 'Adicionar Cliente' ?>
                    </h6>
                </div>
                <div class="card-body">
                    <form method="post">
                        <input type="hidden" name="id" value="<?= h($editar['id'] ?? 0) ?>">
                        <div class="form-group">
                            <label>Nome do cliente</label>
                            <input class="form-control" name="nome" required value="<?= h($editar['nome'] ?? '') ?>" placeholder="Ex.: João da Silva">
                        </div>
                        <div class="form-group">
                            <label>Usuário</label>
                            <input class="form-control" name="usuario" required value="<?= h($editar['usuario'] ?? '') ?>" placeholder="Usuário">
                        </div>
                        <div class="form-group">
                            <label>Senha</label>
                            <input class="form-control" name="senha" required value="<?= h($editar['senha'] ?? '') ?>" placeholder="Senha">
                        </div>
                        <div class="form-group">
                            <label>Data de vencimento</label>
                            <input type="date" class="form-control" name="vencimento" required value="<?= h($editar['vencimento'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                            <label>WhatsApp <span class="text-muted small">(opcional)</span></label>
                            <input class="form-control" name="whatsapp" value="<?= h($editar['whatsapp'] ?? '') ?>" placeholder="5511999999999">
                        </div>
                        <button class="btn btn-primary btn-block py-2" name="salvar" type="submit">
                            <i class="fas fa-save mr-2"></i><?= $editar ? 'Salvar Alterações' : 'Adicionar Cliente' ?>
                        </button>
                        <?php if ($editar): ?>
                            <a href="gestor.php" class="btn btn-secondary btn-block mt-2">Cancelar edição</a>
                        <?php endif; ?>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-xl-8 mb-4">
            <div class="card gestor-card shadow">
                <div class="card-header py-3 d-flex align-items-center justify-content-between flex-wrap">
                    <h6 class="m-0 font-weight-bold text-info"><i class="fas fa-users mr-2"></i>Clientes Cadastrados</h6>
                    <form method="get" class="mt-2 mt-md-0">
                        <div class="input-group input-group-sm">
                            <input class="form-control" name="busca" value="<?= h($busca) ?>" placeholder="Buscar cliente...">
                            <div class="input-group-append"><button class="btn btn-primary"><i class="fas fa-search"></i></button></div>
                        </div>
                    </form>
                </div>
                <div class="card-body p-0">
                    <?php if (!$clientes): ?>
                        <div class="text-center p-5">
                            <i class="fas fa-users fa-3x text-muted mb-3"></i>
                            <h5>Nenhum cliente cadastrado</h5>
                            <p class="text-muted mb-0">Use o formulário ao lado para adicionar o primeiro cliente.</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table gestor-table mb-0">
                                <thead>
                                    <tr><th>Cliente</th><th>Usuário</th><th>Senha</th><th>Vencimento</th><th class="text-center">Ações</th></tr>
                                </thead>
                                <tbody>
                                <?php foreach ($clientes as $c):
                                    $wa = preg_replace('/\D+/', '', $c['whatsapp'] ?? '');
                                    $venc = $c['vencimento'];
                                    $expirada = $venc !== '' && $venc < date('Y-m-d');
                                ?>
                                    <tr>
                                        <td><span class="client-avatar mr-2"><i class="fas fa-user"></i></span><strong><?= h($c['nome']) ?></strong></td>
                                        <td><?= h($c['usuario']) ?></td>
                                        <td><span class="badge badge-light"><?= h($c['senha']) ?></span></td>
                                        <td><span class="badge badge-<?= $expirada ? 'danger' : 'success' ?>"><?= h(date('d/m/Y', strtotime($venc))) ?></span></td>
                                        <td class="text-center text-nowrap">
                                            <?php if ($wa): ?>
                                                <a class="action-btn btn btn-success" target="_blank" href="https://wa.me/<?= h($wa) ?>?text=Ol%C3%A1%20<?= rawurlencode($c['nome']) ?>%2C%20estou%20entrando%20em%20contato%20sobre%20seu%20acesso." title="WhatsApp"><i class="fab fa-whatsapp"></i></a>
                                            <?php else: ?>
                                                <button class="action-btn btn btn-secondary" disabled title="Cadastre o WhatsApp"><i class="fab fa-whatsapp"></i></button>
                                            <?php endif; ?>
                                            <a class="action-btn btn btn-info" href="gestor.php?editar=<?= (int)$c['id'] ?>" title="Editar"><i class="fas fa-edit"></i></a>
                                            <a class="action-btn btn btn-danger" href="gestor.php?excluir=<?= (int)$c['id'] ?>" onclick="return confirm('Excluir este cliente?')" title="Excluir"><i class="fas fa-trash"></i></a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
