<?php
require_once __DIR__ . '/includes/header.php';

if (!isset($_SESSION['loggedin'], $_SESSION['name'], $_SESSION['role'])) {
    header("Location: index.php");
    exit;
}

$currentUser = $_SESSION['name'];
$role = $_SESSION['role'];

if (!in_array($role, ['master','super-reseller','reseller'], true)) {
    die('Acceso denegado');
}

$dbFile = __DIR__ . '/api/.db.db';
ensure_codes_schema($dbFile);

function randomChar() {
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    return $chars[random_int(0, strlen($chars) - 1)];
}

function getScopedCodeById(SQLiteWrapper $db, $role, $currentUser, $id) {
    if ($role === 'master') {
        $rows = $db->select('codes', '*', "id = :id AND owner != 'trial'", '', [':id' => $id]);
        return $rows ? $rows[0] : null;
    }

    $owners = get_visible_client_owners($db, $role, $currentUser);
    if (!$owners) return null;
    $in = build_in_clause_params($owners, ':o');
    $params = array_merge([':id' => $id], $in['params']);
    $rows = $db->select('codes', '*', "id = :id AND owner IN ({$in['sql']}) AND owner != 'trial'", '', $params);
    return $rows ? $rows[0] : null;
}

if (isset($_GET['block']) || isset($_GET['unblock']) || isset($_GET['delete'])) {
    $id = (int)($_GET['block'] ?? $_GET['unblock'] ?? $_GET['delete']);
    $row = getScopedCodeById($db, $role, $currentUser, $id);
    if ($row) {
        if (isset($_GET['delete'])) {
            $db->delete('codes', 'id = :id', [':id' => $id]);
        } else {
            $currentCode = $row['code'] ?? '';
            if (isset($_GET['block'])) {
                if (strlen($currentCode) === 6) {
                    $newCode = $currentCode . randomChar();
                    $db->update('codes', ['status' => 'blocked', 'code' => $newCode], 'id = :id', [':id' => $id]);
                } else {
                    $db->update('codes', ['status' => 'blocked'], 'id = :id', [':id' => $id]);
                }
            } else {
                if (strlen($currentCode) === 7) {
                    $db->update('codes', ['status' => 'active', 'code' => substr($currentCode, 0, 6)], 'id = :id', [':id' => $id]);
                } else {
                    $db->update('codes', ['status' => 'active'], 'id = :id', [':id' => $id]);
                }
            }
        }
    }
    header('Location: clients.php');
    exit;
}

$myCredits = ($role === 'master') ? -1 : (($db->select('menualuser', 'credits', 'username = :u', '', [':u' => $currentUser])[0]['credits'] ?? 0));

if ($role === 'master') {
    $codes = $db->select('codes', '*', "owner != 'trial'", 'created_at DESC');
} else {
    $owners = get_visible_client_owners($db, $role, $currentUser);
    $in = build_in_clause_params($owners, ':owner');
    $codes = $in['sql'] ? $db->select('codes', '*', "owner IN ({$in['sql']}) AND owner != 'trial'", 'created_at DESC', $in['params']) : [];
}

$totalClients = count($codes);
$activeClients = 0;
$blockedClients = 0;
$expiredClients = 0;

foreach ($codes as $c) {
    $status = $c['status'] ?? 'active';
    $expTs = !empty($c['expires_at']) ? strtotime($c['expires_at']) : 0;
    $expired = ($expTs && $expTs < time());
    if ($status === 'blocked') $blockedClients++;
    elseif ($expired) $expiredClients++;
    else $activeClients++;
}

$showOwnerColumn = in_array($role, ['master', 'super-reseller'], true);
$downloadUrl = (string) settings_get($db, 'app_download_url', '');
$downloaderCode = (string) settings_get($db, 'app_downloader_code', '');
?>

<div class="col-md-12 mx-auto">
<div class="card text-white" style="background:#1a1a1a">
<div class="card-header d-flex justify-content-between align-items-center">
    <div>
        <h3><i class="fa fa-users"></i> Gestión de Clientes</h3>
        <small>Clientes visibles para <?=htmlspecialchars($currentUser)?></small>
    </div>
    <a href="addclient.php" class="btn btn-info">
        <i class="fa fa-plus"></i> Registrar Nuevo Cliente
    </a>
</div>

<div class="card-body">

<?php if ($role !== 'master'): ?>
<div class="alert alert-dark d-flex justify-content-between align-items-center">
    <span><i class="fa fa-coins"></i> Créditos disponibles: <b><?=credits_display($myCredits)?></b></span>
    <a href="addclient.php" class="btn btn-sm btn-success">
        <i class="fa fa-user-plus"></i> Usar Crédito
    </a>
