<?php 
include ('includes/header.php');

$table_name = "menualuser";
$page = "clients.php";

// Lógica de búsqueda
$search = isset($_GET['search']) ? $_GET['search'] : '';
$where = "";
$params = [];

if ($userRole !== 'admin') {
    $where = "owner_id = :owner_id";
    $params[':owner_id'] = $currentUser['id'];
}

if (!empty($search)) {
    $where .= (!empty($where) ? " AND " : "") . "(username LIKE :search OR title LIKE :search)";
    $params[':search'] = "%$search%";
}

$res = $db->select($table_name, '*', $where, 'id DESC', $params);

// Acción masiva: Eliminar seleccionados
if (isset($_POST['bulk_delete']) && isset($_POST['selected_users'])) {
    foreach ($_POST['selected_users'] as $id) {
        $clientData = $db->select($table_name, '*', 'id = :id', '', [':id' => $id]);
        
        $check_where = "id = :id";
        $check_params = [':id' => $id];
        if ($userRole !== 'admin') {
            $check_where .= " AND owner_id = :owner_id";
            $check_params[':owner_id'] = $currentUser['id'];
        }
        
        if ($db->delete($table_name, $check_where, $check_params)) {
            if (!empty($clientData)) {
                logClientDeleted($db, $currentUser['id'], $id, $clientData[0]['username']);
            }
        }
    }
    echo "<script>window.location.href='".$page."?status=deleted'</script>";
}

// Crear nuevo cliente
if (isset($_POST['submit'])){
    unset($_POST['submit']);
    $duration = $_POST['duration'];
    
    // Determinar créditos y fecha de expiración según la duración
    if ($duration === 'demo') {
        $credits_needed = 0;
        $expire_date = date('Y-m-d H:i:s', strtotime("+2 hours"));
        $duration_text = "Demo 2 Horas";
    } else {
        $months = intval($duration);
        $credits_needed = $months;
        $expire_date = date('Y-m-d', strtotime("+$months months"));
        $duration_text = "$months Mes(es)";
    }
    
    // Verificar créditos si es reseller (demo es gratis)
    if ($userRole === 'reseller' && $credits_needed > 0) {
        if ($currentUser['credits'] < $credits_needed) {
            echo "<script>alert('No tienes créditos suficientes (Necesitas $credits_needed)'); window.location.href='".$page."'</script>";
            exit;
        }
        deductCredits($db, $currentUser['id'], $credits_needed, "Cliente creado: " . $_POST['username'] . " ($duration_text)", $currentUser['id']);
    }
    
    $insertData = [
        'title' => $_POST['title'],
        'username' => $_POST['username'],
        'password' => $_POST['password'],
        'expire_date' => $expire_date,
        'owner_id' => $currentUser['id'],
        'user_type' => 'client',
        'max_devices' => $_POST['max_devices']
    ];
    
    $db->insert($table_name, $insertData);
    $newClientId = $db->getLastInsertId();
    
    logClientCreated($db, $currentUser['id'], $newClientId, $_POST['username'], $duration_text, $credits_needed);
    
    $db->close();
    echo "<script>window.location.href='".$page."?status=created'</script>";
}

// Eliminar cliente individual
if(isset($_GET['delete'])){
    $clientData = $db->select($table_name, '*', 'id = :id', '', [':id' => $_GET['delete']]);
    
    $del_where = "id = :id";
    $del_params = [':id' => $_GET['delete']];
    if ($userRole !== 'admin') {
        $del_where .= " AND owner_id = :owner_id";
        $del_params[':owner_id'] = $currentUser['id'];
    }
    
    if ($db->delete($table_name, $del_where, $del_params)) {
        if (!empty($clientData)) {
            logClientDeleted($db, $currentUser['id'], $_GET['delete'], $clientData[0]['username']);
        }
    }
    echo "<script>window.location.href='".$page."?status=deleted'</script>";
}

?>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content bg-dark text-white">
            <div class="modal-header border-secondary">
                <h5 class="modal-title">Confirmar Eliminación</h5>
            </div>
            <div class="modal-body">
                ¿Realmente deseas eliminar este cliente? Esta acción no se puede deshacer.
            </div>
            <div class="modal-footer border-secondary">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                <a class="btn btn-danger btn-ok">Eliminar</a>
            </div>
        </div>
    </div>
</div>

