<?php
session_start();
require_once 'config/database.php';

// Get user info
$user_id = $_SESSION['user_id'];
$sql = "SELECT username, email, role FROM users WHERE id = $user_id";
$result = $con->query($sql);
$user = $result ? $result->fetch_assoc() : null;

// If user not found, create empty user array to prevent sidebar errors
if (!$user) {
    $user = [
        'username' => 'Unknown',
        'email' => '',
        'role' => 'user'
    ];
}

// Get all users with device counts (admin only)
if ($user['role'] === 'admin') {
    $users_sql = "SELECT 
        u.id, 
        u.username, 
        u.email, 
        CONCAT(u.first_name, ' ', u.last_name) as full_name,
        u.role,
        u.created_at, 
        u.last_login,
        COUNT(d.id) as device_count,
        SUM(CASE WHEN d.status = 'online' THEN 1 ELSE 0 END) as online_devices
        FROM users u 
        LEFT JOIN devices d ON u.id = d.owner_id 
        GROUP BY u.id, u.username, u.email, u.first_name, u.last_name, u.role, u.created_at, u.last_login 
        ORDER BY u.created_at DESC";
    $users_result = $con->query($users_sql);
    $users = $users_result ? $users_result->fetch_all(MYSQLI_ASSOC) : [];
}

// Layout variables
$page_title = 'Tüm Kullanıcılar';
$breadcrumb_title = 'Kullanıcılar';
$current_page = 'all_users';
$extra_css = '<link rel="stylesheet" href="assets/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="assets/plugins/datatables-responsive/css/responsive.bootstrap4.min.css">
<link rel="stylesheet" href="assets/dist/css/buttons.dataTables.min.css">';
$page_scripts = '<script src="assets/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="assets/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="assets/plugins/datatables-responsive/js/dataTables.responsive.min.js"></script>
<script src="assets/dist/js/dataTables.buttons.min.js"></script>
<script src="assets/dist/js/jszip.min.js"></script>
<script src="assets/dist/js/pdfmake.min.js"></script>
<script src="assets/dist/js/vfs_fonts.js"></script>
<script src="assets/dist/js/buttons.html5.min.js"></script>
<script src="assets/dist/js/buttons.print.min.js"></script>
<script src="assets/plugins/sweetalert2/sweetalert2.min.js"></script>';

?>

<?php require_once 'layouts/header.php'; ?>

