<?php
session_start();
require_once __DIR__ . '/auth.php';
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$uploadDir = realpath(__DIR__ . '/../profile/uploads') ?: (__DIR__ . '/../profile/uploads');
$files = [];
if (is_dir($uploadDir)) {
    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($uploadDir, FilesystemIterator::SKIP_DOTS));
    foreach ($rii as $file) {
        if ($file->isFile()) {
            $rel = str_replace($uploadDir . DIRECTORY_SEPARATOR, '', $file->getPathname());
            $files[] = [
                'name' => $file->getFilename(),
                'path' => $rel,
                'size' => $file->getSize(),
                'mtime' => date('Y-m-d H:i', $file->getMTime()),
                'ext' => strtolower(pathinfo($file->getFilename(), PATHINFO_EXTENSION)),
            ];
        }
    }
}
usort($files, function($a, $b) { return strcmp($b['mtime'], $a['mtime']); });
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KYC İnceleme</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <style>
        .preview-img { max-width: 120px; max-height: 120px; object-fit: cover; border-radius: 4px; }
        .toolbar { display:flex; gap:8px; align-items:center; margin-bottom: 12px; }
        .toolbar input[type="text"], .toolbar select { max-width: 240px; }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include __DIR__ . '/sidebar.php'; ?>

            <div class="col-md-10 p-4">
                <?php include __DIR__ . '/topbar.php'; ?>
                <h1>KYC İnceleme</h1>
                <p class="text-muted">Yüklenen kimlik doğrulama dosyalarını görüntüleyin ve indirin.</p>

                <div class="toolbar">
                    <input type="text" id="quickSearch" class="form-control" placeholder="Dosya adına göre ara...">
                    <select id="extFilter" class="form-select">
                        <option value="">Tüm uzantılar</option>
                        <option value="jpg">jpg</option>
                        <option value="jpeg">jpeg</option>
                        <option value="png">png</option>
                        <option value="pdf">pdf</option>
                        <option value="doc">doc</option>
                        <option value="docx">docx</option>
                    </select>
                    <button id="exportCsv" class="btn btn-secondary">CSV Dışa Aktar</button>
                </div>

                <div class="table-responsive">
                    <table class="table table-sm table-striped" id="kycTable">
                        <thead>
                            <tr>
                                <th>Önizleme</th>
                                <th>Dosya</th>
                                <th>Uzantı</th>
                                <th>Boyut</th>
                                <th>Yüklenme</th>
                                <th>İşlem</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($files as $f): ?>
                            <tr data-name="<?= htmlspecialchars(strtolower($f['name'])) ?>" data-ext="<?= htmlspecialchars($f['ext']) ?>">
                                <td>
                                    <?php if (in_array($f['ext'], ['jpg','jpeg','png'])): ?>
                                        <img src="../profile/uploads/<?= htmlspecialchars($f['path']) ?>" class="preview-img" alt="preview">
                                    <?php else: ?>
                                        <span class="text-muted">Önizleme yok</span>
                                    <?php endif; ?>
                                </td>
                                <td><?= htmlspecialchars($f['name']) ?></td>
                                <td><?= htmlspecialchars($f['ext']) ?></td>
                                <td><?= number_format($f['size']/1024, 2) ?> KB</td>
                                <td><?= htmlspecialchars($f['mtime']) ?></td>
                                <td>
                                    <a class="btn btn-primary btn-sm" href="../profile/uploads/<?= htmlspecialchars($f['path']) ?>" target="_blank">Görüntüle</a>
                                    <a class="btn btn-secondary btn-sm" href="../profile/uploads/<?= htmlspecialchars($f['path']) ?>" download>İndir</a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        const $search = $('#quickSearch');
        const $ext = $('#extFilter');
        const $rows = $('#kycTable tbody tr');
        function applyFilters(){
            const q = $search.val().toLowerCase();
            const e = $ext.val();
            $rows.each(function(){
                const name = $(this).data('name');
                const ext = $(this).data('ext');
                const matchName = !q || name.indexOf(q) !== -1;
                const matchExt = !e || ext === e;
                $(this).toggle(matchName && matchExt);
            });
        }
        $search.on('input', applyFilters);
        $ext.on('change', applyFilters);

        // CSV Export
        $('#exportCsv').on('click', function(){
            const headers = [];
            $('#kycTable thead th').each(function(){ headers.push($(this).text().trim()); });
            const rows = [];
            $('#kycTable tbody tr:visible').each(function(){
                const cols = [];
                $(this).find('td').each(function(i){
                    let text = $(this).text().trim();
                    // Önizleme ve işlem sütunları için link href’lerini dahil et
                    if (i === 0) {
                        const img = $(this).find('img').attr('src');
                        text = img ? img : 'Yok';
                    }
                    if (i === 5) {
                        const links = $(this).find('a').map(function(){ return $(this).attr('href'); }).get().join(' | ');
                        text = links;
                    }
                    cols.push('"' + text.replace(/"/g,'""') + '"');
                });
                rows.push(cols.join(','));
            });
            const csv = headers.join(',') + '\n' + rows.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 = 'kyc_dosyalar.csv';
            a.click();
            URL.revokeObjectURL(url);
        });
    </script>
</body>
</html>
<script src="admin.js"></script>