<?php
/**
 * Admin Back Office — shared auth
 */
require_once __DIR__ . '/../config.php';

// ── IP whitelist — usar solo REMOTE_ADDR (X-Forwarded-For es spoofable) ──
$_adm_allowed_ips = array_map('trim', explode(',', defined('ADMIN_IP_WHITELIST') ? ADMIN_IP_WHITELIST : '127.0.0.1'));
$_adm_client_ip   = $_SERVER['REMOTE_ADDR'] ?? '';
if (!in_array($_adm_client_ip, $_adm_allowed_ips, true)) {
    http_response_code(403); die('Acceso restringido.');
}

// DB connection
try {
    $pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8mb4', DB_USER, DB_PASS, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
} catch (PDOException $e) { die('DB error'); }

// Sesión con cookie segura
if (session_status() === PHP_SESSION_NONE) {
    session_set_cookie_params([
        'lifetime' => 0,
        'path'     => '/supercerebro/admin/',
        'secure'   => true,
        'httponly' => true,
        'samesite' => 'Strict',
    ]);
    session_start();
}

function adm_logged_in(): bool { return !empty($_SESSION['adm_id']); }
function adm_user(): array     { return $_SESSION['adm_data'] ?? []; }

function adm_require_login(): void {
    if (!adm_logged_in()) {
        header('Location: /supercerebro/admin/index.php'); exit;
    }
}