<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <?php require_once 'layouts/navbar.php'; ?>
    <?php require_once 'layouts/sidebar.php'; ?>

    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <?php require_once 'layouts/header_dashboard.php'; ?>

        <!-- Main content -->
        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Kullanıcı Listesi</h3>
                            <?php if ($user['role'] === 'admin'): ?>
                            <div class="card-tools">
                                <a href="add_user.php" class="btn btn-primary btn-sm mr-2">
                                    <i class="fas fa-plus"></i> Yeni Kullanıcı
                                </a>
                                <div class="btn-group">
                                    <button class="btn btn-success btn-sm" onclick="exportToExcel()">
                                        <i class="fas fa-file-excel"></i> Excel
                                    </button>
                                    <button class="btn btn-info btn-sm" onclick="exportToCSV()">
                                        <i class="fas fa-file-csv"></i> CSV
                                    </button>
                                    <button class="btn btn-danger btn-sm" onclick="exportToPDF()">
                                        <i class="fas fa-file-pdf"></i> PDF
                                    </button>
                                    <button class="btn btn-secondary btn-sm" onclick="printTable()">
                                        <i class="fas fa-print"></i> Yazdır
                                    </button>
                                    <button class="btn btn-warning btn-sm" onclick="copyTable()">
                                        <i class="fas fa-copy"></i> Kopyala
                                    </button>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="card-body">
                            <?php if ($user['role'] === 'admin'): ?>
                            <table id="usersTable" class="table table-bordered table-striped">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Kullanıcı Adı</th>
                                        <th>E-posta</th>
                                        <th>Ad Soyad</th>
                                        <th>Tip</th>
                                        <th>Cihaz Sayısı</th>
                                        <th>Online Cihaz</th>
                                        <th>Kayıt Tarihi</th>
                                        <th>Son Giriş</th>
                                        <th>İşlemler</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($users as $user_row): ?>
                                    <tr>
                                        <td><?php echo $user_row['id']; ?></td>
                                        <td><?php echo htmlspecialchars($user_row['username']); ?></td>
                                        <td><?php echo htmlspecialchars($user_row['email']); ?></td>
                                        <td><?php echo htmlspecialchars($user_row['full_name']); ?></td>
                                        <td>
                                            <?php if ($user_row['role'] === 'admin'): ?>
                                                <span class="badge badge-danger">Admin</span>
                                            <?php else: ?>
                                                <span class="badge badge-info">User</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge badge-primary"><?php echo $user_row['device_count']; ?></span>
                                        </td>
                                        <td>
                                            <span class="badge badge-success"><?php echo $user_row['online_devices']; ?></span>
                                        </td>
                                        <td><?php echo date('d.m.Y H:i', strtotime($user_row['created_at'])); ?></td>
                                        <td><?php echo $user_row['last_login'] ? date('d.m.Y H:i', strtotime($user_row['last_login'])) : '-'; ?></td>
                                        <td>
                                            <div class="btn-group">
                                                <button class="btn btn-sm btn-info" onclick="editUser(<?php echo $user_row['id']; ?>)">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <?php if ($user_row['id'] != $user_id): ?>
                                                <button class="btn btn-sm btn-danger" onclick="deleteUser(<?php echo $user_row['id']; ?>)">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                            <?php else: ?>
                            <div class="alert alert-warning">
                                <h5><i class="icon fas fa-exclamation-triangle"></i> Yetki Hatası</h5>
                                Kullanıcı listesini görüntüleme yetkiniz yok. Sadece yöneticiler bu sayfayı görebilir.
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#usersTable').DataTable({
        "responsive": true,
        "lengthChange": false,
        "autoWidth": false,
        "ordering": true,
        "info": true,
        "paging": true,
        "search": true,
        "dom": 'Bfrtip',
        "buttons": [
            {
                extend: 'excelHtml5',
                text: '<i class="fas fa-file-excel"></i> Excel',
                className: 'btn btn-success btn-sm',
                filename: 'kullanici_listesi_' + new Date().toISOString().slice(0,10),
                exportOptions: {
                    columns: [0, 1, 2, 3, 4, 5, 6, 7, 8]
                }
            },
            {
                extend: 'csvHtml5',
                text: '<i class="fas fa-file-csv"></i> CSV',
                className: 'btn btn-info btn-sm',
                filename: 'kullanici_listesi_' + new Date().toISOString().slice(0,10),
                exportOptions: {
                    columns: [0, 1, 2, 3, 4, 5, 6, 7, 8]
                }
            },
            {
                extend: 'pdfHtml5',
                text: '<i class="fas fa-file-pdf"></i> PDF',
                className: 'btn btn-danger btn-sm',
                filename: 'kullanici_listesi_' + new Date().toISOString().slice(0,10),
                exportOptions: {
                    columns: [0, 1, 2, 3, 4, 5, 6, 7, 8]
                }
            },
            {
                extend: 'print',
                text: '<i class="fas fa-print"></i> Yazdır',
                className: 'btn btn-secondary btn-sm',
                exportOptions: {
                    columns: [0, 1, 2, 3, 4, 5, 6, 7, 8]
                }
            },
            {
                extend: 'copy',
                text: '<i class="fas fa-copy"></i> Kopyala',
                className: 'btn btn-warning btn-sm',
                exportOptions: {
                    columns: [0, 1, 2, 3, 4, 5, 6, 7, 8]
                }
            }
        ],
        "language": {
            "search": "Ara:",
            "lengthMenu": "Show _MENU_ entries",
            "info": "Showing _START_ to _END_ of _TOTAL_ entries",
            "paginate": {
                "first": "İlk",
                "last": "Son",
                "next": "Sonraki",
                "previous": "Önceki"
            }
        }
    });
});

function exportToExcel() {
    $('.buttons-excelHtml5').click();
}

function exportToCSV() {
    $('.buttons-csvHtml5').click();
}

function exportToPDF() {
    $('.buttons-pdfHtml5').click();
}

function printTable() {
    $('.buttons-print').click();
}

function copyTable() {
    $('.buttons-copy').click();
}

function editUser(userId) {
    Swal.fire({
        icon: 'info',
        title: 'Düzenleme',
        text: 'Kullanıcı düzenleme özelliği yakında eklenecek!'
    });
}

function deleteUser(userId) {
    Swal.fire({
        title: 'Emin misiniz?',
        text: "Bu kullanıcıyı silmek istediğinizden emin misiniz?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Evet, sil!',
        cancelButtonText: 'İptal'
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = 'delete_user.php?id=' + userId;
        }
    });
}
</script>

<?php require_once 'layouts/footer.php'; ?>
