<?php
/**
 * Manajemen User
 * Koperasi Management System
 * Admin-only: manage operator and admin accounts
 */

$pageTitle = 'Manajemen User';
$pageSubtitle = 'Kelola akun pengguna sistem';

require_once __DIR__ . '/config/database.php';
require_once __DIR__ . '/config/auth.php';
requireAdmin();

$db = getDB();

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        // Check duplicate username
        $check = $db->prepare("SELECT id FROM users WHERE username = ?");
        $check->execute([trim($_POST['username'])]);
        if ($check->fetch()) {
            setFlash('danger', 'Username sudah digunakan.');
            header('Location: users.php');
            exit;
        }

        $stmt = $db->prepare("INSERT INTO users (username, password, nama_lengkap, role, status) VALUES (?, ?, ?, ?, ?)");
        $stmt->execute([
            trim($_POST['username']),
            password_hash($_POST['password'], PASSWORD_DEFAULT),
            sanitize($_POST['nama_lengkap']),
            $_POST['role'] ?? 'operator',
            $_POST['status'] ?? 'aktif'
        ]);
        setFlash('success', 'User berhasil ditambahkan.');
        header('Location: users.php');
        exit;
    }

    if ($action === 'edit') {
        $id = (int)$_POST['id'];

        // Prevent editing own role/status to avoid lockout
        if ($id === (int)$_SESSION['user_id']) {
            // Only allow name change
            $stmt = $db->prepare("UPDATE users SET nama_lengkap = ? WHERE id = ?");
            $stmt->execute([sanitize($_POST['nama_lengkap']), $id]);
        } else {
            $stmt = $db->prepare("UPDATE users SET nama_lengkap = ?, role = ?, status = ? WHERE id = ?");
            $stmt->execute([
                sanitize($_POST['nama_lengkap']),
                $_POST['role'] ?? 'operator',
                $_POST['status'] ?? 'aktif',
                $id
            ]);
        }

        // Update password if provided
        if (!empty($_POST['password'])) {
            $pwStmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
            $pwStmt->execute([password_hash($_POST['password'], PASSWORD_DEFAULT), $id]);
        }

        setFlash('success', 'Data user berhasil diperbarui.');
        header('Location: users.php');
        exit;
    }

    if ($action === 'delete') {
        $id = (int)$_POST['id'];
        // Prevent self-delete
        if ($id === (int)$_SESSION['user_id']) {
            setFlash('danger', 'Tidak dapat menghapus akun sendiri.');
        } else {
            $stmt = $db->prepare("DELETE FROM users WHERE id = ?");
            $stmt->execute([$id]);
            setFlash('success', 'User berhasil dihapus.');
        }
        header('Location: users.php');
        exit;
    }
}

// Get all users
$userList = $db->query("SELECT * FROM users ORDER BY created_at DESC")->fetchAll();

// Edit data
$editData = null;
if (isset($_GET['edit'])) {
    $editStmt = $db->prepare("SELECT * FROM users WHERE id = ?");
    $editStmt->execute([$_GET['edit']]);
    $editData = $editStmt->fetch();
}

