<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Redirect if not IT user - using functions from connection.php
if (!is_logged_in() || !is_user_type('it')) {
    header("Location: ../login.php");
    exit();
}

// Get IT user data
$it_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM it_users WHERE id = ?");
$stmt->bind_param("i", $it_id);
$stmt->execute();
$it_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Initialize message variables
$success_msg = '';
$error_msg = '';

// Process form submission for adding new admin
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_admin'])) {
    $username = sanitize_input($conn, $_POST['username']);
    $email = sanitize_input($conn, $_POST['email']);
    $password = $_POST['password'];
    $status = sanitize_input($conn, $_POST['status']);
    
    // Validate inputs
    if (empty($username) || empty($password) || empty($email)) {
        $error_msg = "Semua field harus diisi";
    } elseif (strlen($password) < 8) {
        $error_msg = "Password harus minimal 8 karakter";
    } else {
        // Check if username already exists
        $check_stmt = $conn->prepare("SELECT id FROM admin_users WHERE username = ?");
        $check_stmt->bind_param("s", $username);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows > 0) {
            $error_msg = "Username sudah digunakan";
        } else {
            // Hash the password
            $hashed_password = hash_password($password);
            
            // Insert new admin user
            $insert_stmt = $conn->prepare("INSERT INTO admin_users (username, password, email, status, created_at) VALUES (?, ?, ?, ?, NOW())");
            $insert_stmt->bind_param("ssss", $username, $hashed_password, $email, $status);
            
            if ($insert_stmt->execute()) {
                $success_msg = "Admin berhasil ditambahkan";
                
                // Log the action
                $details = "IT ID " . $it_id . " ({$_SESSION['username']}) added new admin user: " . $username;
                log_activity($conn, $it_id, 'it', 'Add Admin User', $details);
            } else {
                $error_msg = "Gagal menambahkan admin: " . $conn->error;
            }
            
            $insert_stmt->close();
        }
        $check_stmt->close();
    }
}

// Process form submission for editing admin
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_admin'])) {
    $admin_id = sanitize_input($conn, $_POST['admin_id']);
    $username = sanitize_input($conn, $_POST['username']);
    $email = sanitize_input($conn, $_POST['email']);
    $status = sanitize_input($conn, $_POST['status']);
    
    // Validate inputs
    if (empty($username) || empty($email)) {
        $error_msg = "Username dan email tidak boleh kosong";
    } else {
        // Check if username already exists (except for the current user)
        $check_stmt = $conn->prepare("SELECT id FROM admin_users WHERE username = ? AND id != ?");
        $check_stmt->bind_param("si", $username, $admin_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows > 0) {
            $error_msg = "Username sudah digunakan oleh admin lain";
        } else {
            // Update admin user
            $update_stmt = $conn->prepare("UPDATE admin_users SET username = ?, email = ?, status = ? WHERE id = ?");
            $update_stmt->bind_param("sssi", $username, $email, $status, $admin_id);
            
            if ($update_stmt->execute()) {
                $success_msg = "Data admin berhasil diperbarui";
                
                // Log the action
                $details = "IT ID " . $it_id . " ({$_SESSION['username']}) updated admin user ID: " . $admin_id;
                log_activity($conn, $it_id, 'it', 'Update Admin User', $details);
            } else {
                $error_msg = "Gagal memperbarui data admin: " . $conn->error;
            }
            
            $update_stmt->close();
        }
        $check_stmt->close();
    }
}

// Process form submission for deleting admin
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_admin'])) {
    $admin_id = sanitize_input($conn, $_POST['admin_id']);
    
    // Check if it's the only super admin
    $check_stmt = $conn->prepare("SELECT COUNT(*) as admin_count FROM admin_users");
    $check_stmt->execute();
    $check_result = $check_stmt->get_result()->fetch_assoc();
    $check_stmt->close();
    
    if ($check_result['admin_count'] <= 1) {
        $error_msg = "Tidak dapat menghapus admin terakhir dalam sistem";
    } else {
        // Delete admin user
        $delete_stmt = $conn->prepare("DELETE FROM admin_users WHERE id = ?");
        $delete_stmt->bind_param("i", $admin_id);
        
        if ($delete_stmt->execute()) {
            $success_msg = "Admin berhasil dihapus";
            
            // Log the action
            $details = "IT ID " . $it_id . " ({$_SESSION['username']}) deleted admin user ID: " . $admin_id;
            log_activity($conn, $it_id, 'it', 'Delete Admin User', $details);
        } else {
            $error_msg = "Gagal menghapus admin: " . $conn->error;
        }
        
        $delete_stmt->close();
    }
}

