<?php
require_once __DIR__ . '/../models/User.php';
class UserController {
    public function index() {
        if ($_SESSION['user']['role'] !== 'admin') { echo 'Access denied.'; exit; }
        if (!isset($_SESSION['user'])) { header('Location: index.php?controller=auth&action=login'); exit; }
        $model = new User();
        $users = $model->all();
        include __DIR__ . '/../views/user/list.php';
    }

    public function add() {
        if ($_SESSION['user']['role'] !== 'admin') { echo 'Access denied.'; exit; }
        if (!isset($_SESSION['user'])) { header('Location: index.php?controller=auth&action=login'); exit; }
        $errors = [];
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf'] ?? '')) { $errors[] = 'Invalid CSRF token.'; }
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $fullname = trim($_POST['fullname'] ?? '');
            if ($username === '') $errors[] = 'Username is required.';
            if ($password === '') $errors[] = 'Password is required.';
            if (empty($errors)) {
                $model = new User();
                $model->create($username, $password, $fullname, $_POST['role'] ?? 'user');
                header('Location: index.php?controller=user&action=index');
                exit;
            }
        }
        include __DIR__ . '/../views/user/add.php';
    }

    public function edit() {
        if ($_SESSION['user']['role'] !== 'admin') { echo 'Access denied.'; exit; }
        if (!isset($_SESSION['user'])) { header('Location: index.php?controller=auth&action=login'); exit; }
        $id = $_GET['id'] ?? null;
        $model = new User();
        $user = $model->get($id);
        if (!$user) { echo 'User not found'; exit; }
        $errors = [];
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf'] ?? '')) { $errors[] = 'Invalid CSRF token.'; }
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $fullname = trim($_POST['fullname'] ?? '');
            if ($username === '') $errors[] = 'Username is required.';
            if (empty($errors)) {
                $model->update($id, $username, $password, $fullname, $_POST['role'] ?? 'user');
                header('Location: index.php?controller=user&action=index');
                exit;
            }
        }
        include __DIR__ . '/../views/user/edit.php';
    }

    public function delete() {
        if ($_SESSION['user']['role'] !== 'admin') { echo 'Access denied.'; exit; }
        if (!isset($_SESSION['user'])) { header('Location: index.php?controller=auth&action=login'); exit; }
        $id = $_GET['id'] ?? null;
        $model = new User();
        $model->delete($id);
        header('Location: index.php?controller=user&action=index');
        exit;
    }
}
?>