<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner();
require_once __DIR__ . '/../includes/header_admin.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$users = $pdo->query("SELECT id, name, email, username, role, created_at FROM users WHERE role IN ('admin','owner') ORDER BY created_at DESC")->fetchAll();
?>

<h2 class="fw-bold mb-4">Manajemen User</h2>

<div class="d-flex justify-content-end mb-3">
    <a class="btn" href="<?= base_url('owner/user_add.php'); ?>">Tambah User</a>
</div>

<div class="card shadow-sm">
    <div class="card-body table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>Nama</th>
                    <th>Email</th>
                    <th>Username</th>
                    <th>Role</th>
                    <th>Terdaftar</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!$users): ?>
                    <tr><td colspan="6">Belum ada user admin/owner.</td></tr>
                <?php endif; ?>
                <?php foreach ($users as $user): ?>
                    <tr>
                        <td><?= sanitize($user['name']); ?></td>
                        <td><?= sanitize($user['email']); ?></td>
                        <td><?= sanitize($user['username']); ?></td>
                        <td><?= strtoupper(sanitize($user['role'])); ?></td>
                        <td><?= sanitize(date('d M Y', strtotime($user['created_at']))); ?></td>
                        <td>
                            <a class="btn btn-sm" href="<?= base_url('owner/user_edit.php?id=' . (int) $user['id']); ?>">Edit</a>
                            <form method="post" action="<?= base_url('owner/user_delete.php'); ?>" class="d-inline">
                                <input type="hidden" name="id" value="<?= (int) $user['id']; ?>">
                                <button class="btn btn-sm" type="submit">Hapus</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer_admin.php'; ?>
