<?php
// ==================== PROSES SIMPAN PENGGUNA BARU ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_user'])) {
    // Ambil semua data dari form
    $username = mysql_real_escape_string($_POST['username']);
    $nama = mysql_real_escape_string($_POST['nama']);
    $institusi = mysql_real_escape_string($_POST['institusi']);
    $telpon = mysql_real_escape_string($_POST['telpon']);
    $email = mysql_real_escape_string($_POST['email']);
    $role = mysql_real_escape_string($_POST['role']);
    $status = (int)$_POST['status'];
    $password = mysql_real_escape_string($_POST['password']);
    $password_confirm = mysql_real_escape_string($_POST['password_confirm']);
    
    // Validasi
    $errors = [];
    
    if (empty($username)) $errors[] = "Username wajib diisi";
    if (empty($nama)) $errors[] = "Nama lengkap wajib diisi";
    if (empty($password)) $errors[] = "Password wajib diisi";
    if ($password !== $password_confirm) $errors[] = "Konfirmasi password tidak cocok";
    if (empty($role)) $errors[] = "Role wajib dipilih";
    
    // Cek username unik
    $check_query = mysql_query("SELECT id FROM user WHERE username = '$username' AND idweb = '$idweb'");
    if (mysql_num_rows($check_query) > 0) {
        $errors[] = "Username sudah digunakan";
    }
    
    // Cek email unik jika diisi
    if (!empty($email)) {
        $check_email = mysql_query("SELECT id FROM user WHERE email = '$email' AND idweb = '$idweb'");
        if (mysql_num_rows($check_email) > 0) {
            $errors[] = "Email sudah terdaftar";
        }
    }
    
    if (empty($errors)) {
        // Hash password dengan SHA1
        $password_hash = sha1($password);
        $new_id = date("ymdHis") . rand(1000,9999);
        // Insert ke database
        $insert_query = "INSERT INTO user SET
            id = '$new_id',
            idweb = '$idweb',
            username = '$username',
            password = '$password_hash',
            nama = '$nama',
            institusi = '$institusi',
            telpon = '$telpon',
            email = '$email',
            role = '$role',
            status = '$status',
            updated = NOW()";
        
        if (mysql_query($insert_query)) {
            
            
            // JIKA ROLE = MEMBER, BUAT DATA DI TABEL ANGGOTA
            if ($role == 'member') {
                // Generate nomor anggota (contoh: ANGG-YYYYMMDD-ID)
                $no_anggota = "P-" . str_pad($new_id, 5, '0', STR_PAD_LEFT);
                $tgl_daftar = date('Y-m-d');
                $tgl_expired = date('Y-m-d', strtotime('+1 year'));
                $tgl_last_renewal = date('Y-m-d');
                $aktif = ($status == 1) ? 'Y' : 'N';
                
                // Insert ke tabel anggota
                $insert_anggota = "INSERT INTO anggota SET
                    no_anggota = '$no_anggota',
                    tgl_daftar = '$tgl_daftar',
                    tgl_expired = '$tgl_expired',
                    tgl_last_renewal = '$tgl_last_renewal',
                    id_user = '$new_id',
                    alamat = '',
                    kabkota = '',
                    provinsi = '',
                    aktif = '$aktif',
                    foto = '',
                    updated = NOW()";
                
                if (!mysql_query($insert_anggota)) {
                    // Jika gagal insert anggota, hapus user yang baru dibuat
                    mysql_query("DELETE FROM user WHERE id = '$new_id'");
                    $_SESSION['error_message'] = "Gagal membuat data anggota: " . mysql_error();
                    echo "<script>window.location.href = 'users-add/';</script>";
                    exit();
                }
            }
            
            $_SESSION['success_message'] = "Pengguna berhasil ditambahkan!";
            echo "<script>window.location.href = 'users-edit?id=$new_id';</script>";
            exit();
        } else {
            $_SESSION['error_message'] = "Gagal menyimpan pengguna: " . mysql_error();
        }
    } else {
        $_SESSION['error_message'] = implode("<br>", $errors);
    }
}
?>
<style>
    .form-section {
        background: var(--gray-50);
        border-radius: var(--border-radius);
        padding: 1.5rem;
        margin-bottom: 1.5rem;
    }
    
    .form-section h6 {
        border-bottom: 2px solid var(--primary-color);
        padding-bottom: 0.5rem;
        margin-bottom: 1.5rem;
        color: var(--gray-700);
    }
    
    .password-input-group {
        position: relative;
    }
    
    .password-toggle {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        background: none;
        border: none;
        color: var(--gray-500);
        cursor: pointer;
    }
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="fw-bold mb-1">Tambah Pengguna Baru</h4>
        <p class="text-muted mb-0">Tambah data pengguna baru untuk sistem</p>
    </div>
    <div>
        <a href="users-manage/" class="btn btn-outline-secondary">
            <i data-lucide="arrow-left" width="16"></i>
            Kembali ke Daftar
        </a>
    </div>
