<?php
// Bağlantıyı sağlayın ve yetki/lojik yardımcıları
include 'config.php';
include 'auth.php';
include 'logger.php';
// E-posta gönderimi için ortak yardımcıyı dahil et
@include_once __DIR__ . '/../inc/send_mail.php';
// SMS için basit sağlayıcı iskeleti
@include_once __DIR__ . '/sms.php';
require_permission('users_manage');

// Maskeleme yardımcıları (izin yoksa hassas alanları gizle)
if (!function_exists('mask_email')) {
    function mask_email($email) {
        if (!$email) return '';
        $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 ? '@' . $domain : '');
    }
}
if (!function_exists('mask_phone')) {
    function mask_phone($phone) {
        if (!$phone) return '';
        return substr($phone,0,3) . str_repeat('*', max(0, strlen($phone)-6)) . substr($phone,-3);
    }
}
if (!function_exists('mask_tc')) {
    function mask_tc($tc) {
        if (!$tc) return '';
        return substr($tc,0,3) . str_repeat('*', max(0, strlen($tc)-6)) . substr($tc,-3);
    }
}

// Şema özelliklerini kontrol et (gerekirse ekle)
$has_is_frozen = false;
$has_deleted_at = false;
$has_twofa_secret = false;
$has_twofa_enabled = false;
// Doğrulama altyapısı kolonları
$has_email_verified_at = false;
$has_phone_verified_at = false;
$has_email_verification_code = false;
$has_phone_verification_code = false;
$has_email_code_expires_at = false;
$has_phone_code_expires_at = false;
try {
    $cols = $pdo->query("SHOW COLUMNS FROM kullanicilar")->fetchAll(PDO::FETCH_COLUMN, 0);
    $has_is_frozen = in_array('is_frozen', $cols, true);
    $has_deleted_at = in_array('deleted_at', $cols, true);
    $has_twofa_secret = in_array('twofa_secret', $cols, true);
    $has_twofa_enabled = in_array('twofa_enabled', $cols, true);
    $has_email_verified_at = in_array('email_verified_at', $cols, true);
    $has_phone_verified_at = in_array('phone_verified_at', $cols, true);
    $has_email_verification_code = in_array('email_verification_code', $cols, true);
    $has_phone_verification_code = in_array('phone_verification_code', $cols, true);
    $has_email_code_expires_at = in_array('email_code_expires_at', $cols, true);
    $has_phone_code_expires_at = in_array('phone_code_expires_at', $cols, true);
    if (!$has_is_frozen) { $pdo->exec("ALTER TABLE kullanicilar ADD COLUMN is_frozen TINYINT(1) NOT NULL DEFAULT 0"); $has_is_frozen = true; }
    if (!$has_deleted_at) { $pdo->exec("ALTER TABLE kullanicilar ADD COLUMN deleted_at DATETIME NULL DEFAULT NULL"); $has_deleted_at = true; }
    if (!$has_twofa_secret) { $pdo->exec("ALTER TABLE kullanicilar ADD COLUMN twofa_secret VARCHAR(64) NULL DEFAULT NULL"); $has_twofa_secret = true; }
    if (!$has_twofa_enabled) { $pdo->exec("ALTER TABLE kullanicilar ADD COLUMN twofa_enabled TINYINT(1) NOT NULL DEFAULT 0"); $has_twofa_enabled = true; }
    if (!$has_email_verified_at) { $pdo->exec("ALTER TABLE kullanicilar ADD COLUMN email_verified_at DATETIME NULL DEFAULT NULL"); $has_email_verified_at = true; }
    if (!$has_phone_verified_at) { $pdo->exec("ALTER TABLE kullanicilar ADD COLUMN phone_verified_at DATETIME NULL DEFAULT NULL"); $has_phone_verified_at = true; }
    if (!$has_email_verification_code) { $pdo->exec("ALTER TABLE kullanicilar ADD COLUMN email_verification_code VARCHAR(16) NULL DEFAULT NULL"); $has_email_verification_code = true; }
    if (!$has_phone_verification_code) { $pdo->exec("ALTER TABLE kullanicilar ADD COLUMN phone_verification_code VARCHAR(16) NULL DEFAULT NULL"); $has_phone_verification_code = true; }
    if (!$has_email_code_expires_at) { $pdo->exec("ALTER TABLE kullanicilar ADD COLUMN email_code_expires_at DATETIME NULL DEFAULT NULL"); $has_email_code_expires_at = true; }
    if (!$has_phone_code_expires_at) { $pdo->exec("ALTER TABLE kullanicilar ADD COLUMN phone_code_expires_at DATETIME NULL DEFAULT NULL"); $has_phone_code_expires_at = true; }
} catch (Exception $e) {
    // sessiz geç, eski şemalarda devam
}

