<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: login.php');
    exit;
}
require_once __DIR__ . '/../src/Core/Database.php';
require_once __DIR__ . '/../src/Includes/helpers.php';
use HatiApp\Core\Database;
$db = new Database();
$conn = $db->getConnection();
$users = [];
$message = $_GET['message'] ?? '';
$message_type = $_GET['status'] ?? '';
try {
    $stmt = $conn->prepare("SELECT id, name, title, email, role, created_at FROM users ORDER BY name ASC");
    $stmt->execute();
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "Hata: " . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <title>Hati App - Kullanıcılar</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<?php require_once __DIR__ . '/../src/Includes/header.php'; ?>
<div class="header-actions">
    <h2>Kullanıcılar</h2>
    <a href="create_user.php">Yeni Kullanıcı Ekle</a>
</div>
<?php if ($message): ?>
    <p style="color: <?php echo $message_type === 'success' ? 'green' : 'red'; ?>;">
        <?php echo htmlspecialchars($message); ?>
    </p>
<?php endif; ?>
<?php if (empty($users)): ?>
    <p>Henüz kayıtlı bir kullanıcı bulunmamaktadır.</p>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>Ad Soyad</th>
                <th>Ünvan</th>
                <th>E-posta</th>
                <th>Yetki</th>
                <th>İşlemler</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($users as $user): ?>
            <tr>
                <td><?php echo htmlspecialchars($user['name']); ?></td>
                <td><?php echo htmlspecialchars($user['title'] ?? 'Belirtilmemiş'); ?></td>
                <td><?php echo htmlspecialchars($user['email']); ?></td>
                <td><?php echo htmlspecialchars(ucfirst($user['role'])); ?></td>
                <td>
    <a href="view_user.php?id=<?php echo $user['id']; ?>">Gör</a> |
    <a href="edit_user.php?id=<?php echo $user['id']; ?>">Düzenle</a> |
    <a href="delete.php?table=users&id=<?php echo $user['id']; ?>&redirect=users.php" onclick="return confirm('Bu kullanıcıyı silmek istediğinizden emin misiniz?');">Sil</a>
</td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>
</main>
</body>
</html>