<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/guvenlik_kontrol.php';

$sayfa_baslik = __("user_management");
$aktif_sirket_id = $_SESSION['aktif_sirket_id'] ?? 0;

// Yetki kontrolü - Sadece admin ve yönetici erişebilir
if (!isset($_SESSION['yetki_seviyesi']) || !in_array($_SESSION['yetki_seviyesi'], ['admin', 'yonetici'])) {
    $_SESSION['hata'] = __("no_permission_to_access_this_page");
    header("Location: index.php");
    exit();
}

// Şirket kontrolü
if (empty($aktif_sirket_id)) {
    $_SESSION['hata'] = __("company_selection_required");
    header("Location: index.php");
    exit();
}

// Filtreleme parametreleri
$filtreler = [];
$sayfa = isset($_GET['sayfa']) ? max(1, intval($_GET['sayfa'])) : 1;
$limit = 20;
$offset = ($sayfa - 1) * $limit;

// Filtreleri al
if (!empty($_GET['yetki_seviyesi'])) {
    $filtreler['yetki_seviyesi'] = $_GET['yetki_seviyesi'];
}
if (isset($_GET['aktif'])) {
    $filtreler['aktif'] = intval($_GET['aktif']);
}
if (!empty($_GET['arama'])) {
    $filtreler['arama'] = $_GET['arama'];
}

// Kullanıcı durumu değiştirme
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['durum_degistir']) && isset($_POST['kullanici_id'])) {
    $kullanici_id = intval($_POST['kullanici_id']);
    $yeni_durum = intval($_POST['yeni_durum']);
    
    try {
        kullanici_guncelle($db, $kullanici_id, ['aktif' => $yeni_durum]);
        $_SESSION['mesaj'] = __("user_status_updated_successfully");
    } catch (Exception $e) {
        $_SESSION['hata'] = $e->getMessage();
    }
    
    header("Location: kullanicilar.php");
    exit();
}

// Şirket filtresini ekle
$filtreler['sirket_id'] = $aktif_sirket_id;

// Kullanıcıları getir
$kullanicilar = kullanicilari_listele($db, $filtreler, $limit, $offset);
$toplam_kullanici = kullanici_sayisi_getir($db, $filtreler);
$toplam_sayfa = ceil($toplam_kullanici / $limit);