// AJAX işlemleri: dondur/çöz, sil, 2FA hazırlık
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    // Toplu işlem özel akışı: id doğrulaması gerektirmez
    if ($action === 'bulk') {
        try {
            $op = isset($_POST['op']) ? trim($_POST['op']) : '';
            $idsRaw = isset($_POST['ids']) ? trim($_POST['ids']) : '';
            $idsArr = array_values(array_unique(array_filter(array_map(function($x){ return ctype_digit($x) ? (int)$x : null; }, explode(',', $idsRaw)), function($v){ return !is_null($v) && $v > 0; })));
            if (!$op || empty($idsArr)) { echo json_encode(['success'=>false,'error'=>'Geçersiz toplu işlem veya ID listesi']); exit; }

            // İzin kontrolü ve SQL hazırlığı
            $affected = 0;
            $placeholders = implode(',', array_fill(0, count($idsArr), '?'));
            if ($op === 'freeze') {
                require_permission('users_freeze');
                if ($has_is_frozen) {
                    $stmt = $pdo->prepare("UPDATE kullanicilar SET is_frozen = 1 WHERE id IN ($placeholders)");
                    $stmt->execute($idsArr);
                    $affected = $stmt->rowCount();
                } else {
                    $stmt = $pdo->prepare("UPDATE kullanicilar SET ana_bakiye = ana_bakiye WHERE id IN ($placeholders)");
                    $stmt->execute($idsArr);
                    $affected = $stmt->rowCount();
                }
                audit_log('freeze_bulk','user',['ids'=>$idsArr,'count'=>count($idsArr),'admin'=>$_SESSION['admin_user']??'unknown']);
            } elseif ($op === 'unfreeze') {
                require_permission('users_freeze');
                if ($has_is_frozen) {
                    $stmt = $pdo->prepare("UPDATE kullanicilar SET is_frozen = 0 WHERE id IN ($placeholders)");
                    $stmt->execute($idsArr);
                    $affected = $stmt->rowCount();
                } else {
                    $stmt = $pdo->prepare("UPDATE kullanicilar SET ana_bakiye = ana_bakiye WHERE id IN ($placeholders)");
                    $stmt->execute($idsArr);
                    $affected = $stmt->rowCount();
                }
                audit_log('unfreeze_bulk','user',['ids'=>$idsArr,'count'=>count($idsArr),'admin'=>$_SESSION['admin_user']??'unknown']);
            } elseif ($op === 'delete') {
                require_permission('user_delete');
                if ($has_deleted_at) {
                    $stmt = $pdo->prepare("UPDATE kullanicilar SET deleted_at = NOW() WHERE id IN ($placeholders)");
                    $stmt->execute($idsArr);
                    $affected = $stmt->rowCount();
                } else {
                    $stmt = $pdo->prepare("DELETE FROM kullanicilar WHERE id IN ($placeholders)");
                    $stmt->execute($idsArr);
                    $affected = $stmt->rowCount();
                }
                audit_log('delete_bulk','user',['ids'=>$idsArr,'count'=>count($idsArr),'admin'=>$_SESSION['admin_user']??'unknown']);
            } elseif ($op === 'restore') {
                require_permission('user_delete');
                if ($has_deleted_at) {
                    $stmt = $pdo->prepare("UPDATE kullanicilar SET deleted_at = NULL WHERE id IN ($placeholders)");
                    $stmt->execute($idsArr);
                    $affected = $stmt->rowCount();
                } else {
                    $affected = 0;
                }
                audit_log('restore_bulk','user',['ids'=>$idsArr,'count'=>count($idsArr),'admin'=>$_SESSION['admin_user']??'unknown']);
            } else {
                echo json_encode(['success'=>false,'error'=>'Bilinmeyen toplu işlem']);
                exit;
            }
            echo json_encode(['success'=>true,'affected'=>$affected]);
        } catch (Exception $ex) {
            event_log('error','users_bulk',$ex->getMessage(),['op'=>$_POST['op']??'', 'ids'=>$_POST['ids']??'']);
            echo json_encode(['success'=>false,'error'=>'Toplu işlem başarısız']);
        }
        exit;
    }
    $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
    if ($id <= 0) { echo json_encode(['success' => false, 'error' => 'Geçersiz ID']); exit; }
    try {
        if ($action === 'send_email_verif') {
            // E-posta doğrulama kodu gönder
            // Not: 2FA kapalı, sadece doğrulama altyapısı
            $email = '';
            try { $email = $pdo->query("SELECT email FROM kullanicilar WHERE id = ".$id)->fetchColumn() ?: ''; } catch(Exception $e){}
            if (!$email) { echo json_encode(['success'=>false,'error'=>'Kullanıcının e-posta adresi yok']); exit; }
            // 6 haneli kod üret
            $code = str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            $expires = date('Y-m-d H:i:s', time()+15*60);
            $stmt = $pdo->prepare('UPDATE kullanicilar SET email_verification_code = :code, email_code_expires_at = :exp WHERE id = :id');
            $stmt->execute([':code'=>$code, ':exp'=>$expires, ':id'=>$id]);
            $ok = false;
            if (function_exists('send_mail')) {
                $subject = 'E-posta Doğrulama Kodu';
                $body = '<p>Doğrulama kodunuz: <strong>'.htmlspecialchars($code).'</strong></p><p>Bu kod 15 dakika içinde geçerlidir.</p>';
                $ok = send_mail($email, $subject, $body);
            }
            audit_log('send_email_verif','user',['id'=>$id,'email'=>$email,'sent'=>$ok]);
            echo json_encode(['success'=>true, 'sent'=>$ok]);
        } elseif ($action === 'send_sms_verif') {
            // SMS doğrulama kodu gönder
            $phone = '';
            try { $phone = $pdo->query("SELECT phone FROM kullanicilar WHERE id = ".$id)->fetchColumn() ?: ''; } catch(Exception $e){}
            if (!$phone) { echo json_encode(['success'=>false,'error'=>'Kullanıcının telefon numarası yok']); exit; }
            $code = str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
            $expires = date('Y-m-d H:i:s', time()+15*60);
            $stmt = $pdo->prepare('UPDATE kullanicilar SET phone_verification_code = :code, phone_code_expires_at = :exp WHERE id = :id');
            $stmt->execute([':code'=>$code, ':exp'=>$expires, ':id'=>$id]);
            $ok = false;
            if (function_exists('send_sms')) {
                $msg = "Doğrulama kodunuz: $code (15 dk geçerli)";
                $ok = send_sms($phone, $msg);
            } else {
                // SMS gönderici yoksa logla
                event_log('sms','Gönderici tanımsız', ['phone'=>$phone,'code'=>$code]);
            }
            audit_log('send_sms_verif','user',['id'=>$id,'phone'=>$phone,'sent'=>$ok]);
            echo json_encode(['success'=>true, 'sent'=>$ok]);
        } elseif ($action === 'freeze') {
            require_permission('users_freeze');
            if ($has_is_frozen) {
                $stmt = $pdo->prepare('UPDATE kullanicilar SET is_frozen = 1 WHERE id = :id');
                $stmt->execute([':id' => $id]);
            } else {
                $stmt = $pdo->prepare('UPDATE kullanicilar SET ana_bakiye = ana_bakiye WHERE id = :id');
                $stmt->execute([':id' => $id]);
            }
            audit_log('freeze','user',['id'=>$id,'admin'=>$_SESSION['admin_user']??'unknown']);
            echo json_encode(['success' => true]);
        } elseif ($action === 'unfreeze') {
            require_permission('users_freeze');
            if ($has_is_frozen) {
                $stmt = $pdo->prepare('UPDATE kullanicilar SET is_frozen = 0 WHERE id = :id');
                $stmt->execute([':id' => $id]);
            } else {
                $stmt = $pdo->prepare('UPDATE kullanicilar SET ana_bakiye = ana_bakiye WHERE id = :id');
                $stmt->execute([':id' => $id]);
            }
            audit_log('unfreeze','user',['id'=>$id,'admin'=>$_SESSION['admin_user']??'unknown']);
            echo json_encode(['success' => true]);
        } elseif ($action === 'delete') {
            require_permission('user_delete');
            if ($has_deleted_at) {
                $stmt = $pdo->prepare('UPDATE kullanicilar SET deleted_at = NOW() WHERE id = :id');
                $stmt->execute([':id' => $id]);
            } else {
                $stmt = $pdo->prepare('DELETE FROM kullanicilar WHERE id = :id');
                $stmt->execute([':id' => $id]);
            }
            audit_log('delete','user',['id'=>$id,'admin'=>$_SESSION['admin_user']??'unknown']);
            echo json_encode(['success' => true]);
        } elseif ($action === 'restore') {
            require_permission('user_delete');
            if ($has_deleted_at) {
                $stmt = $pdo->prepare('UPDATE kullanicilar SET deleted_at = NULL WHERE id = :id');
                $stmt->execute([':id' => $id]);
                audit_log('restore','user',['id'=>$id,'admin'=>$_SESSION['admin_user']??'unknown']);
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => true]);
            }
        } elseif ($action === 'prepare_2fa') {
            // 2FA secret oluştur (pasif entegrasyon)
            // Base32 16 karakterlik secret
            $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
            $secret = '';
            for ($i=0; $i<16; $i++) { $secret .= $alphabet[random_int(0, strlen($alphabet)-1)]; }
            $stmt = $pdo->prepare('UPDATE kullanicilar SET twofa_secret = :sec WHERE id = :id');
            $stmt->execute([':sec'=>$secret, ':id'=>$id]);
            $issuer = isset($GLOBALS['SITE_NAME']) ? $GLOBALS['SITE_NAME'] : 'Site';
            // Kullanıcı adını al otpauth için
            $un = '';
            try { $un = $pdo->query("SELECT username FROM kullanicilar WHERE id = ".(int)$id)->fetchColumn() ?: ('user'.$id); } catch(Exception $e){}
            $otpauth = "otpauth://totp/".$issuer.":".$un."?secret=".$secret."&issuer=".$issuer."&digits=6&period=30";
            audit_log('2fa_prepare','user',['id'=>$id]);
            echo json_encode(['success'=>true,'secret'=>$secret,'otpauth'=>$otpauth]);
        } elseif ($action === 'toggle_2fa') {
            // sadece veritabanı bayrağı; login akışında henüz zorunlu değil
            $enabled = isset($_POST['enabled']) ? (int)$_POST['enabled'] : 0;
            $stmt = $pdo->prepare('UPDATE kullanicilar SET twofa_enabled = :en WHERE id = :id');
            $stmt->execute([':en'=>$enabled, ':id'=>$id]);
            audit_log('2fa_toggle','user',['id'=>$id,'enabled'=>$enabled]);
            echo json_encode(['success'=>true]);
        } else {
            echo json_encode(['success'=>false,'error'=>'Bilinmeyen işlem']);
        }
    } catch (Exception $ex) {
        event_log('error','users_action',$ex->getMessage(),['action'=>$action,'id'=>$id]);
        echo json_encode(['success'=>false,'error'=>'İşlem başarısız']);
    }
    exit;
}

