<?php
// KVKK/GDPR basit veri ihracı (admin)
session_start();
include 'config.php';
include 'auth.php';

require_permission('reports_view');

header('Content-Type: application/json; charset=utf-8');

$userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
$mask = isset($_GET['mask']) ? (int)$_GET['mask'] : 1; // varsayılan: maskeli

if ($userId <= 0) {
    echo json_encode(['error' => 'invalid_user_id']);
    exit;
}

function mask_email($email) {
    if (!is_string($email) || $email === '') return $email;
    $parts = explode('@', $email);
    $name = $parts[0] ?? '';
    $domain = $parts[1] ?? '';
    $maskedName = strlen($name) > 2 ? substr($name,0,2) . str_repeat('*', max(0, strlen($name)-2)) : str_repeat('*', strlen($name));
    return $maskedName . '@' . $domain;
}

function mask_phone($phone) {
    if (!is_string($phone)) $phone = (string)$phone;
    $len = strlen($phone);
    if ($len <= 4) return str_repeat('*', $len);
    return substr($phone,0,$len-4) . str_repeat('*', 4);
}

function mask_tc($tc) {
    if (!is_string($tc)) $tc = (string)$tc;
    $len = strlen($tc);
    if ($len <= 4) return str_repeat('*', $len);
    return str_repeat('*', $len-4) . substr($tc, -4);
}

// Kullanıcı verisi
$stmt = $pdo->prepare('SELECT * FROM kullanicilar WHERE id = :id');
$stmt->execute([':id' => $userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$user) { echo json_encode(['error' => 'user_not_found']); exit; }

if ($mask) {
    $user['email'] = mask_email($user['email'] ?? '');
    $user['phone'] = mask_phone($user['phone'] ?? '');
    $user['tc_kimlik_no'] = mask_tc($user['tc_kimlik_no'] ?? '');
}

// Para yatırma ve çekme hareketleri
$py = $pdo->prepare('SELECT id,banka,miktar,tarih,durum,tur,aciklama FROM parayatir WHERE user_id = :id ORDER BY tarih DESC, id DESC');
$py->execute([':id' => $userId]);
$parayatir = $py->fetchAll(PDO::FETCH_ASSOC);

$pc = $pdo->prepare('SELECT id,payas,kazanilan,tarih,durum,aciklama FROM paracek WHERE user_id = :id ORDER BY tarih DESC, id DESC');
$pc->execute([':id' => $userId]);
$paracek = $pc->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'user' => $user,
    'parayatir' => $parayatir,
    'paracek' => $paracek,
    'masked' => (bool)$mask,
]);
?>