<?php
// Hata gösterme ayarları
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require 'config.php'; // Veritabanı bağlantısı
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/logger.php';
require_permission('withdraw_review');

// Kayıtlı Görünümler Yardımcıları (Paracek)
function load_saved_views_pc() {
    $file = __DIR__ . DIRECTORY_SEPARATOR . 'saved_views_paracek.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_pc($views) {
    $file = __DIR__ . DIRECTORY_SEPARATOR . 'saved_views_paracek.json';
    file_put_contents($file, json_encode($views, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_view_pc'])) {
    
    $name = trim($_POST['view_name'] ?? '');
    if ($name !== '') {
        $views = load_saved_views_pc();
        $views[$name] = $_GET; // mevcut filtreleri kaydet
        save_saved_views_pc($views);
        echo "<script>location.href='paracek.php?msg=view-saved';</script>";
        exit;
    }
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_view_pc'])) {
    
    $name = trim($_POST['delete_name'] ?? '');
    $views = load_saved_views_pc();
    if (isset($views[$name])) { unset($views[$name]); save_saved_views_pc($views); }
    echo "<script>location.href='paracek.php?msg=view-deleted';</script>";
    exit;
}

// Çekim talebini güncelleme işlemi
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    $id = intval($_POST['id']);
    $action = $_POST['action'];

    if ($action === 'onayla' || $action === 'red') {
        $newStatus = ($action === 'onayla') ? 1 : 2; // 1: Onay, 2: Red

        // Çekim talebi bilgilerini al
        $query = $pdo->prepare("SELECT miktar, user_id FROM paracek WHERE id = ?");
        $query->execute([$id]);
        $cekim = $query->fetch();

        if ($cekim && $action === 'onayla') {
            // Kullanıcının ana bakiyesini düş
            $miktar = $cekim['miktar'];
            $userId = $cekim['user_id'];

            // Çevrim kontrolü
            $wrTotal = 0.0; $betTotal = 0.0;
                $stmtPB = $pdo->prepare("SELECT id, amount, wagering_requirement, no_wagering, COALESCE(used_at, created_at) AS start_at FROM personalized_bonuses WHERE user_id = ? AND status = 'active'");
            $stmtPB->execute([$userId]);
                foreach ($stmtPB->fetchAll(PDO::FETCH_ASSOC) as $pb) {
                    if (intval($pb['no_wagering'])) { continue; }
                    $wrTotal += (float)$pb['amount'] * (float)$pb['wagering_requirement'];
                if ($pb['start_at']) {
                    $stmtBet = $pdo->prepare("SELECT COALESCE(SUM(bet_amount),0) FROM live_bet WHERE users_id = ? AND created_at >= ?");
                    $stmtBet->execute([$userId, $pb['start_at']]);
                    $betTotal += (float)$stmtBet->fetchColumn();
                }
            }
                $stmtBR = $pdo->prepare("SELECT miktar, wagering_requirement, no_wagering, tarih FROM bonus_talepleri WHERE uye_id = ? AND durum = 1");
            $stmtBR->execute([$userId]);
                foreach ($stmtBR->fetchAll(PDO::FETCH_ASSOC) as $br) {
                    if (intval($br['no_wagering'])) { continue; }
                    $wrTotal += (float)$br['miktar'] * (float)$br['wagering_requirement'];
                if ($br['tarih']) {
                    $stmtBet2 = $pdo->prepare("SELECT COALESCE(SUM(bet_amount),0) FROM live_bet WHERE users_id = ? AND created_at >= ?");
                    $stmtBet2->execute([$userId, $br['tarih']]);
                    $betTotal += (float)$stmtBet2->fetchColumn();
                }
            }
            $remaining = max(0.0, $wrTotal - $betTotal);
            if ($remaining > 0.01) {
                echo "<script>Swal.fire('Uyarı', 'Çevrim şartı tamamlanmadı. Gerekli: ₺".number_format($wrTotal,2)." • Yapılan: ₺".number_format($betTotal,2)." • Kalan: ₺".number_format($remaining,2)."', 'warning');</script>";
                exit;
            }

            $updateBalance = $pdo->prepare("UPDATE kullanicilar SET ana_bakiye = ana_bakiye - ? WHERE id = ?");
            $updateBalance->execute([$miktar, $userId]);
        }

        if ($action === 'red') {
            $reason = isset($_POST['reason']) ? trim($_POST['reason']) : '';
            $reasonCode = isset($_POST['reason_code']) ? trim($_POST['reason_code']) : '';
            $fullReason = $reasonCode !== '' ? ($reasonCode . ' - ' . $reason) : $reason;
            if ($reason === '') {
                echo "<script>Swal.fire('Hata', 'Red nedeni zorunludur.', 'error');</script>";
                exit;
            }
            $updateStatus = $pdo->prepare("UPDATE paracek SET durum = 2, aciklama = CONCAT(COALESCE(aciklama,''),' | RED: ', :reason) WHERE id = :id");
            $updateStatus->execute(['reason'=>$fullReason,'id'=>$id]);
            audit_log('withdraw_reject','paracek',[ 'id'=>$id, 'full_reason'=>$fullReason ]);
        } else {
            $updateStatus = $pdo->prepare("UPDATE paracek SET durum = 1 WHERE id = ?");
            $updateStatus->execute([$id]);
            audit_log('withdraw_approve','paracek',[ 'id'=>$id ]);
        }

        echo "<script>Swal.fire('Başarılı!', 'Çekim talebi güncellendi.', 'success');</script>";
    }
}

// Toplu işlemler (onay/red)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action']) && isset($_POST['bulk_ids']) && is_array($_POST['bulk_ids'])) {
    // izin kontrolü: finans toplu işlem
    if (!has_permission('finance_bulk')) {
        echo "<script>Swal.fire('Erişim engellendi', 'Toplu işlem için yetkiniz yok.', 'error');</script>";
        exit;
    }
    
    $action = $_POST['bulk_action'];
    $ids = array_map('intval', $_POST['bulk_ids']);
    if (!in_array($action, ['approve','reject'], true) || empty($ids)) {
        echo "<script>Swal.fire('Hata', 'Geçersiz toplu işlem.', 'error');</script>";
    } else {
        try {
            $approved = 0; $rejected = 0;
            if ($action === 'approve') {
                $us = $pdo->prepare("UPDATE paracek SET durum = 1 WHERE id = :id AND durum = 0");
                $qInfo = $pdo->prepare("SELECT user_id FROM paracek WHERE id = :id");
                $approvedBlocked = 0;
                foreach ($ids as $bid) {
                    $qInfo->execute(['id'=>$bid]);
                    $userId = (int)$qInfo->fetchColumn();
                    if ($userId) {
                        $wrTotal = 0.0; $betTotal = 0.0;
                        $stmtPB = $pdo->prepare("SELECT id, amount, wagering_requirement, no_wagering, COALESCE(used_at, created_at) AS start_at FROM personalized_bonuses WHERE user_id = ? AND status = 'active'");
                        $stmtPB->execute([$userId]);
                        foreach ($stmtPB->fetchAll(PDO::FETCH_ASSOC) as $pb) {
                            if (intval($pb['no_wagering'])) { continue; }
                            $wrTotal += (float)$pb['amount'] * (float)$pb['wagering_requirement'];
                            if ($pb['start_at']) {
                                $stmtBet = $pdo->prepare("SELECT COALESCE(SUM(bet_amount),0) FROM live_bet WHERE users_id = ? AND created_at >= ?");
                                $stmtBet->execute([$userId, $pb['start_at']]);
                                $betTotal += (float)$stmtBet->fetchColumn();
                            }
                        }
                        $stmtBR = $pdo->prepare("SELECT miktar, wagering_requirement, no_wagering, tarih FROM bonus_talepleri WHERE uye_id = ? AND durum = 1");
                        $stmtBR->execute([$userId]);
                        foreach ($stmtBR->fetchAll(PDO::FETCH_ASSOC) as $br) {
                            if (intval($br['no_wagering'])) { continue; }
                            $wrTotal += (float)$br['miktar'] * (float)$br['wagering_requirement'];
                            if ($br['tarih']) {
                                $stmtBet2 = $pdo->prepare("SELECT COALESCE(SUM(bet_amount),0) FROM live_bet WHERE users_id = ? AND created_at >= ?");
                                $stmtBet2->execute([$userId, $br['tarih']]);
                                $betTotal += (float)$stmtBet2->fetchColumn();
                            }
                        }
                        $remaining = max(0.0, $wrTotal - $betTotal);
                        if ($remaining > 0.01) { $approvedBlocked++; continue; }
                    }
                    $us->execute(['id'=>$bid]);
                    if ($us->rowCount() > 0) { $approved++; }
                }
                if ($approved>0) { audit_log('withdraw_bulk_approve','paracek',[ 'ids'=>$ids, 'count'=>$approved ]); }
                if ($approvedBlocked>0) {
                    echo "<script>Swal.fire('Uyarı', 'Çevrim şartı nedeniyle onaylanmayan: {$approvedBlocked} kayıt.', 'warning');</script>";
                }
                echo "<script>Swal.fire('Başarılı', 'Toplu onay: {$approved} kayıt.', 'success');</script>";
            } 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 === '') {
                    echo "<script>Swal.fire('Hata', 'Toplu red için neden zorunlu.', 'error');</script>";
                } else {
                    $us = $pdo->prepare("UPDATE paracek SET durum = 2, aciklama = CONCAT(COALESCE(aciklama,''),' | RED: ', :reason) WHERE id = :id");
                    foreach ($ids as $bid) {
                        $q = $pdo->prepare("SELECT durum FROM paracek WHERE id = :id");
                        $q->execute(['id'=>$bid]);
                        $d = $q->fetchColumn();
                        if ((int)$d !== 0) { continue; }
                        $us->execute(['id'=>$bid,'reason'=>$fullReason]);
                        $rejected++;
                    }
                    if ($rejected>0) { audit_log('withdraw_bulk_reject','paracek',[ 'ids'=>$ids, 'count'=>$rejected, 'full_reason'=>$fullReason ]); }
                    echo "<script>Swal.fire('Başarılı', 'Toplu red: {$rejected} kayıt.', 'success');</script>";
                }
            }
        } catch (Throwable $e) {
            echo "<script>Swal.fire('Hata', 'Toplu işlem hatası.', 'error');</script>";
        }
    }
}

