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

$page = "audit.php";

// Filtros
$filter_user = isset($_GET['user']) ? $_GET['user'] : '';
$filter_action = isset($_GET['action']) ? $_GET['action'] : '';
$filter_entity = isset($_GET['entity']) ? $_GET['entity'] : '';
$filter_date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$filter_date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Obtener estadísticas generales
$stats = getAuditStats($db, $userRole === 'admin' ? null : $currentUser['id']);

// Obtener lista de usuarios para filtro (solo admin)
$users = [];
if ($userRole === 'admin') {
    $users = $db->select('user', 'id, username, role', '', 'username ASC');
}

// Construir consulta de logs de actividad
$where_conditions = [];
$params = [];

if ($userRole !== 'admin') {
    $where_conditions[] = "user_id = :current_user";
    $params[':current_user'] = $currentUser['id'];
}

if (!empty($filter_user)) {
    $where_conditions[] = "user_id = :filter_user";
    $params[':filter_user'] = $filter_user;
}

if (!empty($filter_action)) {
    $where_conditions[] = "action_type = :filter_action";
    $params[':filter_action'] = $filter_action;
}

if (!empty($filter_entity)) {
    $where_conditions[] = "entity_type = :filter_entity";
    $params[':filter_entity'] = $filter_entity;
}

if (!empty($filter_date_from)) {
    $where_conditions[] = "date >= :date_from";
    $params[':date_from'] = $filter_date_from . ' 00:00:00';
}

if (!empty($filter_date_to)) {
    $where_conditions[] = "date <= :date_to";
    $params[':date_to'] = $filter_date_to . ' 23:59:59';
}

$where = !empty($where_conditions) ? implode(' AND ', $where_conditions) : '';
$activity_logs = $db->select('activity_logs', '*', $where, 'date DESC', $params);

// Obtener logs de créditos
$credit_where = $userRole === 'admin' ? '' : 'user_id = :user_id';
$credit_params = $userRole === 'admin' ? [] : [':user_id' => $currentUser['id']];
$credit_logs = $db->select('credit_logs', '*', $credit_where, 'date DESC', $credit_params);

// Pestaña activa
$active_tab = isset($_GET['tab']) ? $_GET['tab'] : 'activity';

?>

