<?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 (SINGLE)
======================= */
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 eliminado con éxito!'); window.location='credit_history.php';</script>";
    exit;
}

/* =======================
    MASS DELETE LOGIC
======================= */
if (isset($_POST['mass_delete']) && isset($_POST['selected_ids']) && is_array($_POST['selected_ids'])) {
    $selectedIds = array_map('intval', $_POST['selected_ids']);
    
    if (!empty($selectedIds)) {
        $idsString = implode(',', $selectedIds);
        
        // Build query based on role
        if ($role === 'master') {
            $sql = "DELETE FROM credit_history WHERE id IN ($idsString)";
        } else {
            $sql = "DELETE FROM credit_history WHERE id IN ($idsString) AND actor = '$user'";
        }
        
        // Execute deletion
        if (method_exists($db, 'query')) {
            $result = $db->query($sql);
        } elseif (method_exists($db, 'execute')) {
            $result = $db->execute($sql);
        } else {
            foreach ($selectedIds as $id) {
                $db->delete('credit_history', "id = $id");
            }
            $result = true;
        }
        
        $count = count($selectedIds);
        echo "<script>alert('$count registro(s) eliminado(s) con éxito!'); window.location='credit_history.php';</script>";
        exit;
    }
}

/* =======================
    DELETE ALL (FILTERED)
======================= */
if (isset($_POST['delete_all']) && $role === 'master') {
    // Optional: Add filters if needed
    $filterCondition = '';
    if (isset($_POST['filter_actor']) && !empty($_POST['filter_actor'])) {
        $filterActor = $db->escape($_POST['filter_actor']);
        $filterCondition = "WHERE actor = '$filterActor'";
    }
    if (isset($_POST['filter_target']) && !empty($_POST['filter_target'])) {
        $filterTarget = $db->escape($_POST['filter_target']);
        $filterCondition = empty($filterCondition) ? "WHERE target = '$filterTarget'" : "$filterCondition AND target = '$filterTarget'";
    }
    
    $sql = "DELETE FROM credit_history $filterCondition";
    
    if (method_exists($db, 'query')) {
        $db->query($sql);
    } elseif (method_exists($db, 'execute')) {
        $db->execute($sql);
    } else {
        // Fallback - delete all
        $allHistory = $db->select('credit_history', 'id', $filterCondition);
        foreach ($allHistory as $record) {
            $db->delete('credit_history', "id = {$record['id']}");
        }
    }
    
    echo "<script>alert('Todos los registros filtrados han sido eliminados!'); 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');
}

// Get unique actors and targets for filters (only for master)
$actors = [];
$targets = [];
if ($role === 'master') {
    $actorsResult = $db->select('credit_history', 'DISTINCT actor', '', '');
    foreach ($actorsResult as $a) {
        $actors[] = $a['actor'];
    }
    $targetsResult = $db->select('credit_history', 'DISTINCT target', '', '');
    foreach ($targetsResult as $t) {
        $targets[] = $t['target'];
    }
}