// Filtreler (GET)
$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;

// Çekim taleplerini listele (filtreli ve yeni→eski sıralı)
$where = [];
$params = [];
if ($start !== '' && $end !== '') {
    $where[] = 'tarih BETWEEN :start AND :end';
    $params[':start'] = $start . ' 00:00:00';
    $params[':end'] = $end . ' 23:59:59';
}
if ($type !== '') {
    $where[] = 'turi = :turi';
    $params[':turi'] = $type;
}
if ($status !== '' && is_numeric($status)) {
    $where[] = 'durum = :durum';
    $params[':durum'] = (int)$status;
}
if ($bank !== '') {
    $where[] = 'paracek.banka = :banka';
    $params[':banka'] = $bank;
}
if ($minAmount !== '' && is_numeric($minAmount)) {
    $where[] = 'paracek.miktar >= :min_amount';
    $params[':min_amount'] = (float)$minAmount;
}
if ($maxAmount !== '' && is_numeric($maxAmount)) {
    $where[] = 'paracek.miktar <= :max_amount';
    $params[':max_amount'] = (float)$maxAmount;
}
if ($usernameQ !== '') {
    $where[] = 'kullanicilar.username LIKE :username';
    $params[':username'] = '%' . $usernameQ . '%';
}

$sql = "SELECT paracek.id, kullanicilar.username, paracek.uye, paracek.banka, paracek.miktar, paracek.tarih, paracek.durum, paracek.turi, paracek.aciklama, paracek.sube, paracek.hesap, paracek.iban FROM paracek LEFT JOIN kullanicilar ON (kullanicilar.id = paracek.user_id OR kullanicilar.username = paracek.uye)";
if (!empty($where)) {
    $sql .= ' WHERE ' . implode(' AND ', $where);
}
$sql .= ' ORDER BY paracek.tarih DESC, paracek.id DESC LIMIT :limit OFFSET :offset';

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

