<?php
session_start();
require_once '../../config/database.php';
require_once '../../config/function.php';

// Cek login
checkLogin();

$current_user = getCurrentUser();

// Hanya admin yang bisa mengakses halaman users
if ($current_user['role'] != 'admin') {
    $_SESSION['alert'] = [
        'type' => 'error',
        'title' => 'Akses Ditolak!',
        'message' => 'Anda tidak memiliki izin untuk mengakses halaman ini.'
    ];
    header('Location: ../dashboard.php');
    exit;
}

// Ambil ID dari URL
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Ambil data user
$query = "SELECT * FROM bkcare_users WHERE id_user = $id";
$result = mysqli_query($conn, $query);
$data = mysqli_fetch_assoc($result);

if (!$data) {
    $_SESSION['alert'] = [
        'type' => 'error',
        'title' => 'Error!',
        'message' => 'Data pengguna tidak ditemukan'
    ];
    header('Location: index.php');
    exit;
}

// Proses update data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $nama = mysqli_real_escape_string($conn, $_POST['nama']);
    $username = mysqli_real_escape_string($conn, $_POST['username']);
    $password = $_POST['password'];
    $password_confirm = $_POST['password_confirm'];
    $role = mysqli_real_escape_string($conn, $_POST['role']);
    $is_active = isset($_POST['is_active']) ? '1' : '0';
    
    // Validasi
    $errors = [];
    
    if (empty($nama)) {
        $errors[] = 'Nama harus diisi';
    }
    
    if (empty($username)) {
        $errors[] = 'Username harus diisi';
    } elseif (strlen($username) < 3) {
        $errors[] = 'Username minimal 3 karakter';
    } elseif (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
        $errors[] = 'Username hanya boleh mengandung huruf, angka, dan underscore';
    }
    
    // Validasi password jika diisi
    if (!empty($password)) {
        if (strlen($password) < 6) {
            $errors[] = 'Password minimal 6 karakter';
        }
        
        if ($password != $password_confirm) {
            $errors[] = 'Konfirmasi password tidak sesuai';
        }
    }
    
    if (empty($role)) {
        $errors[] = 'Role harus dipilih';
    }
    
    // Cek duplikat username kecuali data sendiri
    $check = mysqli_query($conn, "SELECT * FROM bkcare_users WHERE username = '$username' AND id_user != $id");
    if (mysqli_num_rows($check) > 0) {
        $errors[] = 'Username sudah digunakan';
    }
    
    // Jika tidak ada error
    if (empty($errors)) {
        // Jika password diisi, update password juga
        if (!empty($password)) {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $query = "UPDATE bkcare_users 
                      SET nama = '$nama', 
                          username = '$username', 
                          password = '$hashed_password',
                          role = '$role', 
                          is_active = '$is_active' 
                      WHERE id_user = $id";
        } else {
            $query = "UPDATE bkcare_users 
                      SET nama = '$nama', 
                          username = '$username', 
                          role = '$role', 
                          is_active = '$is_active' 
                      WHERE id_user = $id";
        }
        
        if (mysqli_query($conn, $query)) {
            // Set alert sukses
            $_SESSION['alert'] = [
                'type' => 'success',
                'title' => 'Berhasil!',
                'message' => 'Data pengguna <strong>' . $nama . '</strong> berhasil diperbarui.'
            ];
            
            // Redirect ke index.php
            header('Location: index.php');
            exit;
        } else {
            $_SESSION['alert'] = [
                'type' => 'error',
                'title' => 'Gagal!',
                'message' => 'Gagal memperbarui data: ' . mysqli_error($conn)
            ];
            header('Location: edit.php?id=' . $id);
            exit;
        }
    } else {
        $_SESSION['alert'] = [
            'type' => 'warning',
            'title' => 'Validasi Gagal!',
            'message' => implode('<br>', $errors)
        ];
        header('Location: edit.php?id=' . $id);
        exit;
    }
}

include '../../includes/header.php';
include '../../includes/navbar.php';
?>