// ── CSRF para el admin ──────────────────────────────────────────────────────
function adm_csrf_token(): string {
    if (empty($_SESSION['adm_csrf'])) {
        $_SESSION['adm_csrf'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['adm_csrf'];
}

function adm_csrf_verify(): void {
    $token = $_POST['_csrf'] ?? ($_SERVER['HTTP_X_CSRF_TOKEN'] ?? '');
    if (!hash_equals($_SESSION['adm_csrf'] ?? '', $token)) {
        http_response_code(403); die('CSRF token inválido.');
    }
}

// ── Rate limiting para login admin ─────────────────────────────────────────
function adm_login_check_rate(string $ip): bool {
    global $pdo;
    try {
        $count = $pdo->prepare("SELECT COUNT(*) FROM dm_admin_audit WHERE action='login_fail' AND details LIKE ? AND created_at > DATE_SUB(NOW(), INTERVAL 15 MINUTE)");
        $count->execute(['%"ip":"'.$ip.'"%']);
        return (int)$count->fetchColumn() < 10;
    } catch (Throwable $e) { return true; }
}

function adm_login(string $email, string $password): bool {
    global $pdo;
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';

    if (!adm_login_check_rate($ip)) {
        sleep(2);
        return false;
    }

    $row = $pdo->prepare("SELECT * FROM dm_superadmin WHERE email=? AND active=1");
    $row->execute([$email]); $r = $row->fetch();

    if (!$r || !password_verify($password, $r['password'])) {
        try {
            $pdo->prepare("INSERT INTO dm_admin_audit (admin_id,action,target_id,details,ip,created_at) VALUES (0,'login_fail',0,?,?,NOW())")
                ->execute([json_encode(['ip'=>$ip,'email'=>$email]), $ip]);
        } catch (Throwable $e) {}
        sleep(1);
        return false;
    }

    session_regenerate_id(true);
    $_SESSION['adm_id']   = $r['id'];
    $_SESSION['adm_data'] = $r;
    $_SESSION['adm_csrf'] = bin2hex(random_bytes(32));
    $pdo->prepare("UPDATE dm_superadmin SET last_login=NOW() WHERE id=?")->execute([$r['id']]);
    return true;
}

function adm_logout(): void {
    session_unset();
    session_destroy();
    session_start();
    session_regenerate_id(true);
    header('Location: /supercerebro/admin/index.php'); exit;
}

function adm_audit(string $action, int $target_id = 0, array $details = []): void {
    global $pdo;
    $adm = adm_user();
    try {
        $pdo->prepare("INSERT INTO dm_admin_audit (admin_id, action, target_id, details, ip, created_at) VALUES (?,?,?,?,?,NOW())")
            ->execute([$adm['id']??0, $action, $target_id, json_encode($details), $_SERVER['REMOTE_ADDR']??'']);
    } catch (Throwable $e) {}
}

function adm_header(string $title, string $active): void {
    header("Content-Security-Policy: default-src 'self'; "
        . "script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com; "
        . "style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
        . "font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; "
        . "connect-src 'self'; frame-ancestors 'none'; object-src 'none'; base-uri 'self'");
    $csrf = adm_csrf_token();
    $nav  = [
        'dashboard'      => ['📊 Dashboard',  'dashboard.php'],
        'growth'         => ['🌱 Growth',     'growth.php'],
        'revenue'        => ['💰 Revenue',    'revenue.php'],
        'users'          => ['👥 Usuarios',   'users.php'],
        'implementations'=> ['🛠 Implems.',   'implementations.php'],
        'tickets'        => ['🎧 Tickets',    'tickets.php'],
        'comms'          => ['📨 Comms',      'comms.php'],
        'config_admin'   => ['⚙️ Config',     'config_admin.php'],
        'system'         => ['🖥 Sistema',    'system.php'],
        'apis'           => ['🔑 APIs',       'apis.php'],
        'announcements'  => ['📢 Anuncios',   'announcements.php'],
        'clients_admin'  => ['🏢 Clientes',   'clients_adm.php'],
        'gdpr'           => ['🔒 GDPR',        'gdpr.php'],
    ];
    echo '<!DOCTYPE html><html lang="es"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">';
    echo '<meta name="adm-csrf" content="'.htmlspecialchars($csrf).'">';
    echo '<title>Admin · '.htmlspecialchars($title).'</title>';
    echo '<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{background:#0a0a0f;color:#e2e8f0;font-family:Inter,system-ui,sans-serif;font-size:14px;display:flex;flex-direction:column;min-height:100vh}
a{color:inherit;text-decoration:none}
.adm-topbar{background:#111;border-bottom:1px solid #1e293b;padding:0 20px;height:50px;display:flex;align-items:center;justify-content:space-between}
.adm-brand{font-weight:700;font-size:15px;color:#a78bfa}
.adm-nav{display:flex;gap:4px;overflow-x:auto}
.adm-nav a{padding:5px 11px;border-radius:6px;font-size:13px;color:#64748b;white-space:nowrap;transition:all .15s}
.adm-nav a:hover{color:#e2e8f0;background:#1e293b}
.adm-nav a.active{color:#e2e8f0;background:#1e293b;font-weight:600}
.adm-user{font-size:12px;color:#475569}
.adm-wrap{flex:1;padding:24px;max-width:1400px;width:100%;margin:0 auto}
.adm-h1{font-size:22px;font-weight:700;margin-bottom:20px}
.card{background:#111827;border:1px solid #1e293b;border-radius:10px;padding:20px;margin-bottom:16px}
.stat-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px}
.stat{background:#111827;border:1px solid #1e293b;border-radius:8px;padding:16px;text-align:center}
.stat .val{font-size:28px;font-weight:700;color:#a78bfa}
.stat .lbl{font-size:12px;color:#475569;margin-top:4px}
table{width:100%;border-collapse:collapse}
th{text-align:left;padding:10px 12px;border-bottom:1px solid #1e293b;color:#475569;font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.5px}
td{padding:10px 12px;border-bottom:1px solid #0f172a;vertical-align:middle}
tr:hover td{background:rgba(255,255,255,.02)}
input[type=text],input[type=email],input[type=password],input[type=number],input[type=date],input[type=datetime-local],select,textarea{background:#0f172a;border:1px solid #1e293b;border-radius:6px;padding:7px 10px;color:#e2e8f0;font-size:13px;font-family:inherit;width:100%;outline:none}
input:focus,select:focus,textarea:focus{border-color:#6d28d9}
.btn{padding:7px 16px;border-radius:6px;font-size:13px;font-weight:600;cursor:pointer;border:none;font-family:inherit;transition:all .15s}
.btn-blue{background:#2563eb;color:#fff}.btn-blue:hover{background:#1d4ed8}
.btn-red{background:#dc2626;color:#fff}.btn-red:hover{background:#b91c1c}
.btn-gray{background:#1e293b;color:#e2e8f0;border:1px solid #334155}.btn-gray:hover{background:#334155}
.btn-green{background:#16a34a;color:#fff}.btn-green:hover{background:#15803d}
</style>
<script>
// Inyectar CSRF en todos los forms del admin automáticamente
document.addEventListener("DOMContentLoaded",function(){
  var t=document.querySelector("meta[name=adm-csrf]")?.content;
  if(!t)return;
  document.querySelectorAll("form[method=POST],form[method=post]").forEach(function(f){
    if(!f.querySelector("input[name=_csrf]")){var i=document.createElement("input");i.type="hidden";i.name="_csrf";i.value=t;f.appendChild(i);}
  });
});
</script>
</head><body>';
    $adm = adm_user();
    $adm_name = htmlspecialchars($adm['name'] ?? 'Admin');
    echo '<div class="adm-topbar">';
    echo '<div style="display:flex;align-items:center;gap:20px"><span class="adm-brand">⚡ SuperCerebro Admin</span>';
    echo '<nav class="adm-nav">';
    foreach ($nav as $key => [$label, $href]) {
        $cls = $active === $key ? ' class="active"' : '';
        echo "<a href=\"$href\"$cls>$label</a>";
    }
    echo '</nav></div>';
    echo '<div style="display:flex;align-items:center;gap:12px"><span class="adm-user">'.$adm_name.'</span>';
    echo '<a href="index.php?logout=1" class="btn btn-gray" style="padding:4px 10px;font-size:12px">Salir</a></div></div>';
    echo '<div class="adm-wrap">';
}

function adm_footer(): void { echo '</div></body></html>'; }
