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

/* =======================
    SECURITY
======================= */
if (!isset($_SESSION['role'], $_SESSION['name'])) {
    header('Location: index.php');
    exit;
}

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

/* =======================
    DELETE LOGIC
======================= */
if (isset($_GET['delete_id'])) {
    $id = (int)$_GET['delete_id'];
    
    // Build query based on role
    if ($role === 'master') {
        $sql = "DELETE FROM credit_history WHERE id = $id";
    } else {
        $sql = "DELETE FROM credit_history WHERE id = $id AND actor = '$user'";
    }

    // Handle database methods
    if (method_exists($db, 'query')) {
        $db->query($sql);
    } elseif (method_exists($db, 'execute')) {
        $db->execute($sql);
    } else {
        $db->delete('credit_history', "id = $id");
    }

    echo "<script>alert('Registro processado!'); window.location='credit_history.php';</script>";
    exit;
}

/* =======================
    DATA FETCHING
======================= */
if ($role === 'master') {
    $history = $db->select('credit_history', '*', '', 'created_at DESC');
} else {
    $history = $db->select('credit_history', '*', "actor = '$user' OR target IN (SELECT username FROM menualuser WHERE parent = '$user')", 'created_at DESC');
}

// Function to translate actions
function translateAction($action, $amount) {
    $actionsMap = [
        'MANUAL_UPDATE'   => $amount > 0 ? 'CRÉDITOS ADICIONADOS' : ($amount < 0 ? 'CRÉDITOS REMOVIDOS' : 'CRÉDITOS ZERADOS'),
        'USER_DELETED'    => 'USUÁRIO EXCLUÍDO',
        'USER_CREATED'    => 'USUÁRIO CRIADO',
        'CREATE_USER'     => 'USUÁRIO CRIADO',
        'CREDIT_ADD'      => 'CRÉDITOS ADICIONADOS',
        'CREDIT_REMOVE'   => 'CRÉDITOS REMOVIDOS',
        'CREDIT_TRANSFER' => 'CRÉDITOS TRANSFERIDOS',
        'SYSTEM_ADD'      => 'SISTEMA ADICIONOU',
        'SYSTEM_REMOVE'   => 'SISTEMA REMOVEU',
        'ORDER_COMPLETED' => 'PEDIDO CONCLUÍDO',
        'SERVICE_USED'    => 'SERVIÇO UTILIZADO',
        'REEMBOLSO'          => 'REEMBOLSO',
        'BÔNUS'           => 'BÔNUS',
        'DAILY_DEDUCTION' => 'DÉBITO DIÁRIO',
        'EXTEND_CLIENT'   => 'ACESSO ESTENDIDO',
    ];
    
    return $actionsMap[$action] ?? str_replace('_', ' ', $action);
}