<!-- Main Content -->
<main class="container mx-auto px-4 py-6">
    <div class="max-w-2xl mx-auto">
        <!-- Header -->
        <div class="flex items-center mb-6">
            <a href="index.php" class="text-gray-600 hover:text-purple-600 transition mr-4">
                <i class="fas fa-arrow-left text-xl"></i>
            </a>
            <div>
                <h1 class="text-2xl font-bold text-gray-800 flex items-center">
                    <i class="fas fa-edit text-purple-600 mr-3"></i>
                    Edit Pengguna
                </h1>
                <p class="text-gray-600 text-sm mt-1">Edit data pengguna: <span class="font-semibold"><?= htmlspecialchars($data['nama']) ?></span></p>
            </div>
        </div>

        <!-- Alert Notification -->
        <?php if (isset($_SESSION['alert'])): ?>
        <div id="alert-notification" class="mb-6 rounded-lg p-4 <?= 
            $_SESSION['alert']['type'] == 'success' ? 'bg-green-50 border-l-4 border-green-500' : 
            ($_SESSION['alert']['type'] == 'error' ? 'bg-red-50 border-l-4 border-red-500' : 
            'bg-yellow-50 border-l-4 border-yellow-500') ?> shadow-md">
            <div class="flex items-start">
                <div class="flex-shrink-0">
                    <?php if ($_SESSION['alert']['type'] == 'success'): ?>
                        <i class="fas fa-check-circle text-green-500 text-xl"></i>
                    <?php elseif ($_SESSION['alert']['type'] == 'error'): ?>
                        <i class="fas fa-exclamation-circle text-red-500 text-xl"></i>
                    <?php else: ?>
                        <i class="fas fa-exclamation-triangle text-yellow-500 text-xl"></i>
                    <?php endif; ?>
                </div>
                <div class="ml-3 flex-1">
                    <h3 class="text-sm font-medium <?= 
                        $_SESSION['alert']['type'] == 'success' ? 'text-green-800' : 
                        ($_SESSION['alert']['type'] == 'error' ? 'text-red-800' : 
                        'text-yellow-800') ?>">
                        <?= $_SESSION['alert']['title'] ?>
                    </h3>
                    <div class="mt-1 text-sm <?= 
                        $_SESSION['alert']['type'] == 'success' ? 'text-green-700' : 
                        ($_SESSION['alert']['type'] == 'error' ? 'text-red-700' : 
                        'text-yellow-700') ?>">
                        <?= $_SESSION['alert']['message'] ?>
                    </div>
                </div>
                <div class="ml-auto pl-3">
                    <button onclick="this.parentElement.parentElement.parentElement.remove()" class="inline-flex <?= 
                        $_SESSION['alert']['type'] == 'success' ? 'text-green-500 hover:text-green-600' : 
                        ($_SESSION['alert']['type'] == 'error' ? 'text-red-500 hover:text-red-600' : 
                        'text-yellow-500 hover:text-yellow-600') ?>">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
        <?php 
        unset($_SESSION['alert']);
        endif; 
        ?>

        <!-- Info Role -->
        <div class="bg-blue-50 border-l-4 border-blue-500 p-4 mb-6 rounded-lg">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-info-circle text-blue-500"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-blue-700">
                        <span class="font-medium">Role saat ini:</span>
                        <?php
                        $role_display = '';
                        switch($data['role']) {
                            case 'admin': $role_display = 'Admin'; break;
                            case 'guru_bk': $role_display = 'Guru BK'; break;
                            case 'wali_kelas': $role_display = 'Wali Kelas'; break;
                            case 'kepala_sekolah': $role_display = 'Kepala Sekolah'; break;
                            case 'guru': $role_display = 'Guru'; break;
                            case 'siswa': $role_display = 'Siswa'; break;
                            default: $role_display = ucfirst($data['role']);
                        }
                        ?>
                        <strong><?= $role_display ?></strong>
                    </p>
                </div>
            </div>
        </div>

        <!-- Form -->
        <div class="card-stat p-8">
            <form action="" method="POST" id="editForm">
                <!-- Nama -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-user text-purple-600 mr-2"></i>
                        Nama Lengkap <span class="text-red-500">*</span>
                    </label>
                    <input type="text" 
                           name="nama" 
                           class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50"
                           placeholder="Masukkan nama lengkap"
                           value="<?= htmlspecialchars($data['nama']) ?>"
                           required>
                </div>

                <!-- Username -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-at text-purple-600 mr-2"></i>
                        Username <span class="text-red-500">*</span>
                    </label>
                    <input type="text" 
                           name="username" 
                           class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50"
                           placeholder="Masukkan username (min. 3 karakter)"
                           value="<?= htmlspecialchars($data['username']) ?>"
                           required>
                    <p class="text-xs text-gray-500 mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        Username hanya boleh mengandung huruf, angka, dan underscore (_)
                    </p>
                </div>

                <!-- Password (opsional) -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-lock text-purple-600 mr-2"></i>
                        Password Baru <span class="text-gray-500 text-xs">(opsional)</span>
                    </label>
                    <input type="password" 
                           name="password" 
                           class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50"
                           placeholder="Kosongkan jika tidak ingin mengubah password">
                    <p class="text-xs text-gray-500 mt-2">
                        <i class="fas fa-info-circle mr-1"></i>
                        Minimal 6 karakter. Kosongkan jika tidak ingin mengubah password.
                    </p>
                </div>

                <!-- Konfirmasi Password -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-lock text-purple-600 mr-2"></i>
                        Konfirmasi Password Baru
                    </label>
                    <input type="password" 
                           name="password_confirm" 
                           class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50"
                           placeholder="Konfirmasi password baru">
                </div>

                <!-- Role -->
                <div class="mb-6">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        <i class="fas fa-user-tag text-purple-600 mr-2"></i>
                        Role <span class="text-red-500">*</span>
                    </label>
                    <select name="role" class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-600 focus:border-transparent outline-none transition bg-gray-50" required>
                        <option value="">-- Pilih Role --</option>
                        <option value="admin" <?= $data['role'] == 'admin' ? 'selected' : '' ?>>Admin</option>
                        <option value="guru_bk" <?= $data['role'] == 'guru_bk' ? 'selected' : '' ?>>Guru BK</option>
                        <option value="wali_kelas" <?= $data['role'] == 'wali_kelas' ? 'selected' : '' ?>>Wali Kelas</option>
                        <option value="kepala_sekolah" <?= $data['role'] == 'kepala_sekolah' ? 'selected' : '' ?>>Kepala Sekolah</option>
                        <option value="guru" <?= $data['role'] == 'guru' ? 'selected' : '' ?>>Guru</option>
                        <option value="siswa" <?= $data['role'] == 'siswa' ? 'selected' : '' ?>>Siswa</option>
                    </select>
                </div>

                <!-- Status Aktif -->
                <div class="mb-8">
                    <label class="flex items-center p-4 bg-purple-50 rounded-xl cursor-pointer">
                        <input type="checkbox" 
                               name="is_active" 
                               class="w-5 h-5 text-purple-600 border-gray-300 rounded focus:ring-purple-500 mr-3"
                               <?= $data['is_active'] == '1' ? 'checked' : '' ?>>
                        <div>
                            <span class="text-sm font-medium text-gray-700">Aktif</span>
                            <p class="text-xs text-gray-500 mt-1">
                                <i class="fas fa-info-circle mr-1"></i>
                                Jika tidak dicentang, user tidak dapat login
                            </p>
                        </div>
                    </label>
                </div>

                <!-- Tombol -->
                <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200">
                    <a href="index.php" class="btn-outline-primary text-sm px-6 py-3">
                        <i class="fas fa-times mr-2"></i>Batal
                    </a>
                    <button type="submit" class="btn-primary text-sm px-6 py-3">
                        <i class="fas fa-save mr-2"></i>Update Data
                    </button>
                </div>
            </form>
        </div>
    </div>
