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

$errors = [];
$values = [
    'name' => '',
    'email' => '',
    'username' => '',
    'role' => 'admin',
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $values['name'] = trim($_POST['name'] ?? '');
    $values['email'] = trim($_POST['email'] ?? '');
    $values['username'] = trim($_POST['username'] ?? '');
    $values['role'] = trim($_POST['role'] ?? 'admin');
    $password = $_POST['password'] ?? '';
    $passwordConfirm = $_POST['password_confirm'] ?? '';

    if ($values['name'] === '') {
        $errors['name'] = 'Nama wajib diisi.';
    }

    if ($values['email'] === '' || !filter_var($values['email'], FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Email tidak valid.';
    }

    if ($values['username'] === '') {
        $errors['username'] = 'Username wajib diisi.';
    }

    if (!in_array($values['role'], ['admin', 'owner'], true)) {
        $errors['role'] = 'Role tidak valid.';
    }

    if (strlen($password) < 6) {
        $errors['password'] = 'Password minimal 6 karakter.';
    }

    if ($password !== $passwordConfirm) {
        $errors['password_confirm'] = 'Konfirmasi password tidak sama.';
    }

    if (!$errors) {
        $stmt = $pdo->prepare('SELECT id FROM users WHERE email = ? OR username = ? LIMIT 1');
        $stmt->execute([$values['email'], $values['username']]);
        if ($stmt->fetch()) {
            $errors['email'] = 'Email atau username sudah digunakan.';
        }
    }

    if (!$errors) {
        $hash = password_hash($password, PASSWORD_BCRYPT);
        $stmt = $pdo->prepare('INSERT INTO users (name, email, username, password_hash, role, is_active) VALUES (?, ?, ?, ?, ?, 1)');
        $stmt->execute([
            $values['name'],
            $values['email'],
            $values['username'],
            $hash,
            $values['role'],
        ]);
        flash_message('success', 'User berhasil ditambahkan.');
        redirect(base_url('owner/users.php'));
    }
}
?>

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

<div class="card shadow-sm">
    <div class="card-body">
        <form method="post">
            <label>Nama</label>
            <input class="form-control" type="text" name="name" value="<?= sanitize($values['name']); ?>" required>
            <?php if (!empty($errors['name'])): ?><small class="error"><?= sanitize($errors['name']); ?></small><?php endif; ?>

            <label>Email</label>
            <input class="form-control" type="email" name="email" value="<?= sanitize($values['email']); ?>" required>
            <?php if (!empty($errors['email'])): ?><small class="error"><?= sanitize($errors['email']); ?></small><?php endif; ?>

            <label>Username</label>
            <input class="form-control" type="text" name="username" value="<?= sanitize($values['username']); ?>" required>
            <?php if (!empty($errors['username'])): ?><small class="error"><?= sanitize($errors['username']); ?></small><?php endif; ?>

            <label>Role</label>
            <select class="form-select" name="role" required>
                <option value="admin" <?= $values['role'] === 'admin' ? 'selected' : ''; ?>>Admin</option>
                <option value="owner" <?= $values['role'] === 'owner' ? 'selected' : ''; ?>>Owner</option>
            </select>
            <?php if (!empty($errors['role'])): ?><small class="error"><?= sanitize($errors['role']); ?></small><?php endif; ?>

            <label>Password</label>
            <input class="form-control" type="password" name="password" required>
            <?php if (!empty($errors['password'])): ?><small class="error"><?= sanitize($errors['password']); ?></small><?php endif; ?>

            <label>Konfirmasi Password</label>
            <input class="form-control" type="password" name="password_confirm" required>
            <?php if (!empty($errors['password_confirm'])): ?><small class="error"><?= sanitize($errors['password_confirm']); ?></small><?php endif; ?>

            <button class="btn mt-3" type="submit">Simpan</button>
            <a class="btn btn-sm" href="<?= base_url('owner/users.php'); ?>">Batal</a>
        </form>
    </div>
</div>

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