<?php
require_once __DIR__ . '/../../config/session.php';
requireAdmin();
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../functions/helper.php';
require_once __DIR__ . '/../../functions/csrf.php';

$db = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $username = trim($_POST['username'] ?? '');
    $nama_lengkap = trim($_POST['nama_lengkap'] ?? '');
    $no_hp = trim($_POST['no_hp'] ?? '');
    $role = $_POST['role'] ?? 'user';
    $is_active = $_POST['is_active'] ?? '1';
    $password = $_POST['password'] ?? '';

    try {
        $stmt = $db->prepare("SELECT id FROM users WHERE username = ?");
        $stmt->execute([$username]);
        if ($stmt->fetch()) {
            setFlash('error', 'Username sudah dipakai.');
        } elseif (empty($username) || empty($nama_lengkap)) {
            setFlash('error', 'Username dan Nama Lengkap wajib diisi.');
        } else {
            $plainPassword = $password ?: 'Posyandu123';
            $stmt = $db->prepare("INSERT INTO users (username, password, nama_lengkap, no_hp, role, is_active) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$username, $plainPassword, $nama_lengkap, $no_hp, $role, $is_active]);
            setFlash('success', 'User berhasil ditambahkan. Password default: Posyandu123');
            header('Location: ' . BASE_URL . '/admin/users/');
            exit;
        }
    } catch (PDOException $e) {
        setFlash('error', 'Error: ' . $e->getMessage());
    }
}

require_once '../../includes/header_admin.php';
?>

<div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
    <div>
        <h1 class="text-2xl font-bold text-gray-800">Tambah User Baru</h1>
        <p class="text-gray-500 text-sm mt-1">Buat akun baru untuk admin atau pasien.</p>
    </div>
    <a href="./" class="inline-flex items-center gap-2 px-4 py-2 bg-white border border-gray-200 rounded-xl text-sm font-medium text-gray-600 hover:bg-gray-50 hover:text-gray-900 transition-colors shadow-sm">
        <i class="fas fa-arrow-left"></i> Kembali
    </a>
</div>

<div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
    <div class="px-6 py-4 border-b border-gray-100 bg-gray-50/50 flex items-center gap-2">
        <i class="fas fa-user-plus text-primary"></i>
        <h3 class="font-bold text-gray-800">Form Tambah User</h3>
    </div>
    <div class="p-6">
        <form action="tambah.php" method="POST" class="space-y-5">
            <?= csrfField() ?>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Username (Bisa NIK) <span class="text-red-500">*</span></label>
                <input type="text" name="username" class="w-full px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary text-sm" required>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">Nama Lengkap <span class="text-red-500">*</span></label>
                <input type="text" name="nama_lengkap" class="w-full px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary text-sm" required>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">No. HP / WA</label>
                <input type="text" name="no_hp" class="w-full px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary text-sm">
            </div>
            
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Role Akses</label>
                    <select name="role" class="w-full px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary text-sm bg-white">
                        <option value="admin" selected>Admin / Bidan</option>
                    </select>
                    <p class="text-xs text-gray-400 mt-1"><i class="fas fa-info-circle mr-1"></i> Akun pasien dibuat otomatis saat mendaftarkan ibu hamil baru.</p>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                    <select name="is_active" class="w-full px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary text-sm bg-white">
                        <option value="1" selected>Aktif</option>
                        <option value="0">Non-Aktif</option>
                    </select>
                </div>
            </div>
            
            <div class="border-t border-gray-100 pt-5 mt-2">
                <label class="block text-sm font-medium text-gray-700 mb-1">Password Awal</label>
                <input type="password" name="password" class="w-full px-4 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-primary focus:border-primary text-sm" placeholder="Kosongkan untuk: Posyandu123">
                <p class="text-xs text-gray-500 mt-1">Default password jika dikosongkan: <b>Posyandu123</b></p>
            </div>
            
            <div class="pt-4 flex items-center justify-end gap-3 border-t border-gray-100 mt-6">
                <a href="./" class="px-6 py-2.5 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-xl transition-colors">Batal</a>
                <button type="submit" class="px-6 py-2.5 bg-primary hover:bg-primary-dark text-white font-bold rounded-xl shadow-lg shadow-primary/30 transition-all transform hover:-translate-y-0.5 focus:ring-2 focus:ring-offset-2 focus:ring-primary flex items-center gap-2">
                    <i class="fas fa-save"></i> Simpan User
                </button>
            </div>
        </form>
    </div>
</div>

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