</main>

<script>
$(document).ready(function() {
    // Auto hide alert after 5 seconds
    if ($('#alert-notification').length) {
        setTimeout(function() {
            $('#alert-notification').fadeOut('slow');
        }, 5000);
    }

    // Validasi form
    $('#editForm').on('submit', function(e) {
        let nama = $('input[name="nama"]').val();
        let username = $('input[name="username"]').val();
        let password = $('input[name="password"]').val();
        let passwordConfirm = $('input[name="password_confirm"]').val();
        let role = $('select[name="role"]').val();
        let errors = [];
        
        // Reset border
        $('input, select').removeClass('border-red-500');
        
        if (!nama.trim()) {
            errors.push('Nama harus diisi');
            $('input[name="nama"]').addClass('border-red-500');
        }
        
        if (!username.trim()) {
            errors.push('Username harus diisi');
            $('input[name="username"]').addClass('border-red-500');
        } else if (username.length < 3) {
            errors.push('Username minimal 3 karakter');
            $('input[name="username"]').addClass('border-red-500');
        } else if (!/^[a-zA-Z0-9_]+$/.test(username)) {
            errors.push('Username hanya boleh huruf, angka, dan underscore');
            $('input[name="username"]').addClass('border-red-500');
        }
        
        // Validasi password jika diisi
        if (password) {
            if (password.length < 6) {
                errors.push('Password minimal 6 karakter');
                $('input[name="password"]').addClass('border-red-500');
            }
            
            if (password !== passwordConfirm) {
                errors.push('Konfirmasi password tidak sesuai');
                $('input[name="password_confirm"]').addClass('border-red-500');
            }
        }
        
        if (!role) {
            errors.push('Role harus dipilih');
            $('select[name="role"]').addClass('border-red-500');
        }
        
        if (errors.length > 0) {
            e.preventDefault();
            alert('Validasi Gagal:\n- ' + errors.join('\n- '));
        }
    });

    // Remove red border on input
    $('input, select').on('input change', function() {
        $(this).removeClass('border-red-500');
    });
});
</script>

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