<?php
require_once '../config/database.php';
session_start();
if (!isset($_SESSION['yonetici'])) header('Location: login.php');

$site_id = (int)$_SESSION['site_id'];
$tenant_id = $site_id;   // tenant_id hatası için eklendi

$basari = $hata = '';

// ====================== TOPLU IMPORT (CSV) ======================
if (isset($_POST['import'])) {
    if (!empty($_FILES['excel_file']['name']) && strtolower(pathinfo($_FILES['excel_file']['name'], PATHINFO_EXTENSION)) === 'csv') {
        $file = $_FILES['excel_file']['tmp_name'];
        $imported = 0;
        $errors = [];
        if (($handle = fopen($file, "r")) !== FALSE) {
            // BOM kontrolü
            $bom = fread($handle, 3);
            if ($bom !== "\xEF\xBB\xBF") {
                rewind($handle);
            }
            // Başlık satırını atla
            fgetcsv($handle, 1000, ",");
            $row_number = 2;

            while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
                if (count($row) < 9) {
                    $row_number++;
                    continue;
                }

                $row = array_map(function($value) {
                    return trim(mb_convert_encoding($value, 'UTF-8', 'UTF-8,Windows-1254,ISO-8859-9'));
                }, $row);

                list($blok_adi, $daire_no, $ad_soyad, $telefon, $email, $sifre, $sahip_kiraci, $aktif, $plaka_no) = $row;

                if (empty($ad_soyad) || empty($daire_no) || empty($sifre)) {
                    $errors[] = "Satır $row_number: Zorunlu alanlar eksik (Ad Soyad, Daire No, Şifre).";
                    $row_number++;
                    continue;
                }

                $telefon = preg_replace('/\D/', '', $telefon ?? '');
                if (strlen($telefon) < 10 || strlen($telefon) > 11) {
                    $errors[] = "Satır $row_number: Telefon geçersiz (10-11 hane olmalı).";
                    $row_number++;
                    continue;
                }

                $sahip_kiraci = strtolower($sahip_kiraci) === 'kiraci' ? 'kiraci' : 'sahip';
                $aktif = in_array((int)$aktif, [0,1]) ? (int)$aktif : 1;

                try {
                    $stmt = $pdo->prepare("
                        INSERT INTO uyeler 
                        (tenant_id, site_id, blok_adi, daire_no, ad_soyad, telefon, email, sifre, sahip_kiraci, aktif, plaka_no)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([
                        $tenant_id,
                        $site_id,
                        $blok_adi ?? '',
                        $daire_no,
                        $ad_soyad,
                        $telefon,
                        $email ?? '',
                        password_hash($sifre, PASSWORD_DEFAULT),
                        $sahip_kiraci,
                        $aktif,
                        $plaka_no ?? ''
                    ]);
                    $imported++;
                } catch (Exception $e) {
                    $errors[] = "Satır $row_number: " . ($e->getCode() == 23000 ? "Bu daire zaten kayıtlı." : $e->getMessage());
                }
                $row_number++;
            }
            fclose($handle);
        }
        $basari = "$imported üye başarıyla aktarıldı!";
        if (!empty($errors)) {
            $hata = implode('<br>', $errors);
        }
    } else {
        $hata = "Lütfen geçerli bir .csv dosyası yükleyin.";
    }
}

// ====================== EKLE ======================
if (isset($_POST['ekle'])) {
    $telefon = preg_replace('/\D/', '', $_POST['telefon'] ?? '');
    if (strlen($telefon) < 10 || strlen($telefon) > 11) {
        $hata = "Telefon numarası geçersiz (10-11 haneli olmalı).";
    } else {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO uyeler 
                (tenant_id, site_id, blok_adi, daire_no, ad_soyad, telefon, email, sifre, sahip_kiraci, aktif, plaka_no)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $tenant_id,
                $site_id,
                $_POST['blok_adi'] ?? '',
                $_POST['daire_no'],
                $_POST['ad_soyad'],
                $telefon,
                $_POST['email'] ?? '',
                password_hash($_POST['sifre'], PASSWORD_DEFAULT),
                $_POST['sahip_kiraci'] ?? 'sahip',
                $_POST['aktif'] ?? 1,
                $_POST['plaka_no'] ?? ''
            ]);
            $basari = "Üye başarıyla eklendi!";
        } catch (Exception $e) {
            $hata = "Ekleme hatası: " . $e->getMessage();
        }
    }
}