</div>
<?php endif; ?>

<div class="row mb-4">
    <div class="col-md-3"><div class="card bg-dark border-info"><div class="card-body text-center"><h4 class="text-info"><?=$totalClients?></h4><small class="text-muted">Total Clientes</small></div></div></div>
    <div class="col-md-3"><div class="card bg-dark border-success"><div class="card-body text-center"><h4 class="text-success"><?=$activeClients?></h4><small class="text-muted">Activos</small></div></div></div>
    <div class="col-md-3"><div class="card bg-dark border-warning"><div class="card-body text-center"><h4 class="text-warning"><?=$blockedClients?></h4><small class="text-muted">Bloqueados</small></div></div></div>
    <div class="col-md-3"><div class="card bg-dark border-danger"><div class="card-body text-center"><h4 class="text-danger"><?=$expiredClients?></h4><small class="text-muted">Expirados</small></div></div></div>
</div>

<div class="row mb-3">
    <div class="col-md-8"><input type="text" class="form-control" placeholder="🔍 Buscar por código, cliente, whatsapp o reseller..." id="searchBox"></div>
    <div class="col-md-4">
        <select class="form-control" id="filterStatus">
            <option value="">Todos los estados</option>
            <option value="active">Activos</option>
            <option value="blocked">Bloqueados</option>
            <option value="expired">Expirados</option>
        </select>
    </div>
</div>

<div class="table-responsive">
<table class="table table-dark table-hover" id="codesTable">
<thead>
<tr>
    <th><i class="fa fa-key"></i> Código</th>
    <th><i class="fa fa-user"></i> Cliente</th>
    <th><i class="fa fa-phone"></i> WhatsApp</th>
    <?php if ($showOwnerColumn): ?><th><i class="fa fa-user-tie"></i> Revendedor</th><?php endif; ?>
    <th><i class="fa fa-calendar"></i> Vencimiento</th>
    <th><i class="fa fa-info-circle"></i> Estado</th>
    <th><i class="fa fa-cog"></i> Acciones</th>
</tr>
</thead>
<tbody>
<?php if (!$codes): ?>
<tr><td colspan="<?= $showOwnerColumn ? '7' : '6' ?>" class="text-center py-5">No hay clientes registrados en tu alcance.</td></tr>
<?php else: ?>
<?php foreach ($codes as $c):
    $expRaw = $c['expires_at'] ?? '';
    $expTs = $expRaw ? strtotime($expRaw) : 0;
    $expired = ($expTs && $expTs < time());
    $days = $expTs ? floor(($expTs - time()) / 86400) : 0;
    $status = $c['status'] ?? 'active';
    $clientName = $c['client_name'] ?? 'Sin nombre';
    $clientWhatsapp = $c['client_whatsapp'] ?? 'Sin WhatsApp';
    $realStatus = ($expired && $status !== 'blocked') ? 'expired' : $status;
