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

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$stmt = $pdo->prepare('SELECT id, name, email, username, role FROM users WHERE id = ? AND role IN ("admin","owner") LIMIT 1');
$stmt->execute([$id]);
$user = $stmt->fetch();

if (!$user) {
    echo '<div class="alert error">User tidak ditemukan.</div>';
    require_once __DIR__ . '/../includes/footer_admin.php';
    exit;
}

$errors = [];
$values = $user;

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'] ?? $user['role']);
    $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 ($password !== '') {
        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 = ?) AND id != ? LIMIT 1');
        $stmt->execute([$values['email'], $values['username'], $id]);
        if ($stmt->fetch()) {
            $errors['email'] = 'Email atau username sudah digunakan.';
        }
    }

    if (!$errors) {
        $pdo->beginTransaction();
        try {
            $stmt = $pdo->prepare('UPDATE users SET name = ?, email = ?, username = ?, role = ? WHERE id = ?');
            $stmt->execute([$values['name'], $values['email'], $values['username'], $values['role'], $id]);

            if ($password !== '') {
                $hash = password_hash($password, PASSWORD_BCRYPT);
                $stmt = $pdo->prepare('UPDATE users SET password_hash = ? WHERE id = ?');
                $stmt->execute([$hash, $id]);
            }

            $pdo->commit();
            flash_message('success', 'User berhasil diperbarui.');
            redirect(base_url('owner/users.php'));
        } catch (Throwable $e) {
            $pdo->rollBack();
            flash_message('error', 'Gagal memperbarui user.');
            redirect(base_url('owner/user_edit.php?id=' . $id));
        }
    }
}
?>

<h2 class="fw-bold mb-4">Edit 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 Baru (opsional)</label>
            <input class="form-control" type="password" name="password">
            <?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">
            <?php if (!empty($errors['password_confirm'])): ?><small class="error"><?= sanitize($errors['password_confirm']); ?></small><?php endif; ?>

            <button class="btn mt-3" type="submit">Simpan Perubahan</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'; ?>