// Function to determine action CSS class
function getActionClass($action) {
    $actionClasses = [
        'CRÉDITOS ADICIONADOS'       => 'text-success',
        'SISTEMA ADICIONOU'        => 'text-success',
        'BÔNUS'               => 'text-success',
        'USUÁRIO CRIADO'        => 'text-info',
        'CRÉDITOS TRANSFERIDOS' => 'text-primary',
        'CRÉDITOS REMOVIDOS'     => 'text-danger',
        'SISTEMA REMOVEU'      => 'text-danger',
        'USUÁRIO EXCLUÍDO'        => 'text-danger',
        'DÉBITO DIÁRIO'     => 'text-danger',
        'SERVIÇO UTILIZADO'        => 'text-danger',
        'CRÉDITOS ZERADOS'       => 'text-warning',
        'REEMBOLSO'              => 'text-warning',
    ];
    
    return $actionClasses[$action] ?? 'text-info';
}
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    .main-card { background: #111; border: 1px solid #333; border-radius: 12px; box-shadow: 0 15px 35px rgba(0,0,0,0.5); }
    .header-style { background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%); padding: 20px; border-radius: 12px 12px 0 0; }
    .table { color: #fff !important; margin: 0; }
    .table thead th { background: #1a1a1a; color: #ff4b2b; border-bottom: 1px solid #333; font-size: 12px; white-space: nowrap; }
    .btn-excluir { background: #ff4b2b; color: white !important; border: none; padding: 5px 15px; border-radius: 4px; font-size: 11px; font-weight: bold; transition: 0.3s; cursor: pointer; }
    .btn-excluir:hover { background: #ff416c; transform: scale(1.05); text-decoration: none; }
    
    .badge-qtd { padding: 4px 8px; border-radius: 4px; font-weight: bold; min-width: 60px; display: inline-block; text-align: center; font-size: 13px; }
    .badge-positive { background: rgba(0, 255, 136, 0.1); color: #00ff88; border: 1px solid #00ff88; }
    .badge-negative { background: rgba(255, 65, 108, 0.1); color: #ff416c; border: 1px solid #ff416c; }
    .badge-neutral { background: rgba(255, 255, 255, 0.1); color: #ffffff; }
    
    .action-badge { padding: 3px 8px; border-radius: 4px; font-size: 11px; font-weight: bold; white-space: nowrap; }
    .action-success { background: rgba(0, 255, 136, 0.1); color: #00ff88; border: 1px solid #00ff88; }
    .action-danger { background: rgba(255, 65, 108, 0.1); color: #ff416c; border: 1px solid #ff416c; }
    .action-warning { background: rgba(255, 193, 7, 0.1); color: #ffc107; border: 1px solid #ffc107; }
    .action-info { background: rgba(23, 162, 184, 0.1); color: #17a2b8; border: 1px solid #17a2b8; }
    .action-primary { background: rgba(0, 123, 255, 0.1); color: #007bff; border: 1px solid #007bff; }
    
    td, th { vertical-align: middle !important; }
</style>

<div class="col-md-11 mx-auto mt-4">
    <div class="card main-card">
        <div class="card-header header-style text-center text-white">
            <h4 class="mb-0"><i class="fas fa-history mr-2"></i> REGISTROS DO HISTÓRICO DE CRÉDITOS</h4>
        </div>

        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead class="text-center">
                        <tr>
                            <th>DATA</th>
                            <th class="text-left">REALIZADO POR</th>
                            <th class="text-left">DESTINATÁRIO</th>
                            <th>VALOR</th>
                            <th>TIPO DE AÇÃO</th>
                            <th>AÇÕES</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($history)): ?>
                            <tr><td colspan="6" class="p-4 text-center">Nenhum registro de histórico encontrado.</td></tr>
                        <?php else: foreach ($history as $h): 
                            $amount = (int)$h['amount'];
                            $isPositive = $amount > 0;
                            $isNegative = $amount < 0;
                            
                            if ($isPositive) {
                                $formattedAmount = "+" . abs($amount);
                                $badgeClass = 'badge-positive';
                            } elseif ($isNegative) {
                                $formattedAmount = "-" . abs($amount);
                                $badgeClass = 'badge-negative';
                            } else {
                                $formattedAmount = "0";
                                $badgeClass = 'badge-neutral';
                            }
                            
                            $actionText = translateAction($h['action'], $amount);
                            $actionClass = getActionClass($actionText);
                            $actionBadgeClass = str_replace('text-', 'action-', $actionClass);
                        ?>
                        <tr class="text-center">
                            <td class="small text-muted">
                                <?= date('M d, Y', strtotime($h['created_at'])) ?><br>
                                <small class="text-muted"><?= date('H:i', strtotime($h['created_at'])) ?></small>
                            </td>
                            <td class="text-left">
                                <strong><?= htmlspecialchars($h['actor']) ?></strong>
                            </td>
                            <td class="text-left">
                                <?= htmlspecialchars($h['target']) ?>
                            </td>
                            <td>
                                <span class="badge-qtd <?= $badgeClass ?>">
                                    <?= $formattedAmount ?>
                                </span>
                            </td>
                            <td>
                                <span class="action-badge <?= $actionBadgeClass ?>">
                                    <?= $actionText ?>
                                </span>
                            </td>
                            <td>
                                <a href="?delete_id=<?= $h['id'] ?>" 
                                   class="btn-excluir" 
                                   onclick="return confirm('Are you sure you want to delete this log entry?')">
                                    <i class="fas fa-trash-alt"></i> EXCLUIR
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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