// Fetch Admin users
$admin_users = [];
$admin_stmt = $conn->prepare("SELECT id, username, email, status, created_at, last_login FROM admin_users ORDER BY username");
$admin_stmt->execute();
$admin_result = $admin_stmt->get_result();
while ($row = $admin_result->fetch_assoc()) {
    $admin_users[] = $row;
}
$admin_stmt->close();

// Set page title
$page_title = "Pengaturan Akun Admin";

// Include header
include '../template_it/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    <!-- Welcome Card -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-2xl font-bold text-gray-800 mb-4">Pengaturan Akun Admin</h2>
        <p class="text-gray-600">Halaman ini digunakan untuk mengelola akun admin sistem. Anda dapat menambah, mengedit, dan menghapus akun admin.</p>
        
        <div class="border-t border-gray-200 pt-4 mt-4">
            <h3 class="text-lg font-semibold text-gray-700 mb-3">Info Anda:</h3>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-blue-100 text-blue-500 mr-3">
                        <i class="fas fa-user text-xl"></i>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Username</p>
                        <p class="text-lg font-medium text-gray-800"><?php echo htmlspecialchars($it_data['username']); ?></p>
                    </div>
                </div>
                
                <div class="flex items-center">
                    <div class="p-3 rounded-full bg-green-100 text-green-500 mr-3">
                        <i class="fas fa-envelope text-xl"></i>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Email</p>
                        <p class="text-lg font-medium text-gray-800"><?php echo htmlspecialchars($it_data['email']); ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Notification Area -->
    <?php if (!empty($success_msg) || !empty($error_msg)): ?>
    <div id="notification" class="mb-4 p-4 rounded-lg <?php echo !empty($success_msg) ? 'bg-green-100 text-green-700 border border-green-300' : 'bg-red-100 text-red-700 border border-red-300'; ?>">
        <div class="flex items-center">
            <div class="mr-3">
                <i class="fas <?php echo !empty($success_msg) ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> text-xl"></i>
            </div>
            <div>
                <p class="font-medium"><?php echo !empty($success_msg) ? $success_msg : $error_msg; ?></p>
            </div>
        </div>
    </div>
    <?php endif; ?>
    
    <!-- Admin Management Section -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <div class="flex justify-between items-center mb-6">
            <h3 class="text-xl font-semibold text-gray-800">Daftar Akun Admin</h3>
            <button id="addAdminBtn" class="bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline transition duration-150 ease-in-out">
                <i class="fas fa-plus mr-2"></i> Tambah Admin
            </button>
        </div>
        
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Username</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Email</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Tanggal Dibuat</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Login Terakhir</th>
                        <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Aksi</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($admin_users)): ?>
                    <tr>
                        <td colspan="7" class="px-6 py-4 text-center text-sm text-gray-500">Tidak ada data admin</td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($admin_users as $user): ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo $user['id']; ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo htmlspecialchars($user['username']); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo htmlspecialchars($user['email']); ?></td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm">
                                <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $user['status'] == 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                    <?php echo ucfirst($user['status']); ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <?php echo $user['created_at'] ? date('d-m-Y H:i', strtotime($user['created_at'])) : '-'; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                <?php echo $user['last_login'] ? date('d-m-Y H:i', strtotime($user['last_login'])) : 'Belum Pernah Login'; ?>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                <button class="text-blue-600 hover:text-blue-900 focus:outline-none mr-3" 
                                        onclick="openEditModal('<?php echo $user['id']; ?>', '<?php echo htmlspecialchars($user['username']); ?>', '<?php echo htmlspecialchars($user['email']); ?>', '<?php echo $user['status']; ?>')">
                                    <i class="fas fa-edit"></i> Edit
                                </button>
                                <button class="text-red-600 hover:text-red-900 focus:outline-none" 
                                        onclick="openDeleteModal('<?php echo $user['id']; ?>', '<?php echo htmlspecialchars($user['username']); ?>')">
                                    <i class="fas fa-trash"></i> Hapus
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<!-- Add Admin Modal -->
<div id="addAdminModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-lg shadow-lg w-full max-w-md mx-4">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800">Tambah Admin Baru</h3>
        </div>
        <form id="addAdminForm" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
            <div class="p-6">
                <div class="mb-4">
                    <label for="username" class="block text-sm font-medium text-gray-700 mb-1">Username</label>
                    <input type="text" id="username" name="username" class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-20" required>
                </div>
                
                <div class="mb-4">
                    <label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                    <input type="email" id="email" name="email" class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-20" required>
                </div>
                
                <div class="mb-4">
                    <label for="password" class="block text-sm font-medium text-gray-700 mb-1">Password</label>
                    <input type="password" id="password" name="password" class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-20" required minlength="8">
                    <p class="mt-1 text-xs text-gray-500">Password minimal 8 karakter</p>
                </div>
                
                <div class="mb-4">
                    <label for="confirm_password" class="block text-sm font-medium text-gray-700 mb-1">Konfirmasi Password</label>
                    <input type="password" id="confirm_password" name="confirm_password" class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-20" required>
                </div>
                
                <div class="mb-4">
                    <label for="status" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                    <select id="status" name="status" class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-20" required>
                        <option value="active">Active</option>
                        <option value="nonactive">Nonactive</option>
                    </select>
                </div>
                
                <div class="flex items-center mt-2">
                    <input type="checkbox" id="show_password_add" class="rounded text-primary focus:ring-primary">
                    <label for="show_password_add" class="ml-2 text-sm text-gray-600">Tampilkan password</label>
                </div>
            </div>
            <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex justify-end space-x-3 rounded-b-lg">
                <button type="button" id="closeAddModal" class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    Batal
                </button>
                <button type="submit" name="add_admin" class="px-4 py-2 text-sm font-medium text-white bg-primary border border-transparent rounded-md shadow-sm hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    Tambah
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Edit Admin Modal -->
<div id="editAdminModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-lg shadow-lg w-full max-w-md mx-4">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800">Edit Admin <span id="edit-admin-username" class="font-medium text-primary"></span></h3>
        </div>
        <form id="editAdminForm" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
            <div class="p-6">
                <input type="hidden" name="admin_id" id="edit_admin_id">
                
                <div class="mb-4">
                    <label for="edit_username" class="block text-sm font-medium text-gray-700 mb-1">Username</label>
                    <input type="text" id="edit_username" name="username" class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-20" required>
                </div>
                
                <div class="mb-4">
                    <label for="edit_email" class="block text-sm font-medium text-gray-700 mb-1">Email</label>
                    <input type="email" id="edit_email" name="email" class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-20" required>
                </div>
                
                <div class="mb-4">
                    <label for="edit_status" class="block text-sm font-medium text-gray-700 mb-1">Status</label>
                    <select id="edit_status" name="status" class="w-full rounded-md border-gray-300 shadow-sm focus:border-primary focus:ring focus:ring-primary focus:ring-opacity-20" required>
                        <option value="active">Active</option>
                        <option value="nonactive">Nonactive</option>
                    </select>
                </div>
                
                <p class="text-sm text-gray-600 italic mt-2">
                    Untuk mengubah password, gunakan menu dropdown "Ubah Password" pada profile
                </p>
            </div>
            <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex justify-end space-x-3 rounded-b-lg">
                <button type="button" id="closeEditModal" class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    Batal
                </button>
                <button type="submit" name="edit_admin" class="px-4 py-2 text-sm font-medium text-white bg-primary border border-transparent rounded-md shadow-sm hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    Simpan Perubahan
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Delete Admin Modal -->
<div id="deleteAdminModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center hidden">
    <div class="bg-white rounded-lg shadow-lg w-full max-w-md mx-4">
        <div class="px-6 py-4 border-b border-gray-200">
            <h3 class="text-lg font-semibold text-gray-800">Konfirmasi Hapus Admin</h3>
        </div>
        <form id="deleteAdminForm" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
            <div class="p-6">
                <input type="hidden" name="admin_id" id="delete_admin_id">
                
                <p class="text-sm text-gray-600">
                    Apakah Anda yakin ingin menghapus admin <span id="delete-admin-username" class="font-semibold"></span>?
                </p>
                <p class="text-sm text-red-600 mt-2">
                    Peringatan: Tindakan ini tidak dapat dibatalkan.
                </p>
            </div>
            <div class="px-6 py-4 bg-gray-50 border-t border-gray-200 flex justify-end space-x-3 rounded-b-lg">
                <button type="button" id="closeDeleteModal" class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    Batal
                </button>
                <button type="submit" name="delete_admin" class="px-4 py-2 text-sm font-medium text-white bg-red-600 border border-transparent rounded-md shadow-sm hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500">
                    Hapus
                </button>
            </div>
        </form>
    </div>
