<?php
// admin/users/tambah.php
$pageTitle = 'Tambah User';
require_once '../../includes/config.php';
require_once '../../includes/database.php';
require_once '../../includes/functions.php';
require_once '../../includes/auth.php';

// Mulai session jika belum dimulai
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Cek apakah user sudah login dan role-nya admin
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'admin') {
    // Redirect ke halaman login jika belum login atau bukan admin
    setFlash('login_required', 'Anda harus login sebagai admin untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

// Koneksi database
$db = dbConnect();

// Inisialisasi variabel error
$errors = [];

// Proses form jika ada submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Ambil data dari form
    $username = sanitize($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $nama_lengkap = sanitize($_POST['nama_lengkap'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $no_telp = sanitize($_POST['no_telp'] ?? '');
    $alamat = sanitize($_POST['alamat'] ?? '');
    $role = sanitize($_POST['role'] ?? 'donatur');
    
    // Validasi data
    if (empty($username)) {
        $errors[] = 'Username tidak boleh kosong';
    } else {
        // Cek apakah username sudah ada
        $db->query("SELECT id FROM users WHERE username = :username");
        $db->bind(':username', $username);
        if ($db->single()) {
            $errors[] = 'Username sudah digunakan';
        }
    }
    
    if (empty($password)) {
        $errors[] = 'Password tidak boleh kosong';
    } elseif (strlen($password) < 6) {
        $errors[] = 'Password minimal 6 karakter';
    }
    
    if ($password !== $confirm_password) {
        $errors[] = 'Konfirmasi password tidak sesuai';
    }
    
    if (empty($nama_lengkap)) {
        $errors[] = 'Nama lengkap tidak boleh kosong';
    }
    
    if (empty($email)) {
        $errors[] = 'Email tidak boleh kosong';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Format email tidak valid';
    } else {
        // Cek apakah email sudah ada
        $db->query("SELECT id FROM users WHERE email = :email");
        $db->bind(':email', $email);
        if ($db->single()) {
            $errors[] = 'Email sudah digunakan';
        }
    }
    
    // Jika tidak ada error, simpan data ke database
    if (empty($errors)) {
        // Hash password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        // Insert data user baru
        $db->query("INSERT INTO users (username, password, nama_lengkap, email, no_telp, alamat, role) 
                   VALUES (:username, :password, :nama_lengkap, :email, :no_telp, :alamat, :role)");
        $db->bind(':username', $username);
        $db->bind(':password', $hashed_password);
        $db->bind(':nama_lengkap', $nama_lengkap);
        $db->bind(':email', $email);
        $db->bind(':no_telp', $no_telp);
        $db->bind(':alamat', $alamat);
        $db->bind(':role', $role);
        
        if ($db->execute()) {
            $user_id = $db->lastInsertId();
            
            // Log aktivitas
            logActivity('Menambah user baru', 'user', $user_id, "Admin menambahkan user baru: $username ($nama_lengkap) dengan role $role");
            
            setFlash('user', 'User berhasil ditambahkan', 'success');
            header('Location: ' . SITE_URL . '/admin/users/index.php');
            exit;
        } else {
            $errors[] = 'Gagal menambahkan user';
        }
    }
}

// Include header admin
require_once '../../includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar Admin -->
        <?php require_once '../../includes/sidebar-admin.php'; ?>
        
        <!-- Content Area -->
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                <h1 class="h2">Tambah User</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/admin/users/index.php" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Kembali
                    </a>
                </div>
            </div>

            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                            <li><?= $error ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <!-- Form Tambah User -->
            <div class="card">
                <div class="card-body">
                    <form action="" method="post">
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="username" class="form-label">Username</label>
                                <input type="text" class="form-control" id="username" name="username" value="<?= $_POST['username'] ?? '' ?>" required>
                                <div class="form-text">Username harus unik dan akan digunakan untuk login.</div>
                            </div>
                            <div class="col-md-6">
                                <label for="role" class="form-label">Role</label>
                                <select class="form-select" id="role" name="role" required>
                                    <option value="donatur" <?= isset($_POST['role']) && $_POST['role'] == 'donatur' ? 'selected' : '' ?>>Donatur</option>
                                    <option value="admin" <?= isset($_POST['role']) && $_POST['role'] == 'admin' ? 'selected' : '' ?>>Admin</option>
                                    <option value="ketua" <?= isset($_POST['role']) && $_POST['role'] == 'ketua' ? 'selected' : '' ?>>Ketua Yayasan</option>
                                    <option value="bendahara" <?= isset($_POST['role']) && $_POST['role'] == 'bendahara' ? 'selected' : '' ?>>Bendahara</option>
                                    <option value="sekretaris" <?= isset($_POST['role']) && $_POST['role'] == 'sekretaris' ? 'selected' : '' ?>>Sekretaris</option>
                                    <option value="pengawas" <?= isset($_POST['role']) && $_POST['role'] == 'pengawas' ? 'selected' : '' ?>>Pengawas</option>
                                </select>
                                <div class="form-text">Pilih role user sesuai dengan fungsinya dalam sistem.</div>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="password" class="form-label">Password</label>
                                <input type="password" class="form-control" id="password" name="password" required>
                                <div class="form-text">Password minimal 6 karakter.</div>
                            </div>
                            <div class="col-md-6">
                                <label for="confirm_password" class="form-label">Konfirmasi Password</label>
                                <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                <div class="form-text">Masukkan kembali password untuk konfirmasi.</div>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="nama_lengkap" class="form-label">Nama Lengkap</label>
                                <input type="text" class="form-control" id="nama_lengkap" name="nama_lengkap" value="<?= $_POST['nama_lengkap'] ?? '' ?>" required>
                            </div>
                            <div class="col-md-6">
                                <label for="email" class="form-label">Email</label>
                                <input type="email" class="form-control" id="email" name="email" value="<?= $_POST['email'] ?? '' ?>" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="no_telp" class="form-label">Nomor Telepon</label>
                                <input type="text" class="form-control" id="no_telp" name="no_telp" value="<?= $_POST['no_telp'] ?? '' ?>">
                            </div>
                            <div class="col-md-6">
                                <label for="alamat" class="form-label">Alamat</label>
                                <textarea class="form-control" id="alamat" name="alamat" rows="3"><?= $_POST['alamat'] ?? '' ?></textarea>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-save me-1"></i> Simpan
                                </button>
                                <a href="<?= SITE_URL ?>/admin/users/index.php" class="btn btn-secondary">
                                    <i class="fas fa-times me-1"></i> Batal
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
</div>

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