// AJAX kullanıcı güncelleme isteğini en başta işle (action yoksa klasik güncelleme)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = $_POST['userId'] ?? null;
    $firstName = $_POST['firstName'] ?? '';
    $surname = $_POST['surname'] ?? '';
    $username = $_POST['username'] ?? '';
    $email = $_POST['email'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $anaBakiye = $_POST['anaBakiye'] ?? 0;
    $tcKimlikNo = $_POST['tcKimlikNo'] ?? '';
    $paraEkle = $_POST['paraEkle'] ?? null;
    $newPassword = $_POST['password'] ?? '';

    if (!empty($paraEkle)) {
        $anaBakiye = (float)$anaBakiye + (float)$paraEkle;
    }

    if (empty($newPassword)) {
        $stmt = $pdo->prepare("SELECT password FROM kullanicilar WHERE id = :id");
        $stmt->bindParam(':id', $userId, PDO::PARAM_INT);
        $stmt->execute();
        $newPassword = $stmt->fetchColumn();
    } else {
        $newPassword = password_hash($newPassword, PASSWORD_DEFAULT);
    }

    $stmt = $pdo->prepare("UPDATE kullanicilar SET 
        first_name = :first_name, 
        surname = :surname, 
        username = :username, 
        email = :email, 
        phone = :phone, 
        ana_bakiye = :ana_bakiye, 
        tc_kimlik_no = :tc_kimlik_no, 
        password = :password 
        WHERE id = :id");
    $stmt->bindParam(':first_name', $firstName);
    $stmt->bindParam(':surname', $surname);
    $stmt->bindParam(':username', $username);
    $stmt->bindParam(':email', $email);
    $stmt->bindParam(':phone', $phone);
    $stmt->bindParam(':ana_bakiye', $anaBakiye);
    $stmt->bindParam(':tc_kimlik_no', $tcKimlikNo);
    $stmt->bindParam(':password', $newPassword);
    $stmt->bindParam(':id', $userId, PDO::PARAM_INT);

    try {
        $ok = $stmt->execute();
        audit_log('users','update','Kullanıcı güncellendi',[
            'id'=>$userId,
            'updated_fields'=>['first_name','surname','username','email','phone','ana_bakiye','tc_kimlik_no'],
            'balance_added'=> (float)($paraEkle ?? 0),
            'password_changed'=> !empty($_POST['password'])
        ]);
        echo json_encode(['success' => $ok]);
    } catch (Exception $e) {
        event_log('error','users_update',$e->getMessage(),['id'=>$userId]);
        echo json_encode(['success' => false, 'error' => 'Veritabanı hatası']);
    }
    exit;
}

$limit = 9; // Sayfa başına gösterilecek kayıt sayısı
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1; // Sayfa numarasını al
$offset = ($page - 1) * $limit;

// Kullanıcı adına göre arama
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
// Topbar’daki global hızlı aramayı da destekle
if (isset($_GET['quick']) && trim($_GET['quick']) !== '') {
    $search = trim($_GET['quick']);
}
// Gelişmiş filtreler
// mevcut gelişmiş filtreler
$balance_min = isset($_GET['balance_min']) && $_GET['balance_min'] !== '' ? (float)$_GET['balance_min'] : null;
$balance_max = isset($_GET['balance_max']) && $_GET['balance_max'] !== '' ? (float)$_GET['balance_max'] : null;
$start_date = isset($_GET['start_date']) ? trim($_GET['start_date']) : '';
$end_date = isset($_GET['end_date']) ? trim($_GET['end_date']) : '';
// yeni gelişmiş filtreler (çoklu alan arama)
$email_q = isset($_GET['email']) ? trim($_GET['email']) : '';
$phone_q = isset($_GET['phone']) ? trim($_GET['phone']) : '';
$role_q = isset($_GET['role']) ? trim($_GET['role']) : '';
$last_login_start = isset($_GET['last_login_start']) ? trim($_GET['last_login_start']) : '';
$last_login_end   = isset($_GET['last_login_end']) ? trim($_GET['last_login_end']) : '';
// Silinenleri göster filtresi
$include_deleted = isset($_GET['include_deleted']) && $_GET['include_deleted'] === '1';

// Şema kontrol: created_at kolonu var mı?
$has_created_at = false;
$has_last_login = false;
$has_role_col = false;
try {
    $cols = $pdo->query("SHOW COLUMNS FROM kullanicilar")->fetchAll(PDO::FETCH_COLUMN, 0);
    $has_created_at = in_array('created_at', $cols, true);
    $has_last_login = in_array('last_login', $cols, true);
    $has_role_col = in_array('role', $cols, true);
} catch (Exception $e) { $has_created_at = false; }

// Dinamik WHERE oluştur
$where = "(username LIKE :search OR id = :id)";
if ($balance_min !== null) { $where .= " AND ana_bakiye >= :balance_min"; }
if ($balance_max !== null) { $where .= " AND ana_bakiye <= :balance_max"; }
if ($has_created_at) {
    if ($start_date !== '') { $where .= " AND created_at >= :start_date"; }
    if ($end_date !== '') { $where .= " AND created_at <= :end_date"; }
}
if ($email_q !== '') { $where .= " AND email LIKE :email_q"; }
if ($phone_q !== '') { $where .= " AND phone LIKE :phone_q"; }
if ($has_role_col && $role_q !== '') { $where .= " AND role = :role_q"; }
if ($has_last_login) {
    if ($last_login_start !== '') { $where .= " AND last_login >= :ll_start"; }
    if ($last_login_end !== '')   { $where .= " AND last_login <= :ll_end"; }
}
if ($has_deleted_at && !$include_deleted) { $where .= " AND (deleted_at IS NULL)"; }

// Kullanıcıları getir
$sql = "SELECT * FROM kullanicilar WHERE $where LIMIT :limit OFFSET :offset";
$stmt = $pdo->prepare($sql);
$searchTerm = "%$search%";
$stmt->bindParam(':search', $searchTerm, PDO::PARAM_STR);

// ID'ye göre tam eşleşme araması yapıyoruz
$searchId = is_numeric($search) ? (int)$search : null; // Sadece sayısal değerler için
$stmt->bindParam(':id', $searchId, PDO::PARAM_INT);
$searchId = is_numeric($search) ? (int)$search : null; // Sadece sayısal değerler için
$stmt->bindParam(':id', $searchId, PDO::PARAM_INT);
if ($balance_min !== null) { $stmt->bindParam(':balance_min', $balance_min); }
if ($balance_max !== null) { $stmt->bindParam(':balance_max', $balance_max); }
if ($has_created_at) {
    if ($start_date !== '') { $stmt->bindParam(':start_date', $start_date); }
    if ($end_date !== '') {
        $endDateTime = $end_date . ' 23:59:59';
        $stmt->bindParam(':end_date', $endDateTime);
    }
}
if ($email_q !== '') { $emailLike = "%$email_q%"; $stmt->bindParam(':email_q', $emailLike, PDO::PARAM_STR); }
if ($phone_q !== '') { $phoneLike = "%$phone_q%"; $stmt->bindParam(':phone_q', $phoneLike, PDO::PARAM_STR); }
if ($has_role_col && $role_q !== '') { $stmt->bindParam(':role_q', $role_q, PDO::PARAM_STR); }
if ($has_last_login) {
    if ($last_login_start !== '') { $stmt->bindParam(':ll_start', $last_login_start); }
    if ($last_login_end !== '') { $llEnd = $last_login_end . ' 23:59:59'; $stmt->bindParam(':ll_end', $llEnd); }
}
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Toplam kullanıcı sayısını al
$total_sql = "SELECT COUNT(*) FROM kullanicilar WHERE $where";
$total_stmt = $pdo->prepare($total_sql);
$total_stmt->bindParam(':search', $searchTerm, PDO::PARAM_STR);
$total_stmt->bindParam(':id', $searchId, PDO::PARAM_INT);
if ($balance_min !== null) { $total_stmt->bindParam(':balance_min', $balance_min); }
if ($balance_max !== null) { $total_stmt->bindParam(':balance_max', $balance_max); }
if ($has_created_at) {
    if ($start_date !== '') { $total_stmt->bindParam(':start_date', $start_date); }
    if ($end_date !== '') { $total_stmt->bindParam(':end_date', $endDateTime); }
}
if ($email_q !== '') { $total_stmt->bindParam(':email_q', $emailLike, PDO::PARAM_STR); }
if ($phone_q !== '') { $total_stmt->bindParam(':phone_q', $phoneLike, PDO::PARAM_STR); }
if ($has_role_col && $role_q !== '') { $total_stmt->bindParam(':role_q', $role_q, PDO::PARAM_STR); }
if ($has_last_login) {
    if ($last_login_start !== '') { $total_stmt->bindParam(':ll_start', $last_login_start); }
    if ($last_login_end !== '') { $total_stmt->bindParam(':ll_end', $llEnd); }
}
$total_stmt->execute();
$total_users = $total_stmt->fetchColumn();

$total_pages = ceil($total_users / $limit); // Toplam sayfa sayısını hesapla

// Sayfalama aralığını ayarla
$visible_pages = 5; // Gösterilecek maksimum sayfa sayısı
$start_page = max(1, $page - floor($visible_pages / 2));
$end_page = min($total_pages, $start_page + $visible_pages - 1);
$start_page = max(1, $end_page - $visible_pages + 1);

// Sunucu tarafı CSV/XLSX export (tüm filtreleri uygula, sayfalama yok)
try {
    $export = isset($_GET['export']) ? strtolower(trim($_GET['export'])) : '';
    if ($export && in_array($export, ['csv','xlsx'], true)) {
        // Ek RBAC: rapor dışa aktarımı için özellikle izin iste
        if (!has_permission('reports_export')) {
            header('Content-Type: text/plain; charset=utf-8');
            http_response_code(403);
            echo 'Bu işlem için yetkiniz yok (reports_export).';
            exit;
        }
        // Export edilecek sütunları dinamik belirle
        $selectCols = ['id','first_name','surname','username','email','phone','ana_bakiye','tc_kimlik_no'];
        if ($has_created_at) { $selectCols[] = 'created_at'; }
        if ($has_last_login) { $selectCols[] = 'last_login'; }
        if ($has_is_frozen) { $selectCols[] = 'is_frozen'; }
        if ($has_role_col) { $selectCols[] = 'role'; }
        $sel = implode(',', array_map(function($c){ return $c; }, $selectCols));
        $exportSql = "SELECT $sel FROM kullanicilar WHERE $where ORDER BY id DESC";
        $estmt = $pdo->prepare($exportSql);
        // Parametreleri yeniden bağla
        $estmt->bindParam(':search', $searchTerm, PDO::PARAM_STR);
        $estmt->bindParam(':id', $searchId, PDO::PARAM_INT);
        if ($balance_min !== null) { $estmt->bindParam(':balance_min', $balance_min); }
        if ($balance_max !== null) { $estmt->bindParam(':balance_max', $balance_max); }
        if ($has_created_at) {
            if ($start_date !== '') { $estmt->bindParam(':start_date', $start_date); }
            if ($end_date !== '') { $endDateTime = $end_date . ' 23:59:59'; $estmt->bindParam(':end_date', $endDateTime); }
        }
        if ($email_q !== '') { $emailLike = "%$email_q%"; $estmt->bindParam(':email_q', $emailLike, PDO::PARAM_STR); }
        if ($phone_q !== '') { $phoneLike = "%$phone_q%"; $estmt->bindParam(':phone_q', $phoneLike, PDO::PARAM_STR); }
        if ($has_role_col && $role_q !== '') { $estmt->bindParam(':role_q', $role_q, PDO::PARAM_STR); }
        if ($has_last_login) {
            if ($last_login_start !== '') { $estmt->bindParam(':ll_start', $last_login_start); }
            if ($last_login_end !== '') { $llEnd = $last_login_end . ' 23:59:59'; $estmt->bindParam(':ll_end', $llEnd); }
        }
        $estmt->execute();
        $rows = $estmt->fetchAll(PDO::FETCH_ASSOC);

        // Hassas alanları izne göre maskele
        $canSeeSensitive = has_permission('users_view_sensitive');
        foreach ($rows as &$r) {
            if (!$canSeeSensitive) {
                if (array_key_exists('email', $r)) { $r['email'] = mask_email($r['email'] ?? ''); }
                if (array_key_exists('phone', $r)) { $r['phone'] = mask_phone($r['phone'] ?? ''); }
                if (array_key_exists('tc_kimlik_no', $r)) { $r['tc_kimlik_no'] = mask_tc($r['tc_kimlik_no'] ?? ''); }
            }
        }
        unset($r);

        // Başlıklar
        $headers = array_map(function($c){
            switch ($c) {
                case 'id': return 'ID';
                case 'first_name': return 'Ad';
                case 'surname': return 'Soyad';
                case 'username': return 'Kullanıcı Adı';
                case 'email': return 'Email';
                case 'phone': return 'Telefon';
                case 'ana_bakiye': return 'Ana Bakiye';
                case 'tc_kimlik_no': return 'TC Kimlik No';
                case 'created_at': return 'Oluşturulma';
                case 'last_login': return 'Son Giriş';
                case 'is_frozen': return 'Dondurulmuş';
                case 'role': return 'Rol';
                default: return $c;
            }
        }, $selectCols);

        $filenameBase = 'kullanicilar_' . date('Ymd_His');
        event_log('export', 'users_export', ['format' => $export, 'count' => count($rows)]);
        if ($export === 'csv') {
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename="' . $filenameBase . '.csv"');
            $out = fopen('php://output', 'w');
            fputcsv($out, $headers);
            foreach ($rows as $r) {
                $line = [];
                foreach ($selectCols as $c) { $line[] = $r[$c] ?? ''; }
                fputcsv($out, $line);
            }
            fclose($out);
            exit;
        } else {
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment; filename="' . $filenameBase . '.xls"');
            echo "<?xml version=\"1.0\"?>\n";
            echo "<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
            echo "<Worksheet ss:Name=\"Kullanicilar\"><Table>";
            echo "<Row>"; foreach ($headers as $h) { echo "<Cell><Data ss:Type=\"String\">".htmlspecialchars($h)."</Data></Cell>"; } echo "</Row>";
            foreach ($rows as $r) {
                echo "<Row>";
                foreach ($selectCols as $c) {
                    $val = $r[$c] ?? '';
                    $type = is_numeric($val) && $c==='ana_bakiye' ? 'Number' : 'String';
                    echo "<Cell><Data ss:Type=\"$type\">".htmlspecialchars((string)$val)."</Data></Cell>";
                }
                echo "</Row>";
            }
            echo "</Table></Worksheet></Workbook>";
            exit;
        }
    }
} catch (Throwable $e) {
    header('Content-Type: text/plain; charset=utf-8');
    http_response_code(500);
    echo 'Export hata: ' . htmlspecialchars($e->getMessage());
    exit;
}
?>


<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kullanıcı Listesi</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <!-- SweetAlert2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.9/dist/sweetalert2.min.css" rel="stylesheet">

<!-- SweetAlert2 JS -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.9/dist/sweetalert2.min.js"></script>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <link rel="stylesheet" href="styles.css">
</head>
<body>
     <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <?php include 'sidebar.php'; ?>

            <div class="col-md-10 p-4">
                <?php include __DIR__ . '/topbar.php'; ?>
                <h2 class="mb-4">Kullanıcı Listesi</h2>

                <!-- Arama Kutusu -->
<!-- Arama Kutusu -->
<form class="search-bar" method="GET" action="">
    <div class="row g-2 align-items-end">
        <div class="col-md-4">
            <label class="form-label">Hızlı Arama</label>
            <input type="text" name="search" class="form-control" placeholder="ID veya kullanıcı adı" value="<?= htmlspecialchars($search) ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label">Min Bakiye</label>
            <input type="number" step="0.01" name="balance_min" class="form-control" value="<?= htmlspecialchars($_GET['balance_min'] ?? '') ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label">Max Bakiye</label>
            <input type="number" step="0.01" name="balance_max" class="form-control" value="<?= htmlspecialchars($_GET['balance_max'] ?? '') ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label">Başlangıç Tarihi</label>
            <input type="date" name="start_date" class="form-control" value="<?= htmlspecialchars($_GET['start_date'] ?? '') ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label">Bitiş Tarihi</label>
            <input type="date" name="end_date" class="form-control" value="<?= htmlspecialchars($_GET['end_date'] ?? '') ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label">E-Posta</label>
            <input type="text" name="email" class="form-control" placeholder="email içerir" value="<?= htmlspecialchars($_GET['email'] ?? '') ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label">Telefon</label>
            <input type="text" name="phone" class="form-control" placeholder="telefon içerir" value="<?= htmlspecialchars($_GET['phone'] ?? '') ?>">
        </div>
        <?php if (!empty($has_role_col) && $has_role_col): ?>
        <div class="col-md-2">
            <label class="form-label">Rol</label>
            <input type="text" name="role" class="form-control" placeholder="ör. vip" value="<?= htmlspecialchars($_GET['role'] ?? '') ?>">
        </div>
        <?php endif; ?>
        <?php if (!empty($has_last_login) && $has_last_login): ?>
        <div class="col-md-2">
            <label class="form-label">Son Giriş Başlangıç</label>
            <input type="date" name="last_login_start" class="form-control" value="<?= htmlspecialchars($_GET['last_login_start'] ?? '') ?>">
        </div>
        <div class="col-md-2">
            <label class="form-label">Son Giriş Bitiş</label>
            <input type="date" name="last_login_end" class="form-control" value="<?= htmlspecialchars($_GET['last_login_end'] ?? '') ?>">
        </div>
        <?php endif; ?>
        <div class="col-md-12">
            <button class="btn btn-primary" type="submit">Filtrele</button>
            <a class="btn btn-outline-secondary" href="users.php">Temizle</a>
            <?php $qs = http_build_query(array_merge($_GET, ['export' => null])); ?>
            <div class="btn-group ms-2" role="group" aria-label="Export">
                <a class="btn btn-outline-success" href="users.php?<?= htmlspecialchars($qs . '&export=csv') ?>">Kullanıcılar CSV</a>
                <a class="btn btn-outline-success" href="users.php?<?= htmlspecialchars($qs . '&export=xlsx') ?>">Kullanıcılar XLSX</a>
            </div>
        </div>
    </div>
</form>

                <!-- Hızlı Araçlar: Hızlı Arama, Sütunlar, Görünüm Kaydet/Yükle, CSV -->
                <div class="d-flex align-items-center gap-2 mb-3">
                    <input type="text" id="quickSearch" class="form-control" placeholder="Tabloda hızlı arama..." style="max-width:300px">
                    <div class="dropdown">
                        <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Sütunlar</button>
                        <div class="dropdown-menu p-3" id="columnMenu" style="min-width:260px"></div>
                    </div>
                    <button class="btn btn-outline-primary" id="saveViewBtn">Görünümü Kaydet</button>
                    <button class="btn btn-outline-secondary" id="loadViewBtn">Görünümü Yükle</button>
                    <button class="btn btn-outline-success" id="exportCsvBtn">CSV Dışa Aktar</button>
                    <div class="vr"></div>
                    <button class="btn btn-outline-dark" id="pinIdBtn">ID’yi Sabitle</button>
                    <button class="btn btn-outline-dark" id="pinUserBtn">Kullanıcı Adını Sabitle</button>
                    <div class="form-check ms-3">
                        <input class="form-check-input" type="checkbox" id="showDeleted" <?php echo $include_deleted ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="showDeleted">Silinenleri göster</label>
                    </div>
                </div>

                <!-- Seçili satırlar araç çubuğu -->
                <div class="d-flex align-items-center gap-2 mb-2" id="bulkBar" style="display:none">
                    <span class="badge bg-dark" id="selectedCount">0 seçili</span>
                    <button class="btn btn-outline-success btn-sm" id="exportSelectedBtn">Seçilileri CSV</button>
                    <button class="btn btn-outline-secondary btn-sm" id="copyIdsBtn">ID’leri Kopyala</button>
                    <div class="vr"></div>
                    <button class="btn btn-outline-warning btn-sm" id="bulkFreezeBtn">Seçilileri Dondur</button>
                    <button class="btn btn-outline-info btn-sm" id="bulkUnfreezeBtn">Seçilileri Çöz</button>
                    <button class="btn btn-outline-danger btn-sm" id="bulkDeleteBtn">Seçilileri Sil</button>
                    <button class="btn btn-outline-primary btn-sm" id="bulkRestoreBtn">Seçilileri Geri Al</button>
                </div>


                <div class="table-responsive">
                    <table class="table table-striped table-hover table-sticky" id="usersTable">
                        <thead>
                            <tr>
                                <th class="select-col"><input type="checkbox" id="selectAll"></th>
                                <th>ID</th>
                                <th class="col-username">Kullanıcı Adı</th>
                            <th>Ana Bakiye</th>
                            <th>Durum</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                       <tbody>
                            <?php foreach ($users as $user): ?>
                            <tr>
                                <td class="select-col"><input type="checkbox" class="row-select" value="<?= htmlspecialchars($user['id']) ?>"></td>
                                <td><?= htmlspecialchars($user['id']) ?></td>
                            <td class="col-username"><?= htmlspecialchars($user['username']) ?></td>
                                <td><?= htmlspecialchars($user['ana_bakiye']) ?></td>
                            <td>
                                <?php
                                  $frozen = isset($user['is_frozen']) ? (int)$user['is_frozen'] : 0;
                                  $deleted = isset($user['deleted_at']) && !empty($user['deleted_at']);
                                  $emailVerified = isset($user['email_verified_at']) && !empty($user['email_verified_at']);
                                  $phoneVerified = isset($user['phone_verified_at']) && !empty($user['phone_verified_at']);
                                  if ($deleted) {
                                      echo '<span class="badge bg-secondary">Silinmiş</span>';
                                  } else if ($frozen) {
                                      echo '<span class="badge bg-danger">Dondurulmuş</span>';
                                  } else {
                                      echo '<span class="badge bg-success">Aktif</span>';
                                  }
                                  // Doğrulama durum rozetleri
                                  if ($emailVerified) {
                                      echo ' <span class="badge bg-success ms-1">E-Posta Onaylı</span>';
                                  } else {
                                      echo ' <span class="badge bg-warning text-dark ms-1">E-Posta Onaysız</span>';
                                  }
                                  if ($phoneVerified) {
                                      echo ' <span class="badge bg-success ms-1">Telefon Onaylı</span>';
                                  } else {
                                      echo ' <span class="badge bg-warning text-dark ms-1">Telefon Onaysız</span>';
                                  }
                                ?>
                            </td>
                            <td class="actions-cell">
                                    <button class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#editUserModal" 
                                    data-id="<?= $user['id'] ?>"
                                    data-first-name="<?= $user['first_name'] ?>"
                                    data-surname="<?= $user['surname'] ?>"
                                    data-username="<?= $user['username'] ?>"
                                    data-email="<?= $user['email'] ?>"
                                    data-phone="<?= $user['phone'] ?>"
                                    data-ana-bakiye="<?= $user['ana_bakiye'] ?>"
                                    data-tc="<?= $user['tc_kimlik_no'] ?>">Düzenle</button>
                                    <?php if (has_permission('users_freeze')): ?>
                                    <?php if (!empty($frozen)): ?>
                                        <button class="btn btn-success btn-sm btn-unfreeze" data-id="<?= $user['id'] ?>">Çöz</button>
                                    <?php else: ?>
                                        <button class="btn btn-outline-danger btn-sm btn-freeze" data-id="<?= $user['id'] ?>">Dondur</button>
                                    <?php endif; ?>
                                    <?php endif; ?>
                                    <?php if (has_permission('user_delete')): ?>
                                        <?php if (!empty($deleted)): ?>
                                            <button class="btn btn-outline-primary btn-sm btn-restore" data-id="<?= $user['id'] ?>">Geri Al</button>
                                        <?php else: ?>
                                            <button class="btn btn-outline-secondary btn-sm btn-delete" data-id="<?= $user['id'] ?>">Sil</button>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                    <?php if (!$emailVerified && !empty($user['email'])): ?>
                                        <button class="btn btn-outline-primary btn-sm btn-send-email-verif" data-id="<?= $user['id'] ?>">E-Posta Kod</button>
                                    <?php endif; ?>
                                    <?php if (!$phoneVerified && !empty($user['phone'])): ?>
                                        <button class="btn btn-outline-primary btn-sm btn-send-sms-verif" data-id="<?= $user['id'] ?>">SMS Kod</button>
                                    <?php endif; ?>
                                    <button class="btn btn-outline-dark btn-sm btn-prepare-2fa" data-id="<?= $user['id'] ?>">2FA Hazırla</button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Sayfalama -->
                <nav aria-label="Sayfa Navigasyonu">
                    <ul class="pagination justify-content-center">
                        <?php if ($page > 1): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?= $page - 1 ?>&search=<?= htmlspecialchars($search) ?>" aria-label="Önceki">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                        <?php endif; ?>

                        <?php for ($i = $start_page; $i <= $end_page; $i++): ?>
                            <li class="page-item <?= ($i === $page) ? 'active' : '' ?>">
                                <a class="page-link" href="?page=<?= $i ?>&search=<?= htmlspecialchars($search) ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>

                        <?php if ($page < $total_pages): ?>
                            <li class="page-item">
                                <a class="page-link" href="?page=<?= $page + 1 ?>&search=<?= htmlspecialchars($search) ?>" aria-label="Sonraki">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        <?php endif; ?>
                    </ul>
                </nav>
            </div>
        </div>
    </div>

<!-- Modal for editing user -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content bg-black text-light">
            <div class="modal-header bg-black text-light">
                <h5 class="modal-title" id="editUserModalLabel">Kullanıcı Düzenle</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body bg-black text-light">
                <form id="editUserForm">
                    
                    <input type="hidden" id="userId" name="userId">
                    <div class="mb-3">
                        <label for="firstName" class="form-label">Ad</label>
                        <input type="text" class="form-control" id="firstName" name="firstName" required>
                    </div>
                    <div class="mb-3">
                        <label for="surname" class="form-label">Soyad</label>
                        <input type="text" class="form-control" id="surname" name="surname" required>
                    </div>
                    <div class="mb-3">
                        <label for="username" class="form-label">Kullanıcı Adı</label>
                        <input type="text" class="form-control" id="username" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">Email</label>
                        <input type="email" class="form-control" id="email" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label for="phone" class="form-label">Telefon</label>
                        <input type="text" class="form-control" id="phone" name="phone" required>
                    </div>
                    <div class="mb-3">
                        <label for="anaBakiye" class="form-label">Ana Bakiye</label>
                        <input type="text" class="form-control" id="anaBakiye" name="anaBakiye" required>
                    </div>
                    <div class="mb-3">
                        <label for="tcKimlikNo" class="form-label">TC Kimlik No</label>
                        <input type="text" class="form-control" id="tcKimlikNo" name="tcKimlikNo" required>
                    </div>
                    <!-- Para Ekleme -->
                    <div class="mb-3">
                        <label for="paraEkle" class="form-label">Para Ekle</label>
                        <input type="text" class="form-control" id="paraEkle" name="paraEkle">
                    </div>
                    <!-- Şifre Değiştirme -->
                    <div class="mb-3">
                        <label for="password" class="form-label">Yeni Şifre</label>
                        <input type="password" class="form-control" id="password" name="password">
                        <small>Şifreyi değiştirmek istemiyorsanız boş bırakabilirsiniz.</small>
                    </div>
                    <button type="submit" class="btn btn-primary">Kaydet</button>
                </form>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.querySelectorAll('.btn-warning').forEach(button => {
    button.addEventListener('click', function() {
        const id = this.getAttribute('data-id');
        const firstName = this.getAttribute('data-first-name');
        const surname = this.getAttribute('data-surname');
        const username = this.getAttribute('data-username');
        const email = this.getAttribute('data-email');
        const phone = this.getAttribute('data-phone');
        const anaBakiye = this.getAttribute('data-ana-bakiye');
        const tcKimlikNo = this.getAttribute('data-tc');

        // Modal içindeki alanları doldur
        document.getElementById('userId').value = id;
        document.getElementById('firstName').value = firstName;
        document.getElementById('surname').value = surname;
        document.getElementById('username').value = username;
        document.getElementById('email').value = email;
        document.getElementById('phone').value = phone;
        document.getElementById('anaBakiye').value = anaBakiye;
        document.getElementById('tcKimlikNo').value = tcKimlikNo;

        // Modal'ı aç
        const editUserModal = new bootstrap.Modal(document.getElementById('editUserModal'));
        editUserModal.show();
    });
});

document.getElementById('editUserForm').addEventListener('submit', function (e) {
    e.preventDefault(); // Sayfa yenilenmesini engelle

    const formData = new FormData(this); // Form verilerini al

    fetch('', {  // Bu sayfaya aynı yerden POST gönderiyoruz
        method: 'POST',
        body: formData
    })
    .then(response => response.json())  // JSON formatında cevap al
    .then(data => {
        if (data && data.success) {
          Swal.fire({
              title: 'Başarılı!',
              text: 'Kullanıcı başarıyla güncellendi!',
              icon: 'success',
              confirmButtonText: 'Tamam'
          }).then((result) => { if (result.isConfirmed) location.reload(); });
        } else {
          const msg = (data && data.error) ? data.error : 'Güncelleme başarısız.';
          Swal.fire({
              title: 'Hata',
              text: msg,
              icon: 'error',
              confirmButtonText: 'Tamam'
          });
        }
    })
    .catch(error => {
        Swal.fire({
            title: 'Hata',
            text: 'İstek sırasında bir hata oluştu.',
            icon: 'error',
            confirmButtonText: 'Tamam'
        });
    });
});
</script>

<script src="admin.js"></script>

<script>
// Tekil işlem butonları (freeze/unfreeze/delete/restore/2FA hazırlık / doğrulama kodu gönderimi)
document.addEventListener('click', function(e){
  const btn = e.target.closest('.btn-freeze, .btn-unfreeze, .btn-delete, .btn-restore, .btn-prepare-2fa, .btn-send-email-verif, .btn-send-sms-verif');
  if(!btn) return;
  const id = btn.getAttribute('data-id');
  let action = '';
  let confirmText = '';
  if(btn.classList.contains('btn-freeze')) { action = 'freeze'; confirmText = 'Hesabı dondurmak istiyor musunuz?'; }
  else if(btn.classList.contains('btn-unfreeze')) { action = 'unfreeze'; confirmText = 'Dondurmayı çözmek istiyor musunuz?'; }
  else if(btn.classList.contains('btn-delete')) { action = 'delete'; confirmText = 'Bu hesabı silmek (soft delete) istiyor musunuz?'; }
  else if(btn.classList.contains('btn-restore')) { action = 'restore'; confirmText = 'Bu hesabı geri almak istiyor musunuz?'; }
  else if(btn.classList.contains('btn-send-email-verif')) { action = 'send_email_verif'; confirmText = 'E-posta doğrulama kodu göndermek istiyor musunuz?'; }
  else if(btn.classList.contains('btn-send-sms-verif')) { action = 'send_sms_verif'; confirmText = 'SMS doğrulama kodu göndermek istiyor musunuz?'; }
  else if(btn.classList.contains('btn-prepare-2fa')) { action = 'prepare_2fa'; }

  if(action === 'prepare_2fa') {
    fetch('', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:`action=prepare_2fa&id=${encodeURIComponent(id)}` })
      .then(r=>r.json()).then(data=>{
        if(data && data.success){
          const uri = data.otpauth || '';
          const secret = data.secret || '';
          const qr = `https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl=${encodeURIComponent(uri)}`;
          Swal.fire({ title:'2FA Secret Hazır', html:`<div style="text-align:left">Secret: <code>${secret}</code><br>URI: <code>${uri}</code><br><img src="${qr}" alt="QR"/></div>`, icon:'info' });
        } else {
          Swal.fire({ title:'Hata', text:(data && data.error) || '2FA hazırlık başarısız', icon:'error' });
        }
      }).catch(()=> Swal.fire({ title:'Hata', text:'İstek başarısız', icon:'error' }));
    return;
  }

  Swal.fire({ title:'Onay', text: confirmText, icon:'question', showCancelButton:true, confirmButtonText:'Evet', cancelButtonText:'Hayır' })
    .then(res=>{
      if(!res.isConfirmed) return;
      fetch('', { method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:`action=${encodeURIComponent(action)}&id=${encodeURIComponent(id)}` })
        .then(r=>r.json()).then(data=>{
          if(data && data.success){
            // Gönderim uçları için kullanıcıya bilgi göster
            if(action === 'send_email_verif' || action === 'send_sms_verif'){
              const sent = (data.sent === true);
              Swal.fire({ title: 'Gönderildi', text: sent ? 'Kod başarıyla gönderildi.' : 'Kod oluşturuldu, gönderim yapılamadı.', icon: sent ? 'success' : 'warning' });
            } else {
              location.reload();
            }
          }
          else { Swal.fire({ title:'Hata', text:(data && data.error)||'İşlem başarısız', icon:'error' }); }
        }).catch(()=> Swal.fire({ title:'Hata', text:'İstek başarısız', icon:'error' }));
    });
});