// Yetki seviyeleri
$yetki_seviyeleri = [
    'admin' => __("admin"),
    'yonetici' => __("manager"), 
    'kullanici' => __("user"),
    'misafir' => __("guest")
];
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= __("odjoo_management") ?> - <?= temizle($sayfa_baslik) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="bi bi-people-fill"></i> <?= temizle($sayfa_baslik) ?></h2>
            <a href="kullanici_ekle.php" class="btn btn-primary">
                <i class="bi bi-person-plus"></i> <?= __("new_user") ?>
            </a>
        </div>

        <!-- Filtreler -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-funnel"></i> <?= __("filters") ?></h5>
            </div>
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <label for="yetki_seviyesi" class="form-label"><?= __("permission_level") ?></label>
                        <select class="form-select" id="yetki_seviyesi" name="yetki_seviyesi">
                            <option value=""><?= __("all") ?></option>
                            <?php foreach ($yetki_seviyeleri as $seviye => $aciklama): ?>
                                <option value="<?= $seviye ?>" <?= isset($filtreler['yetki_seviyesi']) && $filtreler['yetki_seviyesi'] == $seviye ? 'selected' : '' ?>>
                                    <?= $aciklama ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label for="aktif" class="form-label"><?= __("status") ?></label>
                        <select class="form-select" id="aktif" name="aktif">
                            <option value=""><?= __("all") ?></option>
                            <option value="1" <?= isset($filtreler['aktif']) && $filtreler['aktif'] == 1 ? 'selected' : '' ?>><?= __("active") ?></option>
                            <option value="0" <?= isset($filtreler['aktif']) && $filtreler['aktif'] == 0 ? 'selected' : '' ?>><?= __("inactive") ?></option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="arama" class="form-label"><?= __("search") ?></label>
                        <input type="text" class="form-control" id="arama" name="arama" 
                               placeholder="<?= __("search_users_placeholder") ?>"
                               value="<?= temizle($filtreler['arama'] ?? '') ?>">
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="bi bi-search"></i> <?= __("search") ?>
                        </button>
                        <a href="kullanicilar.php" class="btn btn-secondary">
                            <i class="bi bi-x-circle"></i> <?= __("clear") ?>
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Kullanıcı Listesi -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><?= __("users") ?> (<?= number_format($toplam_kullanici) ?> <?= $toplam_kullanici == 1 ? __("user") : __("users") ?>)</h5>
            </div>
            <div class="card-body p-0">
                <?php if (!empty($kullanicilar)): ?>
                    <div class="table-responsive">
                        <table class="table table-striped table-hover mb-0">
                            <thead class="table-dark">
                                <tr>
                                    <th><?= __("username") ?></th>
                                    <th><?= __("full_name") ?></th>
                                    <th><?= __("email") ?></th>
                                    <th><?= __("permission_level") ?></th>
                                    <th><?= __("status") ?></th>
                                    <th><?= __("last_login") ?></th>
                                    <th><?= __("registration_date") ?></th>
                                    <th><?= __("actions") ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($kullanicilar as $kullanici): ?>
                                    <tr>
                                        <td>
                                            <strong><?= temizle($kullanici['kullanici_adi']) ?></strong>
                                            <?php if ($kullanici['id'] == $_SESSION['kullanici_id']): ?>
                                                <span class="badge bg-info ms-1"><?= __("you") ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= temizle($kullanici['ad_soyad']) ?></td>
                                        <td>
                                            <?php if ($kullanici['email']): ?>
                                                <a href="mailto:<?= temizle($kullanici['email']) ?>"><?= temizle($kullanici['email']) ?></a>
                                            <?php else: ?>
                                                <span class="text-muted">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php
                                            switch($kullanici['yetki_seviyesi']) {
                                                case 'admin':
                                                    $badge_class = 'bg-danger';
                                                    break;
                                                case 'yonetici':
                                                    $badge_class = 'bg-warning';
                                                    break;
                                                case 'kullanici':
                                                    $badge_class = 'bg-primary';
                                                    break;
                                                case 'misafir':
                                                    $badge_class = 'bg-secondary';
                                                    break;
                                                default:
                                                    $badge_class = 'bg-dark';
                                            }
                                            ?>
                                            <span class="badge <?= $badge_class ?>">
                                                <?= $yetki_seviyeleri[$kullanici['yetki_seviyesi']] ?? $kullanici['yetki_seviyesi'] ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($kullanici['aktif']): ?>
                                                <span class="badge bg-success"><?= __("active") ?></span>
                                            <?php else: ?>
                                                <span class="badge bg-danger"><?= __("inactive") ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($kullanici['son_giris_tarihi']): ?>
                                                <small><?= date('d.m.Y H:i', strtotime($kullanici['son_giris_tarihi'])) ?></small>
                                                <br><small class="text-muted"><?= sprintf(__("login_count"), $kullanici['giris_sayisi']) ?></small>
                                            <?php else: ?>
                                                <span class="text-muted"><?= __("never_logged_in") ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <small><?= date('d.m.Y', strtotime($kullanici['olusturulma_tarihi'])) ?></small>
                                            <?php if ($kullanici['olusturan_ad_soyad']): ?>
                                                <br><small class="text-muted"><?= sprintf(__("created_by"), temizle($kullanici['olusturan_ad_soyad'])) ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <a href="kullanici_duzenle.php?id=<?= $kullanici['id'] ?>" 
                                                   class="btn btn-outline-primary btn-sm" title="Düzenle">
                                                    <i class="bi bi-pencil"></i> <?= __("edit") ?>
                                                </a>
                                                
                                                <?php if ($kullanici['id'] != $_SESSION['kullanici_id']): ?>
                                                    <!-- Durum Değiştir -->
                                                    <form method="POST" class="d-inline">
                                                        <input type="hidden" name="kullanici_id" value="<?= $kullanici['id'] ?>">
                                                        <input type="hidden" name="yeni_durum" value="<?= $kullanici['aktif'] ? 0 : 1 ?>">
                                                        <button type="submit" name="durum_degistir" 
                                                                class="btn btn-outline-<?= $kullanici['aktif'] ? 'warning' : 'success' ?> btn-sm"
                                                                title="<?= $kullanici['aktif'] ? __('deactivate') : __('activate') ?>"
                                                                onclick="return confirm('<?= __("confirm_change_user_status") ?>')">
                                                            <i class="bi bi-<?= $kullanici['aktif'] ? 'pause' : 'play' ?>"></i>
                                                        </button>
                                                    </form>
                                                    
                                                    <!-- Sil -->
                                                    <?php if ($_SESSION['yetki_seviyesi'] === 'admin'): ?>
                                                        <form method="POST" action="kullanici_sil.php" class="d-inline">
                                                            <input type="hidden" name="kullanici_id" value="<?= $kullanici['id'] ?>">
                                                            <button type="submit" 
                                                                    class="btn btn-outline-danger btn-sm" title="Sil"
                                                                    onclick="return confirm('<?= __("confirm_delete_user") ?>')">
                                                                <i class="bi bi-trash"></i> <?= __("delete") ?>
                                                            </button>
                                                        </form>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <!-- Sayfalama -->
                    <?php if ($toplam_sayfa > 1): ?>
                        <div class="card-footer">
                            <nav aria-label="Kullanıcı sayfalama">
                                <ul class="pagination justify-content-center mb-0">
                                    <?php if ($sayfa > 1): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['sayfa' => $sayfa - 1])) ?>">Önceki</a>
                                        </li>
                                    <?php endif; ?>
                                    
                                    <?php for ($i = max(1, $sayfa - 2); $i <= min($toplam_sayfa, $sayfa + 2); $i++): ?>
                                        <li class="page-item <?= $i == $sayfa ? 'active' : '' ?>">
                                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['sayfa' => $i])) ?>"><?= $i ?></a>
                                        </li>
                                    <?php endfor; ?>
                                    
                                    <?php if ($sayfa < $toplam_sayfa): ?>
                                        <li class="page-item">
                                            <a class="page-link" href="?<?= http_build_query(array_merge($_GET, ['sayfa' => $sayfa + 1])) ?>">Sonraki</a>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </nav>
                        </div>
                    <?php endif; ?>
                <?php else: ?>
                    <div class="text-center py-5">
                        <i class="bi bi-people display-1 text-muted"></i>
                        <h5 class="mt-3"><?= __("no_users_found") ?></h5>
                        <p class="text-muted"><?= __("no_users_matching_criteria") ?></p>
                        <a href="kullanici_ekle.php" class="btn btn-primary">
                            <i class="bi bi-person-plus"></i> İlk Kullanıcıyı Ekle
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <?php include __DIR__ . '/../includes/footer.php'; ?>
</body>
</html>