<div class="row mb-4">
    <!-- Estadísticas -->
    <div class="col-md-3">
        <div class="card stat-card">
            <div class="card-body text-center">
                <i class="fa fa-user-plus fa-2x text-success mb-2"></i>
                <h3 class="text-white"><?=$stats['clients_created']?></h3>
                <p class="text-muted mb-0">Clientes Creados</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card stat-card">
            <div class="card-body text-center">
                <i class="fa fa-user-times fa-2x text-danger mb-2"></i>
                <h3 class="text-white"><?=$stats['clients_deleted']?></h3>
                <p class="text-muted mb-0">Clientes Eliminados</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card stat-card">
            <div class="card-body text-center">
                <i class="fa fa-plus-circle fa-2x text-info mb-2"></i>
                <h3 class="text-white"><?=$stats['credits_added']?></h3>
                <p class="text-muted mb-0">Créditos Asignados</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card stat-card">
            <div class="card-body text-center">
                <i class="fa fa-minus-circle fa-2x text-warning mb-2"></i>
                <h3 class="text-white"><?=$stats['credits_used']?></h3>
                <p class="text-muted mb-0">Créditos Usados</p>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <ul class="nav nav-tabs card-header-tabs">
            <li class="nav-item">
                <a class="nav-link <?=$active_tab === 'activity' ? 'active' : ''?>" href="?tab=activity">
                    <i class="fa fa-history"></i> Historial de Actividad
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link <?=$active_tab === 'credits' ? 'active' : ''?>" href="?tab=credits">
                    <i class="fa fa-credit-card"></i> Historial de Créditos
                </a>
            </li>
            <?php if ($userRole === 'admin'): ?>
            <li class="nav-item">
                <a class="nav-link <?=$active_tab === 'resellers' ? 'active' : ''?>" href="?tab=resellers">
                    <i class="fa fa-users"></i> Actividad por Revendedor
                </a>
            </li>
            <?php endif; ?>
        </ul>
    </div>
    <div class="card-body">
        
        <?php if ($active_tab === 'activity'): ?>
        <!-- Filtros de Actividad -->
        <form method="get" class="mb-4">
            <input type="hidden" name="tab" value="activity">
            <div class="row">
                <?php if ($userRole === 'admin'): ?>
                <div class="col-md-2">
                    <label class="form-label">Usuario</label>
                    <select name="user" class="form-control form-control-sm">
                        <option value="">Todos</option>
                        <?php foreach ($users as $user): ?>
                            <option value="<?=$user['id']?>" <?=$filter_user == $user['id'] ? 'selected' : ''?>>
                                <?=$user['username']?> (<?=$user['role']?>)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="col-md-2">
                    <label class="form-label">Acción</label>
                    <select name="action" class="form-control form-control-sm">
                        <option value="">Todas</option>
                        <option value="create" <?=$filter_action === 'create' ? 'selected' : ''?>>Creación</option>
                        <option value="update" <?=$filter_action === 'update' ? 'selected' : ''?>>Modificación</option>
                        <option value="delete" <?=$filter_action === 'delete' ? 'selected' : ''?>>Eliminación</option>
                        <option value="credit_add" <?=$filter_action === 'credit_add' ? 'selected' : ''?>>Créditos +</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Entidad</label>
                    <select name="entity" class="form-control form-control-sm">
                        <option value="">Todas</option>
                        <option value="client" <?=$filter_entity === 'client' ? 'selected' : ''?>>Cliente</option>
                        <option value="reseller" <?=$filter_entity === 'reseller' ? 'selected' : ''?>>Revendedor</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Desde</label>
                    <input type="date" name="date_from" class="form-control form-control-sm" value="<?=$filter_date_from?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label">Hasta</label>
                    <input type="date" name="date_to" class="form-control form-control-sm" value="<?=$filter_date_to?>">
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-info btn-sm btn-block">
                        <i class="fa fa-filter"></i> Filtrar
                    </button>
                </div>
            </div>
        </form>

        <!-- Tabla de Actividad -->
        <div class="table-responsive">
            <table class="table table-hover table-sm">
                <thead>
                    <tr>
                        <th>Fecha/Hora</th>
                        <th>Usuario</th>
                        <th>Acción</th>
                        <th>Tipo</th>
                        <th>Entidad</th>
                        <th>Detalles</th>
                        <th>IP</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($activity_logs as $log): 
                        $details = json_decode($log['details'], true);
                    ?>
                    <tr>
                        <td>
                            <small><?=date('d/m/Y H:i', strtotime($log['date']))?></small>
                        </td>
                        <td>
                            <strong><?=getUsernameById($db, $log['user_id'])?></strong>
                        </td>
                        <td>
                            <span class="badge <?=getActionBadgeClass($log['action_type'])?>">
                                <?=formatActionType($log['action_type'])?>
                            </span>
                        </td>
                        <td><?=formatEntityType($log['entity_type'])?></td>
                        <td><strong><?=htmlspecialchars($log['entity_name'])?></strong></td>
                        <td>
                            <?php if ($details): ?>
                                <?php if (isset($details['duration'])): ?>
                                    <small>Duración: <?=$details['duration']?></small>
                                <?php endif; ?>
                                <?php if (isset($details['credits_used'])): ?>
                                    <small class="text-warning">(<?=$details['credits_used']?> créditos)</small>
                                <?php endif; ?>
                                <?php if (isset($details['amount'])): ?>
                                    <small class="text-info">+<?=$details['amount']?> créditos</small>
                                <?php endif; ?>
                                <?php if (isset($details['changes']) && is_array($details['changes'])): ?>
                                    <small><?=implode(', ', $details['changes'])?></small>
                                <?php endif; ?>
                            <?php endif; ?>
                        </td>
                        <td><small class="text-muted"><?=$log['ip_address']?></small></td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($activity_logs)): ?>
                        <tr><td colspan="7" class="text-center">No hay registros de actividad.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php elseif ($active_tab === 'credits'): ?>
        <!-- Historial de Créditos -->
        <div class="table-responsive">
            <table class="table table-hover table-sm">
                <thead>
                    <tr>
                        <th>Fecha/Hora</th>
                        <th>Usuario</th>
                        <th>Tipo</th>
                        <th>Cantidad</th>
                        <th>Descripción</th>
                        <th>Realizado por</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($credit_logs as $log): ?>
                    <tr>
                        <td>
                            <small><?=date('d/m/Y H:i', strtotime($log['date']))?></small>
                        </td>
                        <td>
                            <strong><?=getUsernameById($db, $log['user_id'])?></strong>
                        </td>
                        <td>
                            <?php if ($log['action'] === 'add'): ?>
                                <span class="badge badge-success"><i class="fa fa-plus"></i> Agregado</span>
                            <?php else: ?>
                                <span class="badge badge-warning"><i class="fa fa-minus"></i> Descontado</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <strong class="<?=$log['action'] === 'add' ? 'text-success' : 'text-warning'?>">
                                <?=$log['action'] === 'add' ? '+' : '-'?><?=$log['amount']?>
                            </strong>
                        </td>
                        <td><?=htmlspecialchars($log['description'])?></td>
                        <td>
                            <small><?=getUsernameById($db, $log['performed_by'] ?? $log['user_id'])?></small>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($credit_logs)): ?>
                        <tr><td colspan="6" class="text-center">No hay registros de créditos.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
        
        <?php elseif ($active_tab === 'resellers' && $userRole === 'admin'): ?>
        <!-- Actividad por Revendedor -->
        <div class="row">
            <?php 
            $resellers = $db->select('user', '*', 'role = :role', '', [':role' => 'reseller']);
            foreach ($resellers as $reseller): 
                $resellerStats = getAuditStats($db, $reseller['id']);
                $resellerClients = $db->count('menualuser', 'owner_id = :owner_id', [':owner_id' => $reseller['id']]);
            ?>
            <div class="col-md-6 mb-4">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="m-0">
                            <i class="fa fa-user"></i> <?=$reseller['username']?>
                        </h5>
                        <span class="badge badge-info"><?=$reseller['credits']?> créditos</span>
                    </div>
                    <div class="card-body">
                        <div class="row text-center">
                            <div class="col-4">
                                <h4 class="text-success"><?=$resellerStats['clients_created']?></h4>
                                <small class="text-muted">Creados</small>
                            </div>
                            <div class="col-4">
                                <h4 class="text-danger"><?=$resellerStats['clients_deleted']?></h4>
                                <small class="text-muted">Eliminados</small>
                            </div>
                            <div class="col-4">
                                <h4 class="text-info"><?=$resellerClients?></h4>
                                <small class="text-muted">Activos</small>
                            </div>
                        </div>
                        <hr class="border-secondary">
                        <div class="row text-center">
                            <div class="col-6">
                                <h5 class="text-success">+<?=$resellerStats['credits_added']?></h5>
                                <small class="text-muted">Créditos Recibidos</small>
                            </div>
                            <div class="col-6">
                                <h5 class="text-warning">-<?=$resellerStats['credits_used']?></h5>
                                <small class="text-muted">Créditos Usados</small>
                            </div>
                        </div>
                        <div class="mt-3 text-center">
                            <a href="?tab=activity&user=<?=$reseller['id']?>" class="btn btn-sm btn-outline-info">
                                <i class="fa fa-history"></i> Ver Historial Completo
                            </a>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            <?php if (empty($resellers)): ?>
                <div class="col-12 text-center">
                    <p class="text-muted">No hay revendedores registrados.</p>
                </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
        
    </div>
</div>

<style>
.nav-tabs .nav-link {
    color: #aaa;
    border: none;
    padding: 12px 20px;
}
.nav-tabs .nav-link.active {
    background: transparent;
    color: #00c6ff;
    border-bottom: 2px solid #00c6ff;
}
.nav-tabs .nav-link:hover {
    color: #fff;
    border-color: transparent;
}
.stat-card {
    background: linear-gradient(135deg, #1c1e23 0%, #252830 100%);
    border: 1px solid #333;
}
.form-label {
    font-size: 12px;
    color: #aaa;
    margin-bottom: 4px;
}
</style>

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