<?php
session_start();
include 'config.php';
include 'auth.php';
include 'logger.php';

// Yetki kontrolü (Para Yatır İnceleme)
require_permission('deposit_review');

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: index.php");
    exit;
}

// Kayıtlı Görünümler Yardımcıları (Parayatır)
function load_saved_views_pt() {
    $file = __DIR__ . DIRECTORY_SEPARATOR . 'saved_views_parayatir.json';
    if (!file_exists($file)) { return []; }
    $json = file_get_contents($file);
    $data = json_decode($json, true);
    return is_array($data) ? $data : [];
}
function save_saved_views_pt($views) {
    $file = __DIR__ . DIRECTORY_SEPARATOR . 'saved_views_parayatir.json';
    file_put_contents($file, json_encode($views, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_view_pt'])) {
    
    $name = trim($_POST['view_name'] ?? '');
    if ($name !== '') {
        $views = load_saved_views_pt();
        $views[$name] = $_GET; // mevcut filtreleri kaydet
        save_saved_views_pt($views);
        header('Location: parayatir.php?msg=view-saved');
        exit;
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_view_pt'])) {
    
    $name = trim($_POST['delete_name'] ?? '');
    $views = load_saved_views_pt();
    if (isset($views[$name])) { unset($views[$name]); save_saved_views_pt($views); }
    header('Location: parayatir.php?msg=view-deleted');
    exit;
}

// Para yatırma listelerini al ve username bilgilerini ekle
$stmt = $pdo->query("
    SELECT 
        parayatir.*, 
        kullanicilar.username 
    FROM 
        parayatir 
    LEFT JOIN 
        kullanicilar 
    ON 
        parayatir.user_id = kullanicilar.id
");
$parayatir = $stmt->fetchAll();

// Filtreler (GET) ve yeni→eski sıralama
$start = isset($_GET['start']) ? trim($_GET['start']) : '';
$end = isset($_GET['end']) ? trim($_GET['end']) : '';
$type = isset($_GET['type']) ? trim($_GET['type']) : '';
$status = isset($_GET['status']) ? trim($_GET['status']) : '';
$bank = isset($_GET['bank']) ? trim($_GET['bank']) : '';
$minAmount = isset($_GET['min_amount']) ? trim($_GET['min_amount']) : '';
$maxAmount = isset($_GET['max_amount']) ? trim($_GET['max_amount']) : '';
$usernameQ = isset($_GET['username']) ? trim($_GET['username']) : '';
$perPage = isset($_GET['per_page']) && is_numeric($_GET['per_page']) ? max(10, min(200, (int)$_GET['per_page'])) : 50;
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$offset = ($page - 1) * $perPage;

$where = [];
$params = [];
if ($start !== '' && $end !== '') {
    $where[] = 'parayatir.tarih BETWEEN :start AND :end';
    $params[':start'] = $start . ' 00:00:00';
    $params[':end'] = $end . ' 23:59:59';
}
if ($type !== '') {
    $where[] = 'parayatir.tur = :tur';
    $params[':tur'] = $type;
}
if ($status !== '' && is_numeric($status)) {
    $where[] = 'parayatir.durum = :durum';
    $params[':durum'] = (int)$status;
}
if ($bank !== '') {
    $where[] = 'parayatir.banka = :banka';
    $params[':banka'] = $bank;
}
if ($minAmount !== '' && is_numeric($minAmount)) {
    $where[] = 'parayatir.miktar >= :min_amount';
    $params[':min_amount'] = (float)$minAmount;
}
if ($maxAmount !== '' && is_numeric($maxAmount)) {
    $where[] = 'parayatir.miktar <= :max_amount';
    $params[':max_amount'] = (float)$maxAmount;
}
if ($usernameQ !== '') {
    $where[] = 'kullanicilar.username LIKE :username';
    $params[':username'] = '%' . $usernameQ . '%';
}

$sql = "\n    SELECT \n        parayatir.*, \n        kullanicilar.username \n    FROM \n        parayatir \n    LEFT JOIN \n        kullanicilar \n    ON \n        parayatir.user_id = kullanicilar.id\n";
if (!empty($where)) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}
$sql .= ' ORDER BY parayatir.tarih DESC, parayatir.id DESC LIMIT :limit OFFSET :offset';

$stmt2 = $pdo->prepare($sql);
foreach ($params as $k => $v) { $stmt2->bindValue($k, $v); }
$stmt2->bindValue(':limit', $perPage, PDO::PARAM_INT);
$stmt2->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt2->execute();
$parayatir = $stmt2->fetchAll(PDO::FETCH_ASSOC);

// Toplam sayıyı ve toplam miktarı al (filtreye göre)
$countSql = "SELECT COUNT(*) FROM parayatir LEFT JOIN kullanicilar ON parayatir.user_id = kullanicilar.id";
if (!empty($where)) { $countSql .= ' WHERE ' . implode(' AND ', $where); }
$countStmt = $pdo->prepare($countSql);
foreach ($params as $k => $v) { $countStmt->bindValue($k, $v); }
$countStmt->execute();
$totalRows = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($totalRows / $perPage));

$sumSql = "SELECT COALESCE(SUM(parayatir.miktar),0) AS toplam_tutar FROM parayatir LEFT JOIN kullanicilar ON parayatir.user_id = kullanicilar.id";
if (!empty($where)) { $sumSql .= ' WHERE ' . implode(' AND ', $where); }
$sumStmt = $pdo->prepare($sumSql);
foreach ($params as $k => $v) { $sumStmt->bindValue($k, $v); }
$sumStmt->execute();
$toplamTutar = (float)$sumStmt->fetchColumn();

// Export (CSV / XLSX)
if (isset($_GET['export']) && in_array($_GET['export'], ['csv','xlsx'], true)) {
    $expSql = "\n    SELECT \n        parayatir.id, kullanicilar.username, parayatir.banka, parayatir.miktar, parayatir.tarih, parayatir.durum, parayatir.tur, parayatir.aciklama\n    FROM \n        parayatir \n    LEFT JOIN \n        kullanicilar \n    ON \n        parayatir.user_id = kullanicilar.id\n";
    if (!empty($where)) { $expSql .= ' WHERE ' . implode(' AND ', $where); }
    $expSql .= ' ORDER BY parayatir.tarih DESC, parayatir.id DESC';
    $expStmt = $pdo->prepare($expSql);
    foreach ($params as $k => $v) { $expStmt->bindValue($k, $v); }
    $expStmt->execute();
    $rows = $expStmt->fetchAll(PDO::FETCH_ASSOC);
    if ($_GET['export'] === 'csv') {
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="parayatir_' . ($start ?: 'all') . '_to_' . ($end ?: 'all') . '.csv"');
        $out = fopen('php://output', 'w');
        fputcsv($out, ['ID','Kullanıcı','Banka','Miktar','Tarih','Durum','Tür','Açıklama']);
        foreach ($rows as $r) {
            $durumTxt = ($r['durum']==='0' || $r['durum']==0) ? 'Bekliyor' : (($r['durum']==='1' || $r['durum']==1) ? 'Onaylı' : 'Reddedildi');
            fputcsv($out, [
                $r['id'],
                $r['username'],
                $r['banka'],
                $r['miktar'],
                $r['tarih'],
                $durumTxt,
                $r['tur'],
                $r['aciklama'],
            ]);
        }
        fclose($out);
    } else { // xlsx (Excel 2003 XML)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="parayatir_' . ($start ?: 'all') . '_to_' . ($end ?: 'all') . '.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=\"Parayatir\"><Table>";
        $headers = ['ID','Kullanıcı','Banka','Miktar','Tarih','Durum','Tür','Açıklama'];
        echo "<Row>"; foreach ($headers as $h) { echo "<Cell><Data ss:Type=\"String\">".htmlspecialchars($h)."</Data></Cell>"; } echo "</Row>";
        foreach ($rows as $r) {
            $durumTxt = ($r['durum']==='0' || $r['durum']==0) ? 'Bekliyor' : (($r['durum']==='1' || $r['durum']==1) ? 'Onaylı' : 'Reddedildi');
            $data = [ $r['id'], $r['username'], $r['banka'], $r['miktar'], $r['tarih'], $durumTxt, $r['tur'], $r['aciklama'] ];
            echo "<Row>";
            foreach ($data as $i => $val) {
                $type = is_numeric($val) && $i===3 ? 'Number' : 'String';
                echo "<Cell><Data ss:Type=\"$type\">".htmlspecialchars((string)$val)."</Data></Cell>";
            }
            echo "</Row>";
        }
        echo "</Table></Worksheet></Workbook>";
    }
    exit;
}

// Onayla butonuna tıklandığında işlemi onayla
if (isset($_POST['onayla'])) {
    try {
    
        $parayatir_id = (int)$_POST['parayatir_id'];
        // Yatırım bilgilerini al
        $stmt = $pdo->prepare("SELECT * FROM parayatir WHERE id = :id");
        $stmt->execute(['id' => $parayatir_id]);
        $yatir = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($yatir && (int)$yatir['durum'] === 0) {
            $user_id = (int)$yatir['user_id'];
            $miktar = (float)$yatir['miktar'];

            $stmt = $pdo->prepare("SELECT * FROM kullanicilar WHERE id = :id");
            $stmt->execute(['id' => $user_id]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user) {
                $new_balance = (float)$user['ana_bakiye'] + $miktar;
                $stmt = $pdo->prepare("UPDATE kullanicilar SET ana_bakiye = :ana_bakiye WHERE id = :id");
                $stmt->execute(['ana_bakiye' => $new_balance, 'id' => $user_id]);

                $stmt = $pdo->prepare("UPDATE parayatir SET durum = 1 WHERE id = :id");
                $stmt->execute(['id' => $parayatir_id]);
                audit_log(
                    'parayatir',
                    'approve',
                    'Para yatır onayı',
                    [
                        'id' => $parayatir_id,
                        'user_id' => $user_id,
                        'username' => $user['username'] ?? null,
                        'amount' => $miktar,
                    ]
                );
            }
        }
        header("Location: parayatir.php?msg=approved");
        exit;
    } catch (Throwable $e) {
        event_log('error', 'parayatir_approve', $e->getMessage(), [ 'parayatir_id' => $_POST['parayatir_id'] ?? null ]);
        header("Location: parayatir.php?error=onay-hatasi");
        exit;
    }
}

// Red butonuna tıklandığında işlem yapma
if (isset($_POST['red'])) {
    try {
    
        $parayatir_id = (int)$_POST['parayatir_id'];
        $reason = isset($_POST['reason']) ? trim($_POST['reason']) : '';
        $reasonCode = isset($_POST['reason_code']) ? trim($_POST['reason_code']) : '';
        $fullReason = $reasonCode !== '' ? ($reasonCode . ' - ' . $reason) : $reason;
        if ($reason === '') {
            header("Location: parayatir.php?error=red-nedeni-gerekli");
            exit;
        }
        $stmt = $pdo->prepare("UPDATE parayatir SET durum = 2, aciklama = CONCAT(COALESCE(aciklama,''),' | RED: ', :reason) WHERE id = :id");
        $stmt->execute(['id' => $parayatir_id, 'reason' => $fullReason]);

        audit_log(
            'parayatir',
            'reject',
            'Para yatır reddi',
            [
                'id' => $parayatir_id,
                'reason' => $reason,
                'reason_code' => $reasonCode,
            ]
        );

        header("Location: parayatir.php?msg=rejected");
        exit;
    } catch (Throwable $e) {
        event_log('error', 'parayatir_reject', $e->getMessage(), [ 'parayatir_id' => $_POST['parayatir_id'] ?? null ]);
        header("Location: parayatir.php?error=red-hatasi");
        exit;
    }
}

// Toplu işlemler (onay/red)
if (isset($_POST['bulk_action']) && isset($_POST['bulk_ids']) && is_array($_POST['bulk_ids'])) {
    // izin kontrolü: finans toplu işlem
    if (!has_permission('finance_bulk')) {
        header("Location: parayatir.php?error=yetki-yok-toplu");
        exit;
    }
    $action = $_POST['bulk_action'];
    $ids = array_map('intval', $_POST['bulk_ids']);
    if (!in_array($action, ['approve','reject'], true) || empty($ids)) {
        header("Location: parayatir.php?error=toplu-gecersiz");
        exit;
    }
    try {
    
        $approved = 0; $rejected = 0;
        if ($action === 'approve') {
            foreach ($ids as $id) {
                $st = $pdo->prepare("SELECT * FROM parayatir WHERE id = :id");
                $st->execute(['id'=>$id]);
                $yatir = $st->fetch(PDO::FETCH_ASSOC);
                if (!$yatir || (int)$yatir['durum'] !== 0) { continue; }
                $user_id = (int)$yatir['user_id'];
                $miktar = (float)$yatir['miktar'];
                $su = $pdo->prepare("UPDATE kullanicilar SET ana_bakiye = ana_bakiye + :m WHERE id = :uid");
                $su->execute(['m'=>$miktar,'uid'=>$user_id]);
                $up = $pdo->prepare("UPDATE parayatir SET durum = 1 WHERE id = :id");
                $up->execute(['id'=>$id]);
                $approved++;
            }
            audit_log('parayatir', 'bulk_approve', 'Toplu para yatır onayı', [ 'count'=>$approved, 'ids'=>$ids ]);
            header("Location: parayatir.php?msg=toplu-onay&adet={$approved}");
            exit;
        } else { // reject
            $reason = isset($_POST['bulk_reason']) ? trim($_POST['bulk_reason']) : '';
            $reasonCode = isset($_POST['bulk_reason_code']) ? trim($_POST['bulk_reason_code']) : '';
            $fullReason = $reasonCode !== '' ? ($reasonCode . ' - ' . $reason) : $reason;
            if ($reason === '') {
                header("Location: parayatir.php?error=toplu-red-nedeni-gerekli");
                exit;
            }
            $up = $pdo->prepare("UPDATE parayatir SET durum = 2, aciklama = CONCAT(COALESCE(aciklama,''),' | RED: ', :reason) WHERE id = :id");
            foreach ($ids as $id) {
                $st = $pdo->prepare("SELECT durum FROM parayatir WHERE id = :id");
                $st->execute(['id'=>$id]);
                $d = $st->fetchColumn();
                if ((int)$d !== 0) { continue; }
                $up->execute(['id'=>$id,'reason'=>$fullReason]);
                $rejected++;
            }
            audit_log('parayatir', 'bulk_reject', 'Toplu para yatır reddi', [ 'count'=>$rejected, 'ids'=>$ids, 'reason'=>$reason, 'reason_code'=>$reasonCode ]);
            header("Location: parayatir.php?msg=toplu-red&adet={$rejected}");
            exit;
        }
    } catch (Throwable $e) {
        event_log('error', 'parayatir_bulk', $e->getMessage(), [ 'action' => $_POST['bulk_action'] ?? null, 'ids' => $_POST['bulk_ids'] ?? null ]);
        header("Location: parayatir.php?error=toplu-islem-hatasi");
        exit;
    }
}

// Silme butonuna tıklandığında işlemi kaldır
if (isset($_POST['sil'])) {
    try {
    
        $parayatir_id = (int)$_POST['parayatir_id'];
        $stmt = $pdo->prepare("DELETE FROM parayatir WHERE id = :id");
        $stmt->execute(['id' => $parayatir_id]);

        audit_log('parayatir', 'delete', 'Para yatır kaydı silindi', [ 'id' => $parayatir_id ]);

        header("Location: parayatir.php?msg=silindi");
        exit;
    } catch (Throwable $e) {
        event_log('error', 'parayatir_delete', $e->getMessage(), [ 'parayatir_id' => $_POST['parayatir_id'] ?? null ]);
        header("Location: parayatir.php?error=silme-hatasi");
        exit;
    }
}
?>

<!-- HTML kısmı -->
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Para Yatırma 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">
<link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'sidebar.php'; ?>
            <div class="col-md-10 p-4">
                <h2 class="mb-4">Para Yatırma Listesi</h2>

                <!-- Hızlı Durum Sekmeleri -->
                <ul class="nav nav-pills mb-3">
                    <?php
                        // Mevcut query string'i koruyarak status'i değiştir
                        function qs($overrides) {
                            $base = $_GET;
                            foreach ($overrides as $k=>$v) { if ($v==='') { unset($base[$k]); } else { $base[$k]=$v; } }
                            return '?' . http_build_query($base);
                        }
                    ?>
                    <li class="nav-item"><a class="nav-link <?= $status==='' ? 'active' : '' ?>" href="<?= qs(['status'=>'']) ?>">Hepsi</a></li>
                    <li class="nav-item"><a class="nav-link <?= $status==='0' ? 'active' : '' ?>" href="<?= qs(['status'=>'0','page'=>1]) ?>">Beklemede</a></li>
                    <li class="nav-item"><a class="nav-link <?= $status==='1' ? 'active' : '' ?>" href="<?= qs(['status'=>'1','page'=>1]) ?>">Onaylandı</a></li>
                    <li class="nav-item"><a class="nav-link <?= $status==='2' ? 'active' : '' ?>" href="<?= qs(['status'=>'2','page'=>1]) ?>">Reddedildi</a></li>
                </ul>

                <!-- Filtre Formu -->
                <form class="row g-3 mb-3" method="get" action="">
                    <div class="col-sm-3">
                        <label class="form-label">Başlangıç Tarihi</label>
                        <input type="date" name="start" class="form-control" value="<?= htmlspecialchars($start) ?>">
                    </div>
                    <div class="col-sm-3">
                        <label class="form-label">Bitiş Tarihi</label>
                        <input type="date" name="end" class="form-control" value="<?= htmlspecialchars($end) ?>">
                    </div>
                    <div class="col-sm-2">
                        <label class="form-label">Tür</label>
                        <input type="text" name="type" class="form-control" placeholder="Örn: Havale" value="<?= htmlspecialchars($type) ?>">
                    </div>
                    <div class="col-sm-2">
                        <label class="form-label">Durum</label>
                        <select name="status" class="form-select">
                            <option value="">Hepsi</option>
                            <option value="0" <?= $status==='0' ? 'selected' : '' ?>>Beklemede</option>
                            <option value="1" <?= $status==='1' ? 'selected' : '' ?>>Onaylandı</option>
                            <option value="2" <?= $status==='2' ? 'selected' : '' ?>>Reddedildi</option>
                        </select>
                    </div>
                    <div class="col-sm-2">
                        <label class="form-label">Banka</label>
                        <input type="text" name="bank" class="form-control" value="<?= htmlspecialchars($bank) ?>">
                    </div>
                    <div class="col-sm-2">
                        <label class="form-label">Min Tutar</label>
                        <input type="number" step="0.01" name="min_amount" class="form-control" value="<?= htmlspecialchars($minAmount) ?>">
                    </div>
                    <div class="col-sm-2">
                        <label class="form-label">Max Tutar</label>
                        <input type="number" step="0.01" name="max_amount" class="form-control" value="<?= htmlspecialchars($maxAmount) ?>">
                    </div>
                    <div class="col-sm-3">
                        <label class="form-label">Kullanıcı Adı</label>
                        <input type="text" name="username" class="form-control" value="<?= htmlspecialchars($usernameQ) ?>">
                    </div>
                    <div class="col-sm-2">
                        <label class="form-label">Sayfa Boyutu</label>
                        <select name="per_page" class="form-select">
                            <?php foreach ([25,50,100,200] as $opt): ?>
                                <option value="<?= $opt ?>" <?= $perPage==$opt ? 'selected' : '' ?>><?= $opt ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-12 text-end">
                        <button type="submit" class="btn btn-primary">Filtrele</button>
                        <a href="parayatir.php" class="btn btn-secondary">Sıfırla</a>
                        <a href="<?= qs(['export'=>'csv']) ?>" class="btn btn-outline-success">CSV İndir</a>
                        <a href="<?= qs(['export'=>'xlsx']) ?>" class="btn btn-outline-success">XLSX İndir</a>
                    </div>
                </form>

                <!-- Kayıtlı Görünümler (Parayatır) -->
                <?php $savedViewsPT = load_saved_views_pt(); ?>
                <div class="card mb-3">
                    <div class="card-body">
                        <form method="post" class="row g-2 align-items-end">
                            <div class="col-sm-4">
                                <label class="form-label">Görünüm Adı</label>
                                <input type="text" name="view_name" class="form-control" placeholder="Örn: Ziraat Beklemede">
                            </div>
                            <div class="col-sm-3">
                                <button type="submit" name="save_view_pt" class="btn btn-outline-primary">Mevcut Filtreleri Kaydet</button>
                            </div>
                            <div class="col-sm-5 text-end">
                                <?php if (!empty($savedViewsPT)): ?>
                                    <div class="d-flex gap-2 justify-content-end">
                                        <select class="form-select" id="savedViewSelectPT" style="max-width:300px">
                                            <?php foreach ($savedViewsPT as $n=>$q): ?>
                                                <option value="<?= htmlspecialchars('?' . http_build_query($q)) ?>"><?= htmlspecialchars($n) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <a class="btn btn-success" id="applySavedPT">Uygula</a>
                                        <button type="submit" name="delete_view_pt" class="btn btn-danger" onclick="document.getElementById('deleteNamePT').value = document.getElementById('savedViewSelectPT').selectedOptions[0].textContent;">Sil</button>
                                        <input type="hidden" name="delete_name" id="deleteNamePT">
                                    </div>
                                <?php else: ?>
                                    <span class="text-muted">Kayıtlı görünüm yok.</span>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>
                <script>
                document.getElementById('applySavedPT')?.addEventListener('click', function(){
                    var sel = document.getElementById('savedViewSelectPT');
                    if (sel && sel.value) { window.location.href = 'parayatir.php' + sel.value; }
                });
                </script>

                <!-- Özet Kartları -->
                <div class="alert alert-info">Filtreye göre toplam adet: <strong><?= htmlspecialchars($totalRows) ?></strong>, toplam tutar: <strong><?= number_format($toplamTutar,2) ?></strong></div>

                <div class="table-responsive">
                    <form method="post">
            
                    <div class="mb-2 d-flex align-items-center gap-2">
                        <button type="submit" name="bulk_action" value="approve" class="btn btn-success">Seçilileri Onayla</button>
                        <select name="bulk_reason_code" class="form-select" style="max-width:220px">
                            <option value="">Neden Kodu (opsiyonel)</option>
                            <option>Belge eksik</option>
                            <option>Yanlış tutar</option>
                            <option>Ad-soyad uyumsuz</option>
                            <option>Şüpheli işlem</option>
                            <option>Süre aşımı</option>
                            <option>İptal edildi</option>
                        </select>
                        <input type="text" name="bulk_reason" class="form-control" placeholder="Toplu red nedeni" style="max-width:300px">
                        <button type="submit" name="bulk_action" value="reject" class="btn btn-danger">Seçilileri Reddet</button>
                    </div>
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th><input type="checkbox" onclick="document.querySelectorAll('.bulk-chk').forEach(cb=>cb.checked=this.checked)"></th>
                                <th>ID</th>
                                <th>Kullanıcı Adı</th>
                                <th>Banka</th>
                                <th>Miktar</th>
                                <th>Tarih</th>
                                <th>Durum</th>
                                <th>Tür</th>
                                <th>Açıklama</th>
                                <th>İşlem</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($parayatir as $yatir): ?>
                                <tr>
                                    <td><input type="checkbox" class="bulk-chk" name="bulk_ids[]" value="<?= htmlspecialchars($yatir['id']) ?>" <?= ($yatir['durum']==0?'':'disabled') ?>></td>
                                    <td><?= htmlspecialchars($yatir['id']) ?></td>
                                    <td><a href="users.php?search=<?= urlencode($yatir['username'] ?? '') ?>" target="_blank"><?= htmlspecialchars($yatir['username'] ?? 'Belirtilmemiş') ?></a></td>
                                    <td><?= htmlspecialchars($yatir['banka']) ?></td>
                                    <td><?= htmlspecialchars($yatir['miktar']) ?></td>
                                    <td><?= htmlspecialchars($yatir['tarih']) ?></td>
                                    <td><?= $yatir['durum'] == 0 ? 'Bekliyor' : ($yatir['durum'] == 1 ? 'Onaylı' : 'Reddedildi') ?></td>
                                    <td><?= htmlspecialchars($yatir['tur'] ?? '') ?></td>
                                    <td><?= htmlspecialchars($yatir['aciklama'] ?? '') ?></td>
                                    <td>
                                        <?php if ($yatir['durum'] == 0): ?>
                                            <form method="post" style="display:inline;">
                                                <input type="hidden" name="parayatir_id" value="<?= $yatir['id'] ?>">
            
                                                <button type="submit" name="onayla" class="btn btn-success">Onayla</button>
                                            </form>
                                            <form method="post" style="display:inline;">
                                                <input type="hidden" name="parayatir_id" value="<?= $yatir['id'] ?>">
            
                                                <select name="reason_code" class="form-select d-inline-block" style="width:180px">
                                                    <option value="">Neden Kodu (opsiyonel)</option>
                                                    <option>Belge eksik</option>
                                                    <option>Yanlış tutar</option>
                                                    <option>Ad-soyad uyumsuz</option>
                                                    <option>Şüpheli işlem</option>
                                                    <option>Süre aşımı</option>
                                                    <option>İptal edildi</option>
                                                </select>
                                                <input type="text" name="reason" class="form-control d-inline-block" style="width:180px" placeholder="Red nedeni" required>
                                                <button type="submit" name="red" class="btn btn-danger">Red</button>
                                            </form>
                                        <?php endif; ?>
                                        
                                        <!-- Sil Butonu -->
                                        <form method="post" style="display:inline;">
                                            <input type="hidden" name="parayatir_id" value="<?= $yatir['id'] ?>">
            
                                            <button type="submit" name="sil" class="btn btn-dark" onclick="return confirm('Bu kaydı silmek istediğinize emin misiniz?');">Sil</button>
                                        </form>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                    </form>
                    <!-- Sayfalama -->
                    <nav aria-label="Sayfalama" class="mt-3">
                        <ul class="pagination">
                            <li class="page-item <?= $page<=1 ? 'disabled' : '' ?>">
                                <a class="page-link" href="<?= qs(['page'=>max(1,$page-1)]) ?>">Önceki</a>
                            </li>
                            <?php for ($i=max(1,$page-2); $i<=min($totalPages,$page+2); $i++): ?>
                                <li class="page-item <?= $i==$page ? 'active' : '' ?>"><a class="page-link" href="<?= qs(['page'=>$i]) ?>"><?= $i ?></a></li>
                            <?php endfor; ?>
                            <li class="page-item <?= $page>=$totalPages ? 'disabled' : '' ?>">
                                <a class="page-link" href="<?= qs(['page'=>min($totalPages,$page+1)]) ?>">Sonraki</a>
                            </li>
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