?>
<tr data-status="<?=htmlspecialchars($realStatus)?>">
    <td><strong class="text-info"><?=htmlspecialchars($c['code'])?></strong><br><small class="text-muted"><?=htmlspecialchars($c['created_at'] ?? '-')?></small></td>
    <td><strong><?=htmlspecialchars($clientName)?></strong></td>
    <td><?php if ($clientWhatsapp !== 'Sin WhatsApp' && $clientWhatsapp !== ''): ?><a href="https://wa.me/<?=htmlspecialchars(preg_replace('/\D+/', '', $clientWhatsapp))?>" target="_blank" class="text-success"><?=htmlspecialchars($clientWhatsapp)?></a><?php else: ?><span class="text-muted">Sin WhatsApp</span><?php endif; ?></td>
    <?php if ($showOwnerColumn): ?><td><span class="badge bg-secondary"><?=htmlspecialchars($c['owner'] ?? '-')?></span></td><?php endif; ?>
    <td>
        <?=htmlspecialchars($expRaw ?: '-')?><br>
        <?php if($status==='blocked'): ?>
            <span class="badge bg-warning">Bloqueado</span>
        <?php elseif($expired): ?>
            <span class="badge bg-danger">Expirado</span>
        <?php else: ?>
            <span class="badge <?= $days <= 3 ? 'bg-danger' : ($days <= 7 ? 'bg-warning' : 'bg-success') ?>"><?=max(0, (int)$days)?> días</span>
        <?php endif; ?>
    </td>
    <td>
        <?php if($status==='blocked'): ?>
            <span class="badge bg-warning">Bloqueado</span>
        <?php elseif($expired): ?>
            <span class="badge bg-danger">Expirado</span>
        <?php else: ?>
            <span class="badge bg-success">Activo</span>
        <?php endif; ?>
    </td>
    <td>
        <div class="btn-group" role="group">
            <button class="btn btn-sm btn-info" onclick="copyCode('<?=htmlspecialchars($c['code'])?>')" title="Copiar código"><i class="fa fa-copy"></i></button>
            <?php if ($clientWhatsapp !== 'Sin WhatsApp' && $clientWhatsapp !== ''): ?>
                <button class="btn btn-sm btn-success" onclick="shareClientWhatsapp(<?=json_encode($clientWhatsapp, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>, <?=json_encode($clientName, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>, <?=json_encode((string)($c['code'] ?? ''), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>, <?=json_encode($expRaw ?: '-', JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>)" title="Compartir por WhatsApp"><i class="fa fa-whatsapp"></i></button>
            <?php endif; ?>
            <?php if($status==='active'): ?>
                <a href="?block=<?=$c['id']?>" class="btn btn-sm btn-warning" onclick="return confirm('¿Bloquear este cliente?')"><i class="fa fa-ban"></i></a>
            <?php else: ?>
                <a href="?unblock=<?=$c['id']?>" class="btn btn-sm btn-success" onclick="return confirm('¿Desbloquear este cliente?')"><i class="fa fa-check"></i></a>
            <?php endif; ?>
            <a href="editclient.php?id=<?=$c['id']?>" class="btn btn-sm btn-primary"><i class="fa fa-edit"></i></a>
            <a href="?delete=<?=$c['id']?>" class="btn btn-sm btn-danger" onclick="return confirm('¿Eliminar este cliente?')"><i class="fa fa-trash"></i></a>
        </div>
    </td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>

<?php if ($codes): ?>
<div class="text-muted small mt-3"><i class="fa fa-info-circle"></i> Mostrando <?=count($codes)?> cliente(s). Los códigos trial públicos no se muestran aquí.</div>
<?php endif; ?>

</div>
</div>
</div>

<script>
const shareSettings = {
    downloadUrl: <?=json_encode($downloadUrl, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>,
    downloaderCode: <?=json_encode($downloaderCode, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)?>
};
function copyCode(code) {
    navigator.clipboard.writeText(code).then(function() {
        alert('Código copiado: ' + code);
    });
}
function buildWhatsAppUrl(phone, text) {
    var cleanPhone = String(phone || '').replace(/\D+/g, '');
    var encoded = encodeURIComponent(text);
    if (cleanPhone.length >= 10) {
        return 'https://wa.me/' + cleanPhone + '?text=' + encoded;
    }
    return 'https://wa.me/?text=' + encoded;
}
function shareClientWhatsapp(phone, client, code, expire) {
    var parts = [];
    parts.push('Hola ' + client + ', aquí tienes tus datos de acceso:');
    parts.push('Codigo de acceso: ' + code);
    parts.push('Fecha de expiracion: ' + expire);
    if (shareSettings.downloadUrl) parts.push('Link de descarga: ' + shareSettings.downloadUrl);
    if (shareSettings.downloaderCode) parts.push('Codigo downloader: ' + shareSettings.downloaderCode);
    var text = parts.join('\n');
    var popup = window.open(buildWhatsAppUrl(phone, text), '_blank');
    if (!popup || popup.closed || typeof popup.closed === 'undefined') {
        navigator.clipboard.writeText(text).then(function(){
            alert('No se pudo abrir WhatsApp automáticamente. El mensaje fue copiado.');
        }).catch(function(){
            alert('No se pudo abrir WhatsApp automáticamente.');
        });
    }
}
document.getElementById('searchBox').addEventListener('keyup', function() {
    const value = this.value.toLowerCase();
    const filterStatus = document.getElementById('filterStatus').value;
    document.querySelectorAll('#codesTable tbody tr').forEach(function(row) {
        const text = row.innerText.toLowerCase();
        const status = row.getAttribute('data-status');
        row.style.display = (text.includes(value) && (!filterStatus || status === filterStatus)) ? '' : 'none';
    });
});
document.getElementById('filterStatus').addEventListener('change', function() {
    document.getElementById('searchBox').dispatchEvent(new Event('keyup'));
});
</script>

<style>
.btn-group { display:flex; gap:2px; }
.table-hover tbody tr:hover { background-color: rgba(255,255,255,.05); }
.badge { padding:6px 12px; font-size:.85rem; }
</style>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
