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

// Proses tambah 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';
    }
    
    if (empty($password)) {
        $errors[] = 'Password harus diisi';
    } elseif (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
    $check = mysqli_query($conn, "SELECT * FROM bkcare_users WHERE username = '$username'");
    if (mysqli_num_rows($check) > 0) {
        $errors[] = 'Username sudah digunakan';
    }
    
    // Jika tidak ada error
    if (empty($errors)) {
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
        $query = "INSERT INTO bkcare_users (nama, username, password, role, is_active) 
                  VALUES ('$nama', '$username', '$hashed_password', '$role', '$is_active')";
        
        if (mysqli_query($conn, $query)) {
            // Set alert sukses
            $_SESSION['alert'] = [
                'type' => 'success',
                'title' => 'Berhasil!',
                'message' => 'Data pengguna <strong>' . $nama . '</strong> berhasil ditambahkan.'
            ];
            
            // Redirect ke index.php
            header('Location: index.php');
            exit;
        } else {
            $_SESSION['alert'] = [
                'type' => 'error',
                'title' => 'Gagal!',
                'message' => 'Gagal menambahkan data: ' . mysqli_error($conn)
            ];
            header('Location: tambah.php');
            exit;
        }
    } else {
        $_SESSION['alert'] = [
            'type' => 'warning',
            'title' => 'Validasi Gagal!',
            'message' => implode('<br>', $errors)
        ];
        header('Location: tambah.php');
        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-user-plus text-purple-600 mr-3"></i>
                    Tambah Pengguna
                </h1>
                <p class="text-gray-600 text-sm mt-1">Tambahkan data pengguna baru</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; 
        ?>

        <!-- Form -->
        <div class="card-stat p-8">
            <form action="" method="POST" id="tambahForm">
                <!-- 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="<?= isset($_POST['nama']) ? htmlspecialchars($_POST['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="<?= isset($_POST['username']) ? htmlspecialchars($_POST['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 -->
                <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 <span class="text-red-500">*</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="Masukkan password (min. 6 karakter)"
                           required>
                </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 <span class="text-red-500">*</span>
                    </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="Masukkan ulang password"
                           required>
                </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" <?= (isset($_POST['role']) && $_POST['role'] == 'admin') ? 'selected' : '' ?>>Admin</option>
                        <option value="guru_bk" <?= (isset($_POST['role']) && $_POST['role'] == 'guru_bk') ? 'selected' : '' ?>>Guru BK</option>
                        <option value="wali_kelas" <?= (isset($_POST['role']) && $_POST['role'] == 'wali_kelas') ? 'selected' : '' ?>>Wali Kelas</option>
                        <option value="kepala_sekolah" <?= (isset($_POST['role']) && $_POST['role'] == 'kepala_sekolah') ? 'selected' : '' ?>>Kepala Sekolah</option>
                        <option value="guru" <?= (isset($_POST['role']) && $_POST['role'] == 'guru') ? 'selected' : '' ?>>Guru</option>
                        <option value="siswa" <?= (isset($_POST['role']) && $_POST['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"
                               <?= !isset($_POST['is_active']) || $_POST['is_active'] == 'on' ? '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>Simpan 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
    $('#tambahForm').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');
        }
        
        if (!password) {
            errors.push('Password harus diisi');
            $('input[name="password"]').addClass('border-red-500');
        } else 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'; ?>