</div>

<!-- JavaScript for modals and form validation -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Add Admin Modal
        const addAdminModal = document.getElementById('addAdminModal');
        const addAdminBtn = document.getElementById('addAdminBtn');
        const closeAddModal = document.getElementById('closeAddModal');
        
        addAdminBtn.addEventListener('click', function() {
            addAdminModal.classList.remove('hidden');
        });
        
        closeAddModal.addEventListener('click', function() {
            addAdminModal.classList.add('hidden');
        });
        
        // Close Add Modal when clicking outside
        addAdminModal.addEventListener('click', function(e) {
            if (e.target === addAdminModal) {
                addAdminModal.classList.add('hidden');
            }
        });
        
        // Edit Admin Modal
        const editAdminModal = document.getElementById('editAdminModal');
        const closeEditModal = document.getElementById('closeEditModal');
        
        closeEditModal.addEventListener('click', function() {
            editAdminModal.classList.add('hidden');
        });
        
        // Close Edit Modal when clicking outside
        editAdminModal.addEventListener('click', function(e) {
            if (e.target === editAdminModal) {
                editAdminModal.classList.add('hidden');
            }
        });
        
        // Delete Admin Modal
        const deleteAdminModal = document.getElementById('deleteAdminModal');
        const closeDeleteModal = document.getElementById('closeDeleteModal');
        
        closeDeleteModal.addEventListener('click', function() {
            deleteAdminModal.classList.add('hidden');
        });
        
        // Close Delete Modal when clicking outside
        deleteAdminModal.addEventListener('click', function(e) {
            if (e.target === deleteAdminModal) {
                deleteAdminModal.classList.add('hidden');
            }
        });
        
        // Show/hide password in Add Modal
        const showPasswordCheckbox = document.getElementById('show_password_add');
        const passwordInputs = document.querySelectorAll('#addAdminForm input[type="password"]');
        
        showPasswordCheckbox.addEventListener('change', function() {
            const type = this.checked ? 'text' : 'password';
            passwordInputs.forEach(input => {
                input.type = type;
            });
        });
        
        // Form validation for matching passwords in Add Modal
        const addAdminForm = document.getElementById('addAdminForm');
        
        addAdminForm.addEventListener('submit', function(e) {
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            
            if (password !== confirmPassword) {
                e.preventDefault();
                alert('Password dan konfirmasi password tidak cocok');
            }
            
            if (password.length < 8) {
                e.preventDefault();
                alert('Password harus minimal 8 karakter');
            }
        });
        
        // Auto-hide notification after 3 seconds
        const notification = document.getElementById('notification');
        if (notification) {
            setTimeout(function() {
                notification.style.transition = 'opacity 0.5s ease';
                notification.style.opacity = '0';
                
                setTimeout(function() {
                    notification.style.display = 'none';
                }, 500);
            }, 3000);
        }
    });
    
    // Function to open Edit Modal
    function openEditModal(id, username, email, status) {
        document.getElementById('edit_admin_id').value = id;
        document.getElementById('edit-admin-username').textContent = username;
        document.getElementById('edit_username').value = username;
        document.getElementById('edit_email').value = email;
        document.getElementById('edit_status').value = status;
        
        document.getElementById('editAdminModal').classList.remove('hidden');
    }
    
    // Function to open Delete Modal
    function openDeleteModal(id, username) {
        document.getElementById('delete_admin_id').value = id;
        document.getElementById('delete-admin-username').textContent = username;
        
        document.getElementById('deleteAdminModal').classList.remove('hidden');
    }
</script>

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