<?php
// ==================== AMBIL DATA USER ====================
$user_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$user_data = null;
$anggota_data = null;

if ($user_id > 0) {
    // Ambil data user
    $query = mysql_query("SELECT * FROM user WHERE id = '$user_id' AND idweb = '$idweb'");
    if (mysql_num_rows($query) > 0) {
        $user_data = mysql_fetch_assoc($query);
        
        // Jika role member, ambil data anggota
        if ($user_data['role'] == 'member') {
            $anggota_query = mysql_query("SELECT * FROM anggota WHERE id_user = '$user_id'");
            if (mysql_num_rows($anggota_query) > 0) {
                $anggota_data = mysql_fetch_assoc($anggota_query);
            }
        }
    } else {
        $_SESSION['error_message'] = "Pengguna tidak ditemukan!";
        header("Location: users-manage");
        exit();
    }
}

// ==================== PROSES UPDATE PENGGUNA ====================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_user'])) {
    $id = (int)$_POST['id'];
    $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($role)) $errors[] = "Role wajib dipilih";
    
    // Cek username unik (kecuali untuk user ini)
    $check_query = mysql_query("SELECT id FROM user WHERE username = '$username' AND idweb = '$idweb' AND id != '$id'");
    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' AND id != '$id'");
        if (mysql_num_rows($check_email) > 0) {
            $errors[] = "Email sudah terdaftar";
        }
    }
    
    // Jika password diisi, validasi
    if (!empty($password)) {
        if ($password !== $password_confirm) {
            $errors[] = "Konfirmasi password tidak cocok";
        }
    }
    
    if (empty($errors)) {
        // Update data user
        $update_query = "UPDATE user SET
            username = '$username',
            nama = '$nama',
            institusi = '$institusi',
            telpon = '$telpon',
            email = '$email',
            role = '$role',
            status = '$status',
            updated = NOW()";
        
        // Update password jika diisi
        if (!empty($password)) {
            $password_hash = sha1($password);
            $update_query .= ", password = '$password_hash'";
        }
        
        $update_query .= " WHERE id = '$id' AND idweb = '$idweb'";
        
        if (mysql_query($update_query)) {
            
            // PROSES SINKRONISASI DENGAN TABEL ANGGOTA
            $role_before = $user_data['role']; // role sebelum diupdate
            $status_before = $user_data['status']; // status sebelum diupdate
            
            // 1. Jika role berubah dari admin ke member
            if ($role_before != 'member' && $role == 'member') {
                // Cek apakah sudah ada data anggota
                $check_anggota = mysql_query("SELECT id FROM anggota WHERE id_user = '$id'");
                
                if (mysql_num_rows($check_anggota) == 0) {
                    // Buat data anggota baru
                    $no_anggota = "P-" . str_pad($id, 4, '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_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 = '$id',
                        alamat = '',
                        kabkota = '',
                        provinsi = '',
                        aktif = '$aktif',
                        foto = '',
                        updated = NOW()";
                    
                    mysql_query($insert_anggota);
                }
            }
            // 2. Jika role tetap member, update status aktif
            elseif ($role_before == 'member' && $role == 'member') {
                $aktif = ($status == 1) ? 'Y' : 'N';
                mysql_query("UPDATE anggota SET aktif = '$aktif', updated = NOW() WHERE id_user = '$id'");
            }
            
            // Reload data user setelah update
            $query = mysql_query("SELECT * FROM user WHERE id = '$id' AND idweb = '$idweb'");
            $user_data = mysql_fetch_assoc($query);
            
            // Reload data anggota jika role member
            if ($user_data['role'] == 'member') {
                $anggota_query = mysql_query("SELECT * FROM anggota WHERE id_user = '$id'");
                if (mysql_num_rows($anggota_query) > 0) {
                    $anggota_data = mysql_fetch_assoc($anggota_query);
                }
            } else {
                $anggota_data = null;
            }
            
            $_SESSION['success_message'] = "Data pengguna berhasil diperbarui!";
            // TIDAK REDIRECT, tetap di halaman ini
        } else {
            $_SESSION['error_message'] = "Gagal mengupdate 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;
    }
    
    .info-badge {
        display: inline-block;
        padding: 4px 12px;
        background-color: #e3f2fd;
        color: #1565c0;
        border-radius: 20px;
        font-size: 0.85rem;
        margin-left: 10px;
    }
    
    /* Styling untuk tombol update */
    .btn-update {
        min-width: 160px;
        padding: 10px 24px;
        font-weight: 500;
    }
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h4 class="fw-bold mb-1">Edit Pengguna</h4>
        <p class="text-muted mb-0">Ubah data pengguna 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['success_message'])): ?>
<div class="alert alert-success alert-dismissible fade show mb-4" role="alert">
    <i data-lucide="check-circle" class="me-2"></i>
    <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<?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; ?>