// Users tablo geliştirmeleri: hızlı arama, sütun görünürlüğü, görünüm kaydı, CSV export
(function(){
  const table = document.querySelector('.table.table-striped.table-hover');
  if(!table) return;
  const pageKey = 'users_view_v1';
  const quickSearch = document.getElementById('quickSearch');
  const columnMenu = document.getElementById('columnMenu');
  const saveBtn = document.getElementById('saveViewBtn');
  const loadBtn = document.getElementById('loadViewBtn');
  const exportBtn = document.getElementById('exportCsvBtn');
  const showDeleted = document.getElementById('showDeleted');

  const ths = Array.from(table.querySelectorAll('thead th'));
  const rows = Array.from(table.querySelectorAll('tbody tr'));

  // Sütun menüsü oluştur
  const initialVisible = ths.map(() => true);
  columnMenu.innerHTML = ths.map((th, idx) => {
    const label = th.textContent.trim() || ('Sütun ' + (idx+1));
    return `<div class="form-check">
      <input class="form-check-input column-toggle" type="checkbox" data-col="${idx}" id="col_${idx}" checked>
      <label class="form-check-label" for="col_${idx}">${label}</label>
    </div>`;
  }).join('');

  function setColumnVisible(index, visible){
    const display = visible ? '' : 'none';
    const header = ths[index];
    if (header) header.style.display = display;
    rows.forEach(row => {
      const cells = row.children;
      if (cells[index]) cells[index].style.display = display;
    });
  }

  // Toggle olayları
  columnMenu.addEventListener('change', (e)=>{
    const input = e.target.closest('.column-toggle');
    if(!input) return;
    const idx = parseInt(input.dataset.col,10);
    setColumnVisible(idx, input.checked);
  });

  // Hızlı arama
  function normalize(t){ return (t||'').toLowerCase(); }
  function rowMatches(row, term){
    if(!term) return true;
    const txt = normalize(row.textContent);
    return txt.includes(term);
  }
  quickSearch && quickSearch.addEventListener('input', ()=>{
    const term = normalize(quickSearch.value);
    rows.forEach(row => {
      row.style.display = rowMatches(row, term) ? '' : 'none';
    });
  });

  // Görünümü kaydet/yükle
  saveBtn && saveBtn.addEventListener('click', ()=>{
    const visibles = Array.from(columnMenu.querySelectorAll('.column-toggle')).map(inp => inp.checked);
    const data = { search: quickSearch ? quickSearch.value : '', visible: visibles };
    localStorage.setItem(pageKey, JSON.stringify(data));
  });
  loadBtn && loadBtn.addEventListener('click', ()=>{
    const raw = localStorage.getItem(pageKey);
    if(!raw) return;
    try{
      const data = JSON.parse(raw);
      if(quickSearch) {
        quickSearch.value = data.search || '';
        const term = normalize(quickSearch.value);
        rows.forEach(row => { row.style.display = rowMatches(row, term) ? '' : 'none'; });
      }
      const visibles = Array.isArray(data.visible) ? data.visible : initialVisible;
      Array.from(columnMenu.querySelectorAll('.column-toggle')).forEach((inp, i)=>{
        const v = visibles[i] !== false; // default visible
        inp.checked = v;
        setColumnVisible(i, v);
      });
    }catch(err){ /* yoksay */ }
  });

  // Silinenleri göster togglesi
  showDeleted && showDeleted.addEventListener('change', ()=>{
    const url = new URL(window.location.href);
    url.searchParams.set('include_deleted', showDeleted.checked ? '1' : '0');
    window.location.href = url.toString();
  });

  // CSV dışa aktar (görünür sütunlar)
  exportBtn && exportBtn.addEventListener('click', ()=>{
    const visibleMap = Array.from(columnMenu.querySelectorAll('.column-toggle')).map(inp => inp.checked);
    const headers = ths.map((th,i)=> visibleMap[i] ? th.textContent.trim() : null).filter(Boolean);
    const lines = [];
    lines.push(headers.join(','));
    rows.forEach(row => {
      if(row.style.display==='none') return; // filtrelenmiş satırı atla
      const cells = Array.from(row.children).map((td,i)=> visibleMap[i] ? '"'+(td.textContent.trim().replace(/"/g,'""'))+'"' : null).filter(v=> v!==null);
      lines.push(cells.join(','));
    });
    const blob = new Blob([lines.join('\n')], {type: 'text/csv;charset=utf-8;'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'kullanicilar.csv';
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(url);
  });
})();
</script>

<script>
// Seçim, toplu araçlar ve sütun sabitleme
(function(){
  const table = document.getElementById('usersTable');
  if(!table) return;
  const tbody = table.querySelector('tbody');

  // Satır seçimleri ve toplu araçlar
  const selectAll = document.getElementById('selectAll');
  const bulkBar = document.getElementById('bulkBar');
  const selectedCount = document.getElementById('selectedCount');
  const exportSelectedBtn = document.getElementById('exportSelectedBtn');
  const copyIdsBtn = document.getElementById('copyIdsBtn');
  const bulkFreezeBtn = document.getElementById('bulkFreezeBtn');
  const bulkUnfreezeBtn = document.getElementById('bulkUnfreezeBtn');
  const bulkDeleteBtn = document.getElementById('bulkDeleteBtn');
  const bulkRestoreBtn = document.getElementById('bulkRestoreBtn');

  function updateBulkBar(){
    const selected = tbody.querySelectorAll('.row-select:checked');
    const count = selected.length;
    selectedCount.textContent = `${count} seçili`;
    bulkBar.style.display = count > 0 ? 'flex' : 'none';
  }
  selectAll.addEventListener('change', ()=>{
    const checks = tbody.querySelectorAll('.row-select');
    checks.forEach(c=> c.checked = selectAll.checked);
    updateBulkBar();
  });
  tbody.addEventListener('change', (e)=>{
    if(e.target.matches('.row-select')){
      const all = Array.from(tbody.querySelectorAll('.row-select'));
      const sel = all.filter(c=>c.checked).length;
      selectAll.checked = sel === all.length;
      updateBulkBar();
    }
  });
  exportSelectedBtn.addEventListener('click', ()=>{
    const selected = Array.from(tbody.querySelectorAll('.row-select:checked'));
    if(selected.length === 0){ window.notify && window.notify('info','Seçili satır yok'); return; }
    const rows = selected.map(ch => ch.closest('tr'));
    exportRowsToCsv(rows, 'users_selected.csv');
  });
  copyIdsBtn.addEventListener('click', async ()=>{
    const ids = Array.from(tbody.querySelectorAll('.row-select:checked')).map(ch=>ch.value);
    if(ids.length===0){ window.notify && window.notify('info','Seçili ID yok'); return; }
    try{ await navigator.clipboard.writeText(ids.join(',')); window.notify && window.notify('success','ID’ler kopyalandı'); }catch(err){ window.notify && window.notify('error','Kopyalama başarısız'); }
  });

  async function performBulk(op, confirmText){
    const ids = Array.from(tbody.querySelectorAll('.row-select:checked')).map(ch=>ch.value);
    if(ids.length===0){ Swal.fire({title:'Bilgi', text:'Seçili satır yok', icon:'info'}); return; }
    const ok = await Swal.fire({ title:'Onay', text:confirmText, icon:'question', showCancelButton:true, confirmButtonText:'Evet', cancelButtonText:'İptal' }).then(r=>r.isConfirmed);
    if(!ok) return;
    const fd = new FormData();
    fd.append('action','bulk');
    fd.append('op', op);
    fd.append('ids', ids.join(','));
    fetch('users.php', { method:'POST', body: fd })
      .then(r=>r.json())
      .then(data=>{
        if(data && data.success){ location.reload(); }
        else { Swal.fire({ title:'Hata', text:(data && data.error)||'Toplu işlem başarısız', icon:'error' }); }
      }).catch(()=> Swal.fire({ title:'Hata', text:'İstek başarısız', icon:'error' }));
  }

  bulkFreezeBtn && bulkFreezeBtn.addEventListener('click', ()=> performBulk('freeze','Seçilileri dondurmak istediğinize emin misiniz?'));
  bulkUnfreezeBtn && bulkUnfreezeBtn.addEventListener('click', ()=> performBulk('unfreeze','Seçililerin donmasını çözmek istediğinize emin misiniz?'));
  bulkDeleteBtn && bulkDeleteBtn.addEventListener('click', ()=> performBulk('delete','Seçilileri silmek (yumuşak sil) istediğinize emin misiniz?'));
  bulkRestoreBtn && bulkRestoreBtn.addEventListener('click', ()=> performBulk('restore','Seçilileri geri almak istediğinize emin misiniz?'));

  function exportRowsToCsv(rows, filename){
    const headers = Array.from(table.querySelector('thead tr').children).map(th=>th.textContent.trim());
    const headerOut = headers.filter(h=>h && h.toLowerCase()!=='işlemler');
    const data = rows.map(tr => {
      const cells = Array.from(tr.children).map(td=>td.textContent.trim());
      // Seçim sütunu ve işlemler sütununu çıkar
      const filtered = cells.filter((_,i)=> i!==0 && headers[i] && headers[i].toLowerCase()!=='işlemler');
      return filtered;
    });
    const csv = [headerOut.join(','), ...data.map(row => row.map(v=>`"${v.replace(/"/g,'"')}`+`"`).join(','))].join('\n');
    const blob = new Blob([csv], {type:'text/csv;charset=utf-8;'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a'); a.href = url; a.download = filename; a.click(); URL.revokeObjectURL(url);
  }

  // Sütun sabitleme (pin-left)
  const pinIdBtn = document.getElementById('pinIdBtn');
  const pinUserBtn = document.getElementById('pinUserBtn');
  const PIN_KEY = 'users_pins_v1';
  let pinned = { id:false, user:false };

  // Persisted pin durumunu yükle
  try{
    const saved = JSON.parse(localStorage.getItem(PIN_KEY) || '{}');
    pinned = { id: !!saved.id, user: !!saved.user };
  }catch(e){}

  function recalcPinned(){
    const theadRow = table.querySelector('thead tr');
    const heads = Array.from(theadRow.children);
    let left = 0;
    heads.forEach((th)=>{
      const isPinned = th.classList.contains('pin-left');
      if(isPinned){ th.style.left = left + 'px'; left += th.offsetWidth; }
      else { th.style.left = ''; }
    });
    Array.from(tbody.querySelectorAll('tr')).forEach(tr=>{
      let leftRow = 0; const tds = Array.from(tr.children);
      tds.forEach((td)=>{
        const isPinned = td.classList.contains('pin-left');
        if(isPinned){ td.style.left = leftRow + 'px'; leftRow += td.offsetWidth; }
        else { td.style.left = ''; }
      });
    });
  }
  function togglePin(col){
    const theadRow = table.querySelector('thead tr');
    const heads = Array.from(theadRow.children);
    const rows = Array.from(tbody.querySelectorAll('tr'));
    if(col==='id'){
      pinned.id = !pinned.id;
      // ID sütunu index 1 (0 seçim sütunu)
      heads[1].classList.toggle('pin-left', pinned.id); heads[1].classList.toggle('pin-shadow', pinned.id);
      rows.forEach(tr=>{ tr.children[1].classList.toggle('pin-left', pinned.id); tr.children[1].classList.toggle('pin-shadow', pinned.id); });
    } else if(col==='user'){
      const idx = heads.findIndex(h=> h.classList.contains('col-username'));
      if(idx<0) return;
      pinned.user = !pinned.user;
      heads[idx].classList.toggle('pin-left', pinned.user); heads[idx].classList.toggle('pin-shadow', pinned.user);
      rows.forEach(tr=>{ tr.children[idx].classList.toggle('pin-left', pinned.user); tr.children[idx].classList.toggle('pin-shadow', pinned.user); });
    }
    recalcPinned();
    // Kaydet
    try{ localStorage.setItem(PIN_KEY, JSON.stringify(pinned)); }catch(e){}
  }
  pinIdBtn && pinIdBtn.addEventListener('click', ()=> togglePin('id'));
  pinUserBtn && pinUserBtn.addEventListener('click', ()=> togglePin('user'));
  window.addEventListener('resize', recalcPinned);
  // İlk yüklemede mevcut pinleri uygula
  if(pinned.id){ togglePin('id'); }
  if(pinned.user){ togglePin('user'); }

  // Ana bakiye hücrelerini vurgula
  (function(){
    const headCells = Array.from(table.querySelector('thead tr').children);
    const balIdx = headCells.findIndex(h=> (h.textContent||'').toLowerCase().includes('ana bakiye'));
    if(balIdx> -1){
      Array.from(tbody.querySelectorAll('tr')).forEach(tr=>{
        const cell = tr.children[balIdx];
        if(!cell) return;
        const val = parseFloat((cell.textContent||'').replace(/[^0-9.-]/g,''));
        cell.classList.remove('balance-zero','balance-low','balance-high');
        if(!isNaN(val)){
          if(val <= 0){ cell.classList.add('balance-zero'); }
          else if(val < 100){ cell.classList.add('balance-low'); }
          else if(val >= 10000){ cell.classList.add('balance-high'); }
        }
      });
    }
  })();
})();
</script>


</body>
</html>