include __DIR__ . '/includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2><i class="fas fa-user-shield" style="color: var(--primary-500); margin-right: 8px;"></i>Daftar User</h2>
        <button class="btn btn-primary" onclick="openModal('addUserModal')">
            <i class="fas fa-plus"></i> Tambah User
        </button>
    </div>

    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>User</th>
                    <th>Username</th>
                    <th>Role</th>
                    <th>Status</th>
                    <th>Login Terakhir</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($userList as $u): ?>
                    <tr>
                        <td>
                            <div class="member-cell">
                                <div class="member-avatar avatar-<?= ($u['id'] % 6) + 1 ?>">
                                    <?php
                                    $words = explode(' ', $u['nama_lengkap']);
                                    $init = strtoupper(substr($words[0], 0, 1));
                                    if (count($words) > 1) $init .= strtoupper(substr(end($words), 0, 1));
                                    echo $init;
                                    ?>
                                </div>
                                <div class="member-details">
                                    <div class="member-name"><?= htmlspecialchars($u['nama_lengkap']) ?></div>
                                    <?php if ($u['id'] == $_SESSION['user_id']): ?>
                                        <div class="member-id" style="color: var(--primary-500);">● Anda</div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </td>
                        <td><code style="background: var(--gray-100); padding: 3px 8px; border-radius: 4px; font-size: 0.85rem;"><?= htmlspecialchars($u['username']) ?></code></td>
                        <td>
                            <span class="badge <?= $u['role'] === 'admin' ? 'badge-primary' : 'badge-info' ?>">
                                <i class="fas fa-<?= $u['role'] === 'admin' ? 'shield-alt' : 'user' ?>"></i>
                                <?= ucfirst($u['role']) ?>
                            </span>
                        </td>
                        <td>
                            <span class="badge <?= $u['status'] === 'aktif' ? 'badge-success' : 'badge-danger' ?>">
                                <?= ucfirst($u['status']) ?>
                            </span>
                        </td>
                        <td>
                            <?php if ($u['last_login']): ?>
                                <?= formatTanggal($u['last_login']) ?>
                                <div class="text-muted" style="font-size: 0.75rem;"><?= date('H:i', strtotime($u['last_login'])) ?> WIB</div>
                            <?php else: ?>
                                <span class="text-muted">Belum pernah</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div class="action-buttons">
                                <a href="users.php?edit=<?= $u['id'] ?>" class="btn btn-icon btn-outline" title="Edit">
                                    <i class="fas fa-pen" style="color: var(--info-500);"></i>
                                </a>
                                <?php if ($u['id'] != $_SESSION['user_id']): ?>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus user <?= htmlspecialchars($u['nama_lengkap']) ?>?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $u['id'] ?>">
                                        <button type="submit" class="btn btn-icon btn-outline" title="Hapus">
                                            <i class="fas fa-trash" style="color: var(--danger-500);"></i>
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Add User Modal -->
<div class="modal" id="addUserModal">
    <div class="modal-header">
        <h3><i class="fas fa-user-plus" style="color: var(--primary-500); margin-right: 8px;"></i>Tambah User Baru</h3>
        <button class="modal-close" onclick="closeModal('addUserModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="add">
        <div class="modal-body">
            <div class="form-group">
                <label>Nama Lengkap <span class="required">*</span></label>
                <input type="text" name="nama_lengkap" class="form-control" required placeholder="Masukkan nama lengkap">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Username <span class="required">*</span></label>
                    <input type="text" name="username" class="form-control" required placeholder="Username login" autocomplete="off">
                </div>
                <div class="form-group">
                    <label>Password <span class="required">*</span></label>
                    <input type="password" name="password" class="form-control" required placeholder="Minimal 6 karakter" minlength="6" autocomplete="new-password">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Role</label>
                    <select name="role" class="form-control">
                        <option value="operator">Operator</option>
                        <option value="admin">Admin</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Status</label>
                    <select name="status" class="form-control">
                        <option value="aktif">Aktif</option>
                        <option value="nonaktif">Nonaktif</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('addUserModal')">Batal</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan</button>
        </div>
    </form>
</div>

<!-- Edit User Modal -->
<?php if ($editData): ?>
<script>document.addEventListener('DOMContentLoaded', () => openModal('editUserModal'));</script>
<div class="modal" id="editUserModal">
    <div class="modal-header">
        <h3><i class="fas fa-user-edit" style="color: var(--info-500); margin-right: 8px;"></i>Edit User</h3>
        <button class="modal-close" onclick="window.location='users.php'"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST">
        <input type="hidden" name="action" value="edit">
        <input type="hidden" name="id" value="<?= $editData['id'] ?>">
        <div class="modal-body">
            <div class="form-group">
                <label>Nama Lengkap <span class="required">*</span></label>
                <input type="text" name="nama_lengkap" class="form-control" required value="<?= htmlspecialchars($editData['nama_lengkap']) ?>">
            </div>
            <div class="form-group">
                <label>Username</label>
                <input type="text" class="form-control" value="<?= htmlspecialchars($editData['username']) ?>" disabled>
                <span class="form-text">Username tidak dapat diubah.</span>
            </div>
            <div class="form-group">
                <label>Password Baru</label>
                <input type="password" name="password" class="form-control" placeholder="Kosongkan jika tidak ingin mengubah" minlength="6" autocomplete="new-password">
                <span class="form-text">Isi hanya jika ingin mengganti password.</span>
            </div>
            <?php if ($editData['id'] != $_SESSION['user_id']): ?>
                <div class="form-row">
                    <div class="form-group">
                        <label>Role</label>
                        <select name="role" class="form-control">
                            <option value="operator" <?= $editData['role'] === 'operator' ? 'selected' : '' ?>>Operator</option>
                            <option value="admin" <?= $editData['role'] === 'admin' ? 'selected' : '' ?>>Admin</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Status</label>
                        <select name="status" class="form-control">
                            <option value="aktif" <?= $editData['status'] === 'aktif' ? 'selected' : '' ?>>Aktif</option>
                            <option value="nonaktif" <?= $editData['status'] === 'nonaktif' ? 'selected' : '' ?>>Nonaktif</option>
                        </select>
                    </div>
                </div>
            <?php else: ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i>
                    Anda tidak dapat mengubah role dan status akun sendiri.
                </div>
            <?php endif; ?>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="window.location='users.php'">Batal</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Perbarui</button>
        </div>
    </form>
</div>
<?php endif; ?>

<?php include __DIR__ . '/includes/footer.php'; ?>