<?php if (isset($_GET['create'])): ?>
    <div class="col-12 col-md-8 mx-auto">
        <div class="card">
            <div class="card-header">
                <h4 class="m-0 text-white"><i class="fa fa-user-plus"></i> Crear Cuenta de Cliente</h4>
            </div>
            <div class="card-body">
                <form method="post">
                    <div class="form-group">
                        <label>Título / Nombre</label>
                        <input type="text" class="form-control" name="title" placeholder="Ej: Cliente Juan" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Usuario</label>
                        <input type="text" class="form-control" name="username" placeholder="Usuario" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Contraseña</label>
                        <input type="text" class="form-control" name="password" placeholder="Contraseña" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Tiempo de Acceso</label>
                        <select class="form-control" name="duration" required>
                            <option value="demo">Demo 2 Horas - GRATIS</option>
                            <option value="1">1 Mes - 1 Crédito</option>
                            <option value="2">2 Meses - 2 Créditos</option>
                            <option value="3">3 Meses - 3 Créditos</option>
                            <option value="6">6 Meses - 6 Créditos</option>
                            <option value="12">12 Meses - 12 Créditos</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>Máximo de Dispositivos</label>
                        <input type="number" class="form-control" name="max_devices" value="1" min="1" required>
                    </div>
                    
                    <div class="mt-4">
                        <button type="submit" name="submit" class="btn btn-info btn-lg btn-block">
                            <i class="fa fa-save"></i> Guardar y Descontar
                        </button>
                        <a href="clients.php" class="btn btn-secondary btn-block mt-2">Volver</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
<?php else: ?>
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center flex-wrap">
            <h4 class="m-0 text-white"><i class="fa fa-users"></i> Gestión de Clientes</h4>
            <a href="?create" class="btn btn-sm btn-success mt-2 mt-md-0"><i class="fa fa-plus"></i> Nuevo</a>
        </div>
        <div class="card-body">
            <!-- Buscador -->
            <form method="get" class="mb-4">
                <div class="input-group">
                    <input type="text" name="search" class="form-control" placeholder="Buscar..." value="<?=$search?>">
                    <div class="input-group-append">
                        <button type="submit" class="btn btn-info">Buscar</button>
                    </div>
                </div>
            </form>

            <form method="post" id="bulk-form">
                <div class="d-flex justify-content-between mb-3 flex-wrap">
                    <button type="button" class="btn btn-sm btn-secondary mb-2" id="select-all">
                        <i class="fa fa-check-square-o"></i> Seleccionar
                    </button>
                    <button type="submit" name="bulk_delete" class="btn btn-sm btn-danger mb-2" onclick="return confirm('¿Eliminar seleccionados?')">
                        <i class="fa fa-trash"></i> Eliminar
                    </button>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th width="30"></th>
                                <th>Usuario</th>
                                <th>Pass</th>
                                <th>Vence</th>
                                <th>Estado</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($res as $row): 
                                $expiry = strtotime($row['expire_date']);
                                $diff = $expiry - time();
                                
                                if ($diff < 0) {
                                    $time_left = "Vencido";
                                    $badge_class = "badge-danger";
                                } elseif ($diff < 86400) {
                                    $hours = ceil($diff / 3600);
                                    $time_left = $hours . "h";
                                    $badge_class = "badge-warning";
                                } else {
                                    $days = ceil($diff / 86400);
                                    $time_left = $days . "d";
                                    $badge_class = $days > 5 ? "badge-success" : "badge-warning";
                                }
                            ?>
                            <tr>
                                <td>
                                    <input type="checkbox" name="selected_users[]" value="<?=$row['id']?>" class="user-checkbox">
                                </td>
                                <td>
                                    <strong><?=$row['username']?></strong>
                                    <br><small class="text-muted"><?=$row['title']?></small>
                                </td>
                                <td><?=$row['password']?></td>
                                <td><small><?=date('d/m/Y', strtotime($row['expire_date']))?></small></td>
                                <td><span class="badge <?=$badge_class?>"><?=$time_left?></span></td>
                                <td>
                                    <a href="#" data-href="?delete=<?=$row['id']?>" data-toggle="modal" data-target="#confirm-delete" class="btn btn-sm btn-danger"><i class="fa fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($res)): ?>
                                <tr><td colspan="6" class="text-center">No hay clientes.</td></tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </form>
        </div>
    </div>
<?php endif; ?>

<script>
document.getElementById('select-all').onclick = function() {
    var checkboxes = document.querySelectorAll('.user-checkbox');
    for (var checkbox of checkboxes) {
        checkbox.checked = !checkbox.checked;
    }
}
</script>

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