// ====================== GÜNCELLE ======================
if (isset($_POST['guncelle'])) {
    $telefon = preg_replace('/\D/', '', $_POST['telefon'] ?? '');
    if (strlen($telefon) < 10 || strlen($telefon) > 11) {
        $hata = "Telefon numarası geçersiz.";
    } else {
        $sifre = !empty($_POST['sifre']) ? password_hash($_POST['sifre'], PASSWORD_DEFAULT) : $_POST['eski_sifre'];
        try {
            $stmt = $pdo->prepare("
                UPDATE uyeler SET
                    blok_adi = ?,
                    daire_no = ?,
                    ad_soyad = ?,
                    telefon = ?,
                    email = ?,
                    sifre = ?,
                    sahip_kiraci = ?,
                    aktif = ?,
                    plaka_no = ?
                WHERE id = ? AND site_id = ?
            ");
            $stmt->execute([
                $_POST['blok_adi'] ?? '',
                $_POST['daire_no'],
                $_POST['ad_soyad'],
                $telefon,
                $_POST['email'] ?? '',
                $sifre,
                $_POST['sahip_kiraci'],
                $_POST['aktif'],
                $_POST['plaka_no'] ?? '',
                $_POST['id'],
                $site_id
            ]);
            $basari = "Üye başarıyla güncellendi!";
        } catch (Exception $e) {
            $hata = "Güncelleme hatası: " . $e->getMessage();
        }
    }
}

// ====================== SİL ======================
if (isset($_POST['sil'])) {
    $stmt = $pdo->prepare("DELETE FROM uyeler WHERE id = ? AND site_id = ?");
    $stmt->execute([$_POST['id'], $site_id]);
    $basari = "Üye başarıyla silindi!";
}

// ====================== FİLTRELEME ======================
$where = "site_id = ?";
$params = [$site_id];

if (!empty($_GET['blok'])) {
    $where .= " AND blok_adi = ?";
    $params[] = $_GET['blok'];
}
if (!empty($_GET['daire'])) {
    $where .= " AND daire_no = ?";
    $params[] = $_GET['daire'];
}
if (!empty($_GET['ad'])) {
    $where .= " AND ad_soyad LIKE ?";
    $params[] = '%' . $_GET['ad'] . '%';
}
if (!empty($_GET['telefon'])) {
    $where .= " AND telefon LIKE ?";
    $params[] = '%' . $_GET['telefon'] . '%';
}
if (isset($_GET['aktif']) && $_GET['aktif'] !== '') {
    $where .= " AND aktif = ?";
    $params[] = (int)$_GET['aktif'];
}

// ====================== SIRALAMA ======================
$stmt = $pdo->prepare("
    SELECT * FROM uyeler 
    WHERE $where 
    ORDER BY blok_adi ASC, 
             CAST(daire_no AS UNSIGNED) ASC, 
             daire_no ASC, 
             ad_soyad ASC
");
$stmt->execute($params);
$uyeler = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php include '../inc/header.php'; ?>
<?php include '../inc/sidebar.php'; ?>
<?php include '../inc/navbar.php'; ?>

<div class="content-wrapper">
    <section class="content">
        <div class="container-fluid">
            <?php if ($basari): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <button type="button" class="close" data-dismiss="alert">×</button>
                    <?= htmlspecialchars($basari) ?>
                </div>
            <?php endif; ?>
            <?php if ($hata): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <button type="button" class="close" data-dismiss="alert">×</button>
                    <?= htmlspecialchars($hata) ?>
                </div>
            <?php endif; ?>

            <!-- Toplu Import Card -->
            <div class="card mb-4">
                <div class="card-header bg-gradient-info text-white">
                    <h3 class="card-title">Toplu Üye Aktarımı (CSV)</h3>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <p>Şablonu indirin, doldurun ve yükleyin.</p>
                            <a href="uye_sablon.php" class="btn btn-warning mb-3">Şablonu İndir (.csv)</a>
                        </div>
                        <div class="col-md-6">
                            <form method="post" enctype="multipart/form-data">
                                <div class="form-group">
                                    <label>CSV Dosyası Yükle</label>
                                    <input type="file" name="excel_file" accept=".csv" class="form-control" required>
                                </div>
                                <button name="import" class="btn btn-success">Aktar</button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Üye Yönetimi Card -->
            <div class="card">
                <div class="card-header bg-gradient-primary text-white">
                    <h3 class="card-title">Üye Yönetimi</h3>
                    <div class="card-tools">
                        <div id="export_buttons" class="btn-group mr-2"></div>
                        <button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#ekleModal">
                            <i class="fas fa-user-plus"></i> Yeni Üye Ekle
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <!-- Filtre Formu -->
                    <form method="get" class="mb-3">
                        <div class="row align-items-end">
                            <div class="col-md-2"><input name="blok" class="form-control" placeholder="Blok" value="<?= htmlspecialchars($_GET['blok'] ?? '') ?>"></div>
                            <div class="col-md-2"><input name="daire" class="form-control" placeholder="Daire No" value="<?= htmlspecialchars($_GET['daire'] ?? '') ?>"></div>
                            <div class="col-md-3"><input name="ad" class="form-control" placeholder="Ad Soyad" value="<?= htmlspecialchars($_GET['ad'] ?? '') ?>"></div>
                            <div class="col-md-3"><input name="telefon" class="form-control" placeholder="Telefon" value="<?= htmlspecialchars($_GET['telefon'] ?? '') ?>"></div>
                            <div class="col-md-1">
                                <select name="aktif" class="form-control">
                                    <option value="">Tümü</option>
                                    <option value="1" <?= ($_GET['aktif'] ?? '') === '1' ? 'selected' : '' ?>>Aktif</option>
                                    <option value="0" <?= ($_GET['aktif'] ?? '') === '0' ? 'selected' : '' ?>>Pasif</option>
                                </select>
                            </div>
                            <div class="col-md-1">
                                <button type="submit" class="btn btn-primary w-100">Filtrele</button>
                            </div>
                        </div>
                    </form>

                    <!-- Tablo -->
                    <div class="table-responsive p-0">
                        <table id="uyelerTable" class="table table-hover text-nowrap">
                            <thead>
                                <tr>
                                    <th>Blok</th>
                                    <th>Daire No</th>
                                    <th>Ad Soyad</th>
                                    <th>Telefon</th>
                                    <th>E-posta</th>
                                    <th>Plaka</th>
                                    <th>Sahip/Kiracı</th>
                                    <th>Durum</th>
                                    <th>İşlemler</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($uyeler)): ?>
                                    <tr><td colspan="9" class="text-center">Hiç üye kaydı bulunmamaktadır.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($uyeler as $u): ?>
                                    <tr>
                                        <td><?= htmlspecialchars($u['blok_adi'] ?: '-') ?></td>
                                        <td><?= htmlspecialchars($u['daire_no']) ?></td>
                                        <td><?= htmlspecialchars($u['ad_soyad']) ?></td>
                                        <td><?= htmlspecialchars($u['telefon']) ?></td>
                                        <td><?= htmlspecialchars($u['email']) ?></td>
                                        <td><?= htmlspecialchars($u['plaka_no'] ?: '-') ?></td>
                                        <td><?= $u['sahip_kiraci'] === 'kiraci' ? 'Kiracı' : 'Ev Sahibi' ?></td>
                                        <td><?= $u['aktif'] ? '<span class="badge badge-success">Aktif</span>' : '<span class="badge badge-danger">Pasif</span>' ?></td>
                                        <td>
                                            <button type="button" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#duzenle<?= $u['id'] ?>">Düzenle</button>
                                            <form method="post" style="display:inline;" onsubmit="return confirm('Silinsin mi?')">
                                                <input type="hidden" name="id" value="<?= $u['id'] ?>">
                                                <button type="submit" name="sil" class="btn btn-danger btn-sm">Sil</button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- ====================== EKLE MODAL ====================== -->
<div class="modal fade" id="ekleModal">
    <div class="modal-dialog modal-lg">
        <form method="post">
            <div class="modal-content">
                <div class="modal-header bg-success">
                    <h5 class="modal-title">Yeni Üye Ekle</h5>
                    <button type="button" class="close" data-dismiss="modal">×</button>
                </div>
                <div class="modal-body row">
                    <div class="col-md-3"><input name="blok_adi" class="form-control" placeholder="Blok Adı"></div>
                    <div class="col-md-3"><input name="daire_no" class="form-control" placeholder="Daire No" required></div>
                    <div class="col-md-6"><input name="ad_soyad" class="form-control" placeholder="Ad Soyad" required></div>
                    <div class="col-md-6 mt-2"><input name="telefon" class="form-control" placeholder="Telefon (5XXXXXXXXX)" required></div>
                    <div class="col-md-6 mt-2"><input name="email" type="email" class="form-control" placeholder="E-posta"></div>
                    <div class="col-md-6 mt-2"><input name="plaka_no" class="form-control" placeholder="Plaka (opsiyonel)"></div>
                    <div class="col-md-6 mt-2"><input name="sifre" type="text" class="form-control" placeholder="Şifre" required></div>
                    <div class="col-md-3 mt-2">
                        <select name="sahip_kiraci" class="form-control">
                            <option value="sahip">Ev Sahibi</option>
                            <option value="kiraci">Kiracı</option>
                        </select>
                    </div>
                    <div class="col-md-3 mt-2">
                        <select name="aktif" class="form-control">
                            <option value="1">Aktif</option>
                            <option value="0">Pasif</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" name="ekle" class="btn btn-success">Kaydet</button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- ====================== DÜZENLE MODALLARI ====================== -->
<?php foreach ($uyeler as $u): ?>
<div class="modal fade" id="duzenle<?= $u['id'] ?>">
    <div class="modal-dialog modal-lg">
        <form method="post">
            <div class="modal-content">
                <input type="hidden" name="id" value="<?= $u['id'] ?>">
                <input type="hidden" name="eski_sifre" value="<?= $u['sifre'] ?>">
                <div class="modal-header bg-warning">
                    <h5 class="modal-title">Üye Düzenle</h5>
                    <button type="button" class="close" data-dismiss="modal">×</button>
                </div>
                <div class="modal-body row">
                    <div class="col-md-3"><input name="blok_adi" class="form-control" value="<?= htmlspecialchars($u['blok_adi'] ?? '') ?>" placeholder="Blok Adı"></div>
                    <div class="col-md-3"><input name="daire_no" class="form-control" value="<?= htmlspecialchars($u['daire_no']) ?>" required></div>
                    <div class="col-md-6"><input name="ad_soyad" class="form-control" value="<?= htmlspecialchars($u['ad_soyad']) ?>" required></div>
                    <div class="col-md-6 mt-2"><input name="telefon" class="form-control" value="<?= htmlspecialchars($u['telefon']) ?>" required></div>
                    <div class="col-md-6 mt-2"><input name="email" class="form-control" value="<?= htmlspecialchars($u['email']) ?>"></div>
                    <div class="col-md-6 mt-2"><input name="plaka_no" class="form-control" value="<?= htmlspecialchars($u['plaka_no'] ?? '') ?>" placeholder="Plaka"></div>
                    <div class="col-md-6 mt-2"><input name="sifre" type="text" class="form-control" placeholder="Yeni Şifre (boş bırakırsanız değişmez)"></div>
                    <div class="col-md-3 mt-2">
                        <select name="sahip_kiraci" class="form-control">
                            <option value="sahip" <?= $u['sahip_kiraci'] === 'sahip' ? 'selected' : '' ?>>Ev Sahibi</option>
                            <option value="kiraci" <?= $u['sahip_kiraci'] === 'kiraci' ? 'selected' : '' ?>>Kiracı</option>
                        </select>
                    </div>
                    <div class="col-md-3 mt-2">
                        <select name="aktif" class="form-control">
                            <option value="1" <?= $u['aktif'] == 1 ? 'selected' : '' ?>>Aktif</option>
                            <option value="0" <?= $u['aktif'] == 0 ? 'selected' : '' ?>>Pasif</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" name="guncelle" class="btn btn-primary">Güncelle</button>
                </div>
            </div>
        </form>
    </div>
</div>
<?php endforeach; ?>

<!-- DataTables -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap4.min.css">

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>

<script>
$(document).ready(function() {
    var table = $('#uyelerTable').DataTable({
        dom: 'Bfrtip',
        buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
        language: { url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json' },
        responsive: true,
        order: [[0, 'asc'], [1, 'asc']],
        columnDefs: [{ targets: [8], orderable: false }]
    });
    table.buttons().container().appendTo('#export_buttons');
});
</script>

<?php include '../inc/footer.php'; ?>