</div>

<!-- ==================== NOTIFIKASI ==================== -->
<?php if (isset($_SESSION['error_message'])): ?>
<div class="alert alert-danger alert-dismissible fade show mb-4" role="alert">
    <i data-lucide="alert-circle" class="me-2"></i>
    <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<form method="POST" action="">
    <!-- INFORMASI DASAR -->
    <div class="form-section">
        <h6>Informasi Dasar</h6>
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label fw-medium">Username *</label>
                <input type="text" class="form-control" name="username" value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>" required>
                <small class="text-muted">Username untuk login</small>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Role *</label>
                <select class="form-select" name="role" required>
                    <option value="">Pilih Role</option>
                    <option value="member" <?php echo isset($_POST['role']) && $_POST['role'] == 'member' ? 'selected' : ''; ?>>Member</option>
                    <option value="admin" <?php echo isset($_POST['role']) && $_POST['role'] == 'admin' ? 'selected' : ''; ?>>Admin</option>
                </select>
            </div>
            <div class="col-12">
                <label class="form-label fw-medium">Nama Lengkap *</label>
                <input type="text" class="form-control" name="nama" value="<?php echo isset($_POST['nama']) ? htmlspecialchars($_POST['nama']) : ''; ?>" required>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Institusi/Organisasi</label>
                <input type="text" class="form-control" name="institusi" value="<?php echo isset($_POST['institusi']) ? htmlspecialchars($_POST['institusi']) : ''; ?>">
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Status</label>
                <select class="form-select" name="status" required>
                    <option value="1" <?php echo isset($_POST['status']) && $_POST['status'] == 1 ? 'selected' : ''; ?>>Aktif</option>
                    <option value="0" <?php echo (isset($_POST['status']) && $_POST['status'] == 0) || !isset($_POST['status']) ? 'selected' : ''; ?>>Non-Aktif</option>
                </select>
            </div>
        </div>
    </div>

    <!-- KONTAK -->
    <div class="form-section">
        <h6>Informasi Kontak</h6>
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label fw-medium">Email</label>
                <input type="email" class="form-control" name="email" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Telepon/WhatsApp</label>
                <input type="text" class="form-control" name="telpon" value="<?php echo isset($_POST['telpon']) ? htmlspecialchars($_POST['telpon']) : ''; ?>">
            </div>
        </div>
    </div>

    <!-- PASSWORD -->
    <div class="form-section">
        <h6>Password</h6>
        <div class="row g-3">
            <div class="col-md-6">
                <label class="form-label fw-medium">Password *</label>
                <div class="password-input-group">
                    <input type="password" class="form-control" name="password" id="password" required>
                    <button type="button" class="password-toggle" onclick="togglePassword('password')">
                        <i data-lucide="eye" width="16"></i>
                    </button>
                </div>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Konfirmasi Password *</label>
                <div class="password-input-group">
                    <input type="password" class="form-control" name="password_confirm" id="password_confirm" required>
                    <button type="button" class="password-toggle" onclick="togglePassword('password_confirm')">
                        <i data-lucide="eye" width="16"></i>
                    </button>
                </div>
            </div>
            <div class="col-12">
                <div class="alert alert-info">
                    <i data-lucide="info" class="me-2"></i>
                    Password akan di-hash menggunakan SHA1. Default password untuk contoh adalah "1234"
                </div>
            </div>
        </div>
    </div>

    <!-- TOMBOL AKSI -->
    <div class="d-flex justify-content-between mt-4">
        <a href="users-manage/" class="btn btn-outline-secondary">
            <i data-lucide="x" width="16"></i>
            Batal
        </a>
        <button type="submit" name="save_user" class="btn btn-primary btn-lg">
            <i data-lucide="save" width="18"></i>
            Simpan Pengguna
        </button>
    </div>
</form>

<script>
// Inisialisasi icons
document.addEventListener('DOMContentLoaded', function() {
    lucide.createIcons();
});

// Toggle password visibility
function togglePassword(fieldId) {
    const field = document.getElementById(fieldId);
    const toggleBtn = field.nextElementSibling.querySelector('i');
    
    if (field.type === 'password') {
        field.type = 'text';
        toggleBtn.setAttribute('data-lucide', 'eye-off');
    } else {
        field.type = 'password';
        toggleBtn.setAttribute('data-lucide', 'eye');
    }
    
    lucide.createIcons();
}
</script>