<?php if ($user_data): ?>
<form method="POST" action="">
    <input type="hidden" name="id" value="<?php echo $user_data['id']; ?>">
    
    <!-- INFORMASI DASAR -->
    <div class="form-section">
        <h6>Informasi Dasar 
            <?php if ($user_data['role'] == 'member' && $anggota_data): ?>
            <span class="info-badge">
                <i data-lucide="user-check" width="14"></i>
                No. Anggota: <?php echo htmlspecialchars($anggota_data['no_anggota']); ?>
            </span>
            <?php endif; ?>
        </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 htmlspecialchars($user_data['username']); ?>" required>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Role *</label>
                <select class="form-select" name="role" required>
                    <option value="member" <?php echo $user_data['role'] == 'member' ? 'selected' : ''; ?>>Member</option>
                    <option value="admin" <?php echo $user_data['role'] == 'admin' ? 'selected' : ''; ?>>Admin</option>
                </select>
                <?php if ($user_data['role'] == 'member' && $anggota_data): ?>
                <small class="text-muted">
                    <i data-lucide="calendar" width="12"></i>
                    Terdaftar sejak: <?php echo date('d/m/Y', strtotime($anggota_data['tgl_daftar'])); ?>
                </small>
                <?php endif; ?>
            </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 htmlspecialchars($user_data['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 htmlspecialchars($user_data['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 $user_data['status'] == 1 ? 'selected' : ''; ?>>Aktif</option>
                    <option value="0" <?php echo $user_data['status'] == 0 ? '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 htmlspecialchars($user_data['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 htmlspecialchars($user_data['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 Baru</label>
                <div class="password-input-group">
                    <input type="password" class="form-control" name="password" id="password">
                    <button type="button" class="password-toggle" onclick="togglePassword('password')">
                        <i data-lucide="eye" width="16"></i>
                    </button>
                </div>
                <small class="text-muted">Kosongkan jika tidak ingin mengubah password</small>
            </div>
            <div class="col-md-6">
                <label class="form-label fw-medium">Konfirmasi Password Baru</label>
                <div class="password-input-group">
                    <input type="password" class="form-control" name="password_confirm" id="password_confirm">
                    <button type="button" class="password-toggle" onclick="togglePassword('password_confirm')">
                        <i data-lucide="eye" width="16"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- INFORMASI ANGGOTA (jika role member) -->
    <?php if ($user_data['role'] == 'member' && $anggota_data): ?>
    <div class="form-section">
        <h6>Informasi Keanggotaan</h6>
        <div class="row g-3">
            <div class="col-md-4">
                <label class="form-label fw-medium">No. Anggota</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($anggota_data['no_anggota']); ?>" readonly>
            </div>
            <div class="col-md-4">
                <label class="form-label fw-medium">Tanggal Daftar</label>
                <input type="text" class="form-control" value="<?php echo date('d/m/Y', strtotime($anggota_data['tgl_daftar'])); ?>" readonly>
            </div>
            <div class="col-md-4">
                <label class="form-label fw-medium">Tanggal Expired</label>
                <input type="text" class="form-control" value="<?php echo date('d/m/Y', strtotime($anggota_data['tgl_expired'])); ?>" readonly>
            </div>
            <div class="col-12">
                <a href="?menu=anggota-edit&id=<?php echo $anggota_data['id']; ?>" class="btn btn-sm btn-outline-info">
                    <i data-lucide="external-link" width="14"></i>
                    Kelola Data Anggota Lengkap
                </a>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- TOMBOL AKSI -->
    <div class="d-flex justify-content-between mt-4">
        <div>
            <a href="users-manage/" class="btn btn-outline-secondary">
                <i data-lucide="x" width="16"></i>
                Batal
            </a>
            <?php if ($user_data['id'] != 1): ?>
            <a href="users-manage?delete=<?php echo $user_data['id']; ?>" 
               class="btn btn-outline-danger" onclick="return confirm('Hapus pengguna ini?')">
                <i data-lucide="trash-2" width="16"></i>
                Hapus
            </a>
            <?php endif; ?>
        </div>
        <button type="submit" name="update_user" class="btn btn-primary btn-update">
            <i data-lucide="save" width="18"></i>
            Update Pengguna
        </button>
    </div>
</form>
<?php else: ?>
<div class="alert alert-danger">
    <i data-lucide="alert-circle" class="me-2"></i>
    Data pengguna tidak ditemukan!
</div>
<?php endif; ?>

<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();
}

// Auto-hide alert setelah 5 detik
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(() => {
        const alerts = document.querySelectorAll('.alert');
        alerts.forEach(alert => {
            const bsAlert = new bootstrap.Alert(alert);
            bsAlert.close();
        });
    }, 5000);
});
</script>