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

error_reporting(E_ALL);
ini_set('display_errors', 1);

/* =======================
SEGURIDAD
======================= */
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'])) {
    die("Acceso denegado");
}

/* =======================
REPARAR TABLA CODES
======================= */
$dbFile = __DIR__ . '/../api/.db.db';

if (file_exists($dbFile)) {
    $sqlite = new SQLite3($dbFile);

    function columnExists($sqlite,$table,$column){
        $result = $sqlite->query("PRAGMA table_info($table)");
        while($row = $result->fetchArray(SQLITE3_ASSOC)){
            if ($row['name'] == $column) return true;
        }
        return false;
    }

    if (!columnExists($sqlite,'codes','client_name')) {
        $sqlite->exec("ALTER TABLE codes ADD COLUMN client_name TEXT");
    }

    if (!columnExists($sqlite,'codes','client_whatsapp')) {
        $sqlite->exec("ALTER TABLE codes ADD COLUMN client_whatsapp TEXT");
    }

    if (!columnExists($sqlite,'codes','status')) {
        $sqlite->exec("ALTER TABLE codes ADD COLUMN status TEXT DEFAULT 'active'");
    }
}

/* =======================
ACCIONES: BLOQUEAR / DESBLOQUEAR / ELIMINAR
======================= */
// Función para generar carácter aleatorio
function randomChar() {
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    return $chars[random_int(0, strlen($chars) - 1)];
}

/* =======================
BLOQUEAR
======================= */
if(isset($_GET['block'])){
    $id = (int)$_GET['block'];

    // Obtener código actual
    $row = $db->select('codes','code','id = :id','',[':id'=>$id]);
    if($row){
        $currentCode = $row[0]['code'];

        // Evitar agregar más de un carácter
        if(strlen($currentCode) == 6){
            $newCode = $currentCode . randomChar();

            // Verificar que no exista
            $exists = $db->select('codes','id','code = :c','',[':c'=>$newCode]);
            if(!$exists){
                $db->update('codes',[
                    'status'=>'blocked',
                    'code'=>$newCode
                ],'id = :id',[':id'=>$id]);
            }
        } else {
            // Solo cambiar estado si ya está modificado
            $db->update('codes',['status'=>'blocked'],'id = :id',[':id'=>$id]);
        }
    }

    header("Location: clients.php");
    exit;
}

/* =======================
DESBLOQUEAR
======================= */
if(isset($_GET['unblock'])){
    $id = (int)$_GET['unblock'];

    // Obtener código actual
    $row = $db->select('codes','code','id = :id','',[':id'=>$id]);
    if($row){
        $currentCode = $row[0]['code'];

        // Si tiene 7 caracteres → quitar el último
        if(strlen($currentCode) == 7){
            $originalCode = substr($currentCode, 0, 6);

            $db->update('codes',[
                'status'=>'active',
                'code'=>$originalCode
            ],'id = :id',[':id'=>$id]);
        } else {
            // Solo cambiar estado
            $db->update('codes',['status'=>'active'],'id = :id',[':id'=>$id]);
        }
    }

    header("Location: clients.php");
    exit;
}

if(isset($_GET['delete'])){
    $id=(int)$_GET['delete'];
    $db->delete('codes','id = :id',[':id'=>$id]);
    header("Location: clients.php"); exit;
}

/* =======================
OBTENER CREDITOS
======================= */
$myCredits = 0;
if ($role !== 'master') {
    $me = $db->select('menualuser','credits','username = :u','',[':u' => $currentUser]);
    $myCredits = (int)($me[0]['credits'] ?? 0);
}

/* =======================
LISTAR CODIGOS (EXCLUYENDO TRIALS)
======================= */
if ($role === 'master') {
    // Master ve todos los códigos EXCEPTO los de trial
    $codes = $db->select('codes','*',"owner != 'trial'",'created_at DESC');
} else {
    // Resellers solo ven sus propios códigos (que nunca deberían ser trial)
    $codes = $db->select('codes','*',"owner = :o AND owner != 'trial'",'created_at DESC',[':o'=>$currentUser]);
}

/* =======================
ESTADÍSTICAS
======================= */
$totalClients = count($codes);
$activeClients = 0;
$blockedClients = 0;
$expiredClients = 0;

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

<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>Administración de clientes registrados</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><?=$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; ?>

<!-- Estadísticas -->
<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>

<!-- Filtros -->
<div class="row mb-3">
    <div class="col-md-8">
        <input type="text" class="form-control" placeholder="🔍 Buscar por código, cliente o whatsapp..." 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 ($role === 'master'): ?><th><i class="fa fa-user-tie"></i> Reseller</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="<?= $role === 'master' ? '7' : '6' ?>" class="text-center py-5">
        <i class="fa fa-inbox fa-3x text-muted mb-3"></i>
        <p class="text-muted">No hay clientes registrados</p>
        <a href="addclient.php" class="btn btn-info mt-2">
            <i class="fa fa-plus"></i> Registrar Primer Cliente
        </a>
    </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';
    
    // Determinar estado real
    $realStatus = $status;
    if ($expired && $status !== 'blocked') {
        $realStatus = 'expired';
    }
?>
<tr data-status="<?=htmlspecialchars($realStatus)?>">
    <td>
        <strong class="text-info"><?=htmlspecialchars($c['code'])?></strong><br>
        <small class="text-muted">
            <i class="fa fa-clock"></i> <?=htmlspecialchars($c['created_at'] ?? '-')?>
        </small>
    </td>
    <td>
        <strong><?=htmlspecialchars($clientName)?></strong>
    </td>
    <td>
        <?php if ($clientWhatsapp !== 'Sin WhatsApp'): ?>
            <a href="https://wa.me/<?=htmlspecialchars($clientWhatsapp)?>" target="_blank" class="text-success">
                <i class="fab fa-whatsapp"></i> <?=htmlspecialchars($clientWhatsapp)?>
            </a>
        <?php else: ?>
            <span class="text-muted">Sin WhatsApp</span>
        <?php endif; ?>
    </td>
    <?php if ($role === 'master'): ?>
    <td>
        <span class="badge bg-secondary">
            <i class="fa fa-user"></i> <?=htmlspecialchars($c['owner'] ?? '-')?>
        </span>
    </td>
    <?php endif; ?>
    <td>
        <?=htmlspecialchars($expRaw ?: '-')?><br>
        <?php if(!$expired): ?>
            <?php if($days > 7): ?>
                <span class="badge bg-success">
                    <i class="fa fa-check-circle"></i> <?=$days?> días
                </span>
            <?php elseif($days > 3): ?>
                <span class="badge bg-warning">
                    <i class="fa fa-exclamation-triangle"></i> <?=$days?> días
                </span>
            <?php else: ?>
                <span class="badge bg-danger">
                    <i class="fa fa-clock"></i> <?=$days?> días
                </span>
            <?php endif; ?>
        <?php else: ?>
            <span class="badge bg-danger">
                <i class="fa fa-times-circle"></i> Expirado
            </span>
        <?php endif; ?>
    </td>
    <td>
        <?php if($status=='blocked'): ?>
            <span class="badge bg-warning">
                <i class="fa fa-ban"></i> Bloqueado
            </span>
        <?php elseif($expired): ?>
            <span class="badge bg-danger">
                <i class="fa fa-times-circle"></i> Expirado
            </span>
        <?php else: ?>
            <span class="badge bg-success">
                <i class="fa fa-check-circle"></i> Activo
            </span>
        <?php endif; ?>
    </td>
    <td>
        <div class="btn-group" role="group">
            <!-- WhatsApp -->
            <?php if ($clientWhatsapp !== 'Sin WhatsApp'): ?>
            <button class="btn btn-sm btn-success" 
                    onclick="sendWhatsApp('<?=htmlspecialchars($c['code'])?>','<?=htmlspecialchars($expRaw)?>','<?=htmlspecialchars($clientWhatsapp)?>','<?=htmlspecialchars($clientName)?>')"
                    title="Enviar por WhatsApp">
                <i class="fab fa-whatsapp"></i>
            </button>
            <?php endif; ?>
            
            <!-- Copiar -->
            <button class="btn btn-sm btn-info" 
                    onclick="copyCode('<?=htmlspecialchars($c['code'])?>')"
                    title="Copiar código">
                <i class="fa fa-copy"></i>
            </button>
            
            <!-- Bloquear / Desbloquear -->
            <?php if($status=='active'): ?>
                <a href="?block=<?=$c['id']?>" 
                   class="btn btn-sm btn-warning" 
                   onclick="return confirm('¿Bloquear este cliente?')"
                   title="Bloquear">
                    <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?')"
                   title="Desbloquear">
                    <i class="fa fa-check"></i>
                </a>
            <?php endif; ?>
            
            <!-- Editar -->
            <a href="editclient.php?id=<?=$c['id']?>" 
               class="btn btn-sm btn-primary"
               title="Editar">
                <i class="fa fa-edit"></i>
            </a>
            
            <!-- Eliminar -->
            <a href="?delete=<?=$c['id']?>" 
               class="btn btn-sm btn-danger" 
               onclick="return confirm('¿Eliminar este cliente? Esta acción no se puede deshacer.')"
               title="Eliminar">
                <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) registrado(s). 
    Los códigos de prueba (trial) no se muestran en esta lista.