// 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; }
    .btn-mass-delete { background: #dc3545; color: white; border: none; padding: 8px 20px; border-radius: 6px; font-weight: bold; transition: 0.3s; cursor: pointer; }
    .btn-mass-delete:hover { background: #c82333; transform: scale(1.02); }
    .btn-delete-all { background: #6c757d; color: white; border: none; padding: 8px 20px; border-radius: 6px; font-weight: bold; transition: 0.3s; cursor: pointer; }
    .btn-delete-all:hover { background: #5a6268; }
    .btn-filter { background: #007bff; color: white; border: none; padding: 8px 20px; border-radius: 6px; font-weight: bold; transition: 0.3s; cursor: pointer; }
    .btn-filter:hover { background: #0056b3; }
    .select-all { margin-right: 10px; transform: scale(1.1); cursor: pointer; }
    .checkbox-col { width: 40px; text-align: center; }
    .checkbox-col input { transform: scale(1.2); cursor: pointer; }
    .filter-bar { background: #1a1a1a; padding: 15px; border-radius: 8px; margin-bottom: 20px; display: flex; gap: 15px; flex-wrap: wrap; align-items: flex-end; }
    .filter-group { display: flex; flex-direction: column; }
    .filter-group label { font-size: 11px; color: #aaa; margin-bottom: 4px; }
    .filter-group input, .filter-group select { background: #2a2a2a; border: 1px solid #444; color: white; padding: 6px 12px; border-radius: 4px; font-size: 13px; }
    .filter-group input:focus, .filter-group select:focus { outline: none; border-color: #ff4b2b; }
    .action-buttons { display: flex; gap: 10px; margin-left: auto; align-items: center; }
    .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; }
    .selection-info { background: #2a2a2a; padding: 10px 15px; border-radius: 6px; margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center; }
    .selection-info span { color: #ff4b2b; font-weight: bold; }
    
    @media (max-width: 768px) {
        .filter-bar { flex-direction: column; }
        .action-buttons { margin-left: 0; margin-top: 10px; }
        .checkbox-col { width: 30px; }
    }
</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">
            
            <!-- FILTER BAR (Only for Master) -->
            <?php if ($role === 'master'): ?>
            <div class="filter-bar">
                <form method="GET" action="" style="display: flex; gap: 15px; flex-wrap: wrap; width: 100%;">
                    <div class="filter-group">
                        <label><i class="fas fa-user"></i> Filtrar por Actor</label>
                        <select name="filter_actor" style="background: #2a2a2a;">
                            <option value="">Todos</option>
                            <?php foreach ($actors as $actor): ?>
                            <option value="<?= htmlspecialchars($actor) ?>" <?= (isset($_GET['filter_actor']) && $_GET['filter_actor'] == $actor) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($actor) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-user-tag"></i> Filtrar por Destinatário</label>
                        <select name="filter_target" style="background: #2a2a2a;">
                            <option value="">Todos</option>
                            <?php foreach ($targets as $target): ?>
                            <option value="<?= htmlspecialchars($target) ?>" <?= (isset($_GET['filter_target']) && $_GET['filter_target'] == $target) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($target) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label>&nbsp;</label>
                        <button type="submit" class="btn-filter">
                            <i class="fas fa-search"></i> Filtrar
                        </button>
                    </div>
                    <div class="filter-group">
                        <label>&nbsp;</label>
                        <a href="credit_history.php" class="btn-filter" style="background: #6c757d; text-decoration: none;">
                            <i class="fas fa-undo"></i> Limpiar
                        </a>
                    </div>
                </form>
                
                <form method="POST" action="" id="deleteAllForm" style="display: inline;">
                    <?php if (isset($_GET['filter_actor']) && !empty($_GET['filter_actor'])): ?>
                        <input type="hidden" name="filter_actor" value="<?= htmlspecialchars($_GET['filter_actor']) ?>">
                    <?php endif; ?>
                    <?php if (isset($_GET['filter_target']) && !empty($_GET['filter_target'])): ?>
                        <input type="hidden" name="filter_target" value="<?= htmlspecialchars($_GET['filter_target']) ?>">
                    <?php endif; ?>
                    <button type="submit" name="delete_all" class="btn-delete-all" onclick="return confirm('⚠️ ¿ELIMINAR TODOS los registros filtrados? Esta acción no se puede deshacer.');">
                        <i class="fas fa-trash-alt"></i> Eliminar Todos (Filtrados)
                    </button>
                </form>
            </div>
            <?php endif; ?>
            
            <!-- MASS DELETE FORM -->
            <form method="POST" action="" id="massDeleteForm">
                <input type="hidden" name="mass_delete" value="1">
                
                <!-- Selection Info Bar -->
                <div id="selectionInfo" class="selection-info" style="display: none;">
                    <span>
                        <i class="fas fa-check-circle"></i> 
                        <span id="selectedCount">0</span> registro(s) seleccionado(s)
                    </span>
                    <button type="submit" class="btn-mass-delete" onclick="return confirm('¿Estás seguro de eliminar los registros seleccionados?');">
                        <i class="fas fa-trash-alt"></i> Eliminar Seleccionados
                    </button>
                </div>
                
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="text-center">
                            <tr>
                                <th class="checkbox-col">
                                    <input type="checkbox" id="selectAllCheckbox" class="select-all" title="Seleccionar todos">
                                </th>
                                <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="7" class="p-4 text-center">Nenhum registro de histórico encontrado.</td></tr>
                            <?php else: 
                                $hasFilter = (isset($_GET['filter_actor']) && !empty($_GET['filter_actor'])) || (isset($_GET['filter_target']) && !empty($_GET['filter_target']));
                                foreach ($history as $h): 
                                    // Apply filters manually if needed
                                    if ($hasFilter && $role === 'master') {
                                        if (isset($_GET['filter_actor']) && !empty($_GET['filter_actor']) && $h['actor'] != $_GET['filter_actor']) continue;
                                        if (isset($_GET['filter_target']) && !empty($_GET['filter_target']) && $h['target'] != $_GET['filter_target']) continue;
                                    }
                                    
                                    $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" data-id="<?= $h['id'] ?>">
                                <td class="checkbox-col">
                                    <input type="checkbox" name="selected_ids[]" value="<?= $h['id'] ?>" class="record-checkbox">
                                </td>
                                <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'] ?><?= isset($_GET['filter_actor']) ? '&filter_actor=' . urlencode($_GET['filter_actor']) : '' ?><?= isset($_GET['filter_target']) ? '&filter_target=' . urlencode($_GET['filter_target']) : '' ?>" 
                                       class="btn-excluir" 
                                       onclick="return confirm('¿Estás seguro de eliminar este registro?')">
                                        <i class="fas fa-trash-alt"></i> EXCLUIR
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Select All functionality
const selectAllCheckbox = document.getElementById('selectAllCheckbox');
const recordCheckboxes = document.querySelectorAll('.record-checkbox');
const selectionInfo = document.getElementById('selectionInfo');
const selectedCountSpan = document.getElementById('selectedCount');

function updateSelectionInfo() {
    const checkedCount = document.querySelectorAll('.record-checkbox:checked').length;
    if (checkedCount > 0) {
        selectionInfo.style.display = 'flex';
        selectedCountSpan.textContent = checkedCount;
    } else {
        selectionInfo.style.display = 'none';
    }
    
    // Update select all checkbox state
    if (selectAllCheckbox) {
        const totalCheckboxes = document.querySelectorAll('.record-checkbox').length;
        const checkedCheckboxes = document.querySelectorAll('.record-checkbox:checked').length;
        
        if (checkedCheckboxes === 0) {
            selectAllCheckbox.checked = false;
            selectAllCheckbox.indeterminate = false;
        } else if (checkedCheckboxes === totalCheckboxes) {
            selectAllCheckbox.checked = true;
            selectAllCheckbox.indeterminate = false;
        } else {
            selectAllCheckbox.indeterminate = true;
        }
    }
}

if (selectAllCheckbox) {
    selectAllCheckbox.addEventListener('change', function() {
        const isChecked = this.checked;
        recordCheckboxes.forEach(checkbox => {
            checkbox.checked = isChecked;
        });
        updateSelectionInfo();
    });
}

recordCheckboxes.forEach(checkbox => {
    checkbox.addEventListener('change', updateSelectionInfo);
});

// Initialize selection info on page load
updateSelectionInfo();

// Prevent accidental form submission on Enter key
document.getElementById('massDeleteForm')?.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        e.preventDefault();
        return false;
    }
});
</script>

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