// Toplam sayfa ve tutar
$countSql = "SELECT COUNT(*) FROM paracek LEFT JOIN kullanicilar ON (kullanicilar.id = paracek.user_id OR kullanicilar.username = paracek.uye)";
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(paracek.miktar),0) FROM paracek LEFT JOIN kullanicilar ON (kullanicilar.id = paracek.user_id OR kullanicilar.username = paracek.uye)";
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 = "SELECT paracek.id, kullanicilar.username, paracek.banka, paracek.miktar, paracek.tarih, paracek.durum, paracek.turi, paracek.aciklama FROM paracek LEFT JOIN kullanicilar ON paracek.user_id = kullanicilar.id";
    if (!empty($where)) { $expSql .= ' WHERE ' . implode(' AND ', $where); }
    $expSql .= ' ORDER BY paracek.tarih DESC, paracek.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="paracek_' . ($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['turi'],
                $r['aciklama'],
            ]);
        }
        fclose($out);
    } else { // xlsx (Excel 2003 XML)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment; filename="paracek_' . ($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=\"Paracek\"><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['turi'], $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;
}

?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Mobil uyumlu için viewport ekledik -->
    <title>Para Çekim Talepleri</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">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>

</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 Çekim Talepleri</h2>
                <!-- Hızlı Durum Sekmeleri -->
                <ul class="nav nav-pills mb-3">
                    <?php
                        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="paracek.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 (Paracek) -->
                <?php $savedViewsPC = load_saved_views_pc(); ?>
                <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_pc" class="btn btn-outline-primary">Mevcut Filtreleri Kaydet</button>
                            </div>
                            <div class="col-sm-5 text-end">
                                <?php if (!empty($savedViewsPC)): ?>
                                    <div class="d-flex gap-2 justify-content-end">
                                        <select class="form-select" id="savedViewSelectPC" style="max-width:300px">
                                            <?php foreach ($savedViewsPC as $n=>$q): ?>
                                                <option value="<?= htmlspecialchars('?' . http_build_query($q)) ?>"><?= htmlspecialchars($n) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                        <a class="btn btn-success" id="applySavedPC">Uygula</a>
                                        <button type="submit" name="delete_view_pc" class="btn btn-danger" onclick="document.getElementById('deleteNamePC').value = document.getElementById('savedViewSelectPC').selectedOptions[0].textContent;">Sil</button>
                                        <input type="hidden" name="delete_name" id="deleteNamePC">
                                    </div>
                                <?php else: ?>
                                    <span class="text-muted">Kayıtlı görünüm yok.</span>
                                <?php endif; ?>
                            </div>
                        </form>
                    </div>
                </div>
                <script>
                document.getElementById('applySavedPC')?.addEventListener('click', function(){
                    var sel = document.getElementById('savedViewSelectPC');
                    if (sel && sel.value) { window.location.href = 'paracek.php' + sel.value; }
                });
                </script>

                <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-bordered">
<thead>
    <tr>
        <th><input type="checkbox" onclick="document.querySelectorAll('.bulk-chk').forEach(cb=>cb.checked=this.checked)"></th>
        <th>ID</th>
        <th>Üye</th>
        <th>Kullanıcı Adı</th>
        <th>Banka</th>
        <th>Miktar</th>
        <th>Tarih</th>
        <th>Durum</th>
        <th>İşlem Türü</th>
        <th>Açıklama</th>
        <th>Şube</th>
        <th>Hesap</th>
        <th>IBAN</th>
        <th>İşlemler</th>
    </tr>
</thead>
<tbody>
    <?php foreach ($cekimListesi as $cekim): ?>
    <tr>
        <td><input type="checkbox" class="bulk-chk" name="bulk_ids[]" value="<?= htmlspecialchars($cekim['id']) ?>" <?= ((int)$cekim['durum']===0 ? '' : 'disabled') ?>></td>
        <td><?= htmlspecialchars($cekim['id']) ?></td>
        <td><?= htmlspecialchars($cekim['uye']) ?></td>
        <td><a href="users.php?search=<?= urlencode($cekim['username'] ?? '') ?>" target="_blank"><?= htmlspecialchars($cekim['username'] ?? 'Belirtilmemiş') ?></a></td>
        <td><?= htmlspecialchars($cekim['banka']) ?></td>
        <td><?= htmlspecialchars($cekim['miktar']) ?></td>
        <td><?= htmlspecialchars($cekim['tarih']) ?></td>
        <td>
            <?php
            switch ($cekim['durum']) {
                case 0: echo 'Beklemede'; break;
                case 1: echo 'Onaylandı'; break;
                case 2: echo 'Reddedildi'; break;
            }
            ?>
        </td>
        <td><?= htmlspecialchars($cekim['turi'] ?? '') ?></td>
        <td><?= htmlspecialchars($cekim['aciklama'] ?? '') ?></td>
        <td><?= htmlspecialchars($cekim['sube'] ?? '') ?></td>
        <td><?= htmlspecialchars($cekim['hesap'] ?? '') ?></td>
        <td><?= htmlspecialchars($cekim['iban']) ?></td>
        <td>
            <?php if ($cekim['durum'] == 0): ?>
            <form method="POST" style="display: inline;">
                <input type="hidden" name="id" value="<?= htmlspecialchars($cekim['id']) ?>">
            
                <button type="submit" name="action" value="onayla" class="btn btn-success btn-sm mb-1 mb-sm-0">Onayla</button>
                <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">
                <button type="submit" name="action" value="red" class="btn btn-danger btn-sm">Red</button>
            </form>
            <?php else: ?>
            <span class="text-muted">Tamamlandı</span>
            <?php endif; ?>
        </td>
    </tr>
    <?php endforeach; ?>
</tbody>

                    </table>
                    </form>
                </div>
                <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>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