</div>
<?php endif; ?>

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

<script>
// Función para enviar por WhatsApp
function sendWhatsApp(code, expire, phone, name) {
    if (!phone || phone === 'Sin WhatsApp') {
        alert("Este cliente no tiene WhatsApp registrado");
        return;
    }
    
    const msg = "🎬 *Datos de Acceso MyTube Premium*\n\n" +
                "👤 Cliente: " + name + "\n" +
                "🔑 Código: *" + code + "*\n" +
                "📅 Vencimiento: " + expire + "\n\n" +
                "¡Gracias por tu preferencia!";
    
    const url = "https://wa.me/" + phone.replace(/\D/g, '') + "?text=" + encodeURIComponent(msg);
    window.open(url, "_blank");
}

// Función para copiar código
function copyCode(code) {
    navigator.clipboard.writeText(code).then(function() {
        // Crear notificación temporal
        const notification = document.createElement('div');
        notification.className = 'alert alert-success position-fixed top-0 start-50 translate-middle-x mt-3';
        notification.style.zIndex = '9999';
        notification.innerHTML = '<i class="fa fa-check-circle"></i> Código copiado: <strong>' + code + '</strong>';
        document.body.appendChild(notification);
        
        setTimeout(function() {
            notification.remove();
        }, 2000);
    }).catch(function(err) {
        alert("Error al copiar: " + err);
    });
}

// Búsqueda en tiempo real
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');
        
        const matchesSearch = text.includes(value);
        const matchesFilter = !filterStatus || status === filterStatus;
        
        row.style.display = (matchesSearch && matchesFilter) ? "" : "none";
    });
});

// Filtro por estado
document.getElementById("filterStatus").addEventListener("change", function() {
    const searchBox = document.getElementById("searchBox");
    searchBox.dispatchEvent(new Event('keyup'));
});

// Actualizar cada 30 segundos para refrescar estados
setInterval(function() {
    const currentScroll = window.scrollY;
    location.reload();
    window.scrollTo(0, currentScroll);
}, 30000);
</script>

<style>
.btn-group {
    display: flex;
    gap: 2px;
}

.btn-group .btn {
    border-radius: 4px !important;
}

.table-hover tbody tr:hover {
    background-color: rgba(255, 255, 255, 0.05);
}

.badge {
    padding: 6px 12px;
    font-size: 0.85rem;
}

@media (max-width: 768px) {
    .btn-group {
        flex-wrap: wrap;
    }
    
    .table-responsive {
        font-size: 0.85rem;
    }
}
</style>

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