<?php
// ketua/staff/tambah.php
$pageTitle = 'Tambah Staff Baru';
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 ketua
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 'ketua') {
    // Redirect ke halaman login jika belum login atau bukan ketua
    setFlash('login_required', 'Anda harus login sebagai ketua yayasan untuk mengakses halaman ini', 'danger');
    header('Location: ' . SITE_URL . '/auth/login.php');
    exit;
}

// Koneksi database
$db = dbConnect();

// Proses form jika ada submit
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'] ?? '');
    
    // Validasi data
    $errors = [];
    
    // Validasi username
    if (empty($username)) {
        $errors[] = 'Username harus diisi';
    } else {
        // Cek apakah username sudah ada
        $db->query("SELECT * FROM users WHERE username = :username");
        $db->bind(':username', $username);
        if ($db->single()) {
            $errors[] = 'Username sudah digunakan';
        }
    }
    
    // Validasi password
    if (empty($password)) {
        $errors[] = 'Password harus diisi';
    } elseif (strlen($password) < 6) {
        $errors[] = 'Password minimal 6 karakter';
    } elseif ($password !== $confirm_password) {
        $errors[] = 'Konfirmasi password tidak sesuai';
    }
    
    // Validasi nama lengkap
    if (empty($nama_lengkap)) {
        $errors[] = 'Nama lengkap harus diisi';
    }
    
    // Validasi email
    if (empty($email)) {
        $errors[] = 'Email harus diisi';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Format email tidak valid';
    } else {
        // Cek apakah email sudah ada
        $db->query("SELECT * FROM users WHERE email = :email");
        $db->bind(':email', $email);
        if ($db->single()) {
            $errors[] = 'Email sudah digunakan';
        }
    }
    
    // Validasi role
    $allowed_roles = ['admin', 'bendahara', 'sekretaris', 'pengawas', 'ketua'];
    if (empty($role) || !in_array($role, $allowed_roles)) {
        $errors[] = 'Role tidak valid';
    }
    
    // Jika tidak ada error, proses registrasi
    if (empty($errors)) {
        // Hash password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        // Insert 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()) {
            $new_user_id = $db->lastInsertId();
            
            // Log aktivitas
            logActivity('Menambahkan staff baru', 'user', $new_user_id, 'Ketua menambahkan staff baru dengan username: ' . $username . ', role: ' . $role);
            
            setFlash('staff', 'Staff baru berhasil ditambahkan', 'success');
            header('Location: ' . SITE_URL . '/ketua/staff/index.php');
            exit;
        } else {
            setFlash('staff', 'Staff gagal ditambahkan', 'danger');
        }
    } else {
        // Tampilkan error
        $error_message = '<ul class="mb-0">';
        foreach ($errors as $error) {
            $error_message .= '<li>' . $error . '</li>';
        }
        $error_message .= '</ul>';
        
        setFlash('staff', $error_message, 'danger');
    }
}

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

<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
            <div class="position-sticky pt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/dashboard.php">
                            <i class="fas fa-tachometer-alt me-2"></i>
                            Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/kampanye/index.php">
                            <i class="fas fa-hand-holding-heart me-2"></i>
                            Persetujuan Kampanye
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/laporan/index.php">
                            <i class="fas fa-chart-line me-2"></i>
                            Laporan Keuangan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/kegiatan/index.php">
                            <i class="fas fa-newspaper me-2"></i>
                            Kegiatan Yayasan
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="<?= SITE_URL ?>/ketua/staff/index.php">
                            <i class="fas fa-users-cog me-2"></i>
                            Manajemen Staff
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/ketua/profil/index.php">
                            <i class="fas fa-user-circle me-2"></i>
                            Profil Saya
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>/auth/logout.php">
                            <i class="fas fa-sign-out-alt me-2"></i>
                            Logout
                        </a>
                    </li>
                </ul>
                
                <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
                    <span>Pintasan</span>
                </h6>
                <ul class="nav flex-column mb-2">
                    <li class="nav-item">
                        <a class="nav-link" href="<?= SITE_URL ?>" target="_blank">
                            <i class="fas fa-external-link-alt me-2"></i>
                            Lihat Website
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- 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 Staff Baru</h1>
                <div class="btn-toolbar mb-2 mb-md-0">
                    <a href="<?= SITE_URL ?>/ketua/staff/index.php" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Kembali
                    </a>
                </div>
            </div>

            <?php flash(); ?>

            <!-- Form Tambah Staff -->
            <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 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="username" name="username" value="<?= $_POST['username'] ?? '' ?>" required>
                                <div class="form-text">Username akan digunakan untuk login.</div>
                            </div>
                            <div class="col-md-6">
                                <label for="role" class="form-label">Role <span class="text-danger">*</span></label>
                                <select class="form-select" id="role" name="role" required>
                                    <option value="">Pilih Role</option>
                                    <option value="admin" <?= (isset($_POST['role']) && $_POST['role'] == 'admin') ? 'selected' : '' ?>>Admin</option>
                                    <option value="ketua" <?= (isset($_POST['role']) && $_POST['role'] == 'ketua') ? 'selected' : '' ?>>Ketua</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>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="password" class="form-label">Password <span class="text-danger">*</span></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 <span class="text-danger">*</span></label>
                                <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                            </div>
                        </div>
                        
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label for="nama_lengkap" class="form-label">Nama Lengkap <span class="text-danger">*</span></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 <span class="text-danger">*</span></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">No. 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="mb-3">
                            <small class="text-muted">
                                <span class="text-danger">*</span> Field wajib diisi
                            </small>
                        </div>
                        
                        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                            <a href="<?= SITE_URL ?>/ketua/staff/index.php" class="btn btn-secondary me-md-2">Batal</a>
                            <button type="submit" class="btn btn-primary">Simpan</button>
                        </div>
                    </form>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
// Validasi form
document.addEventListener('DOMContentLoaded', function() {
    const form = document.querySelector('form');
    
    form.addEventListener('submit', function(event) {
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirm_password').value;
        
        if (password !== confirmPassword) {
            event.preventDefault();
            alert('Konfirmasi password tidak sesuai dengan password.');
        }
    });
});
</script>

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