<?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 borrower
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_borrower'])) {
    $username = sanitize_input($conn, $_POST['username']);
    $nama_borrower = sanitize_input($conn, $_POST['nama_borrower']);
    $email = sanitize_input($conn, $_POST['email']);
    $lokasi_posisi = sanitize_input($conn, $_POST['lokasi_posisi']);
    $status = sanitize_input($conn, $_POST['status']);
    
    // Generate NIK (same as username for this system)
    $nik = $username;
    
    // Generate password from last 3 digits of NIK
    $last3digits = substr($username, -3);
    $password = "password" . $last3digits;
    
    // Validate inputs
    if (empty($username) || empty($nama_borrower) || empty($email)) {
        $error_msg = "Username, nama, dan email harus diisi";
    } elseif (!preg_match('/^KM\d{8}$/', $username)) {
        $error_msg = "Format username harus KM diikuti 8 angka (contoh: KM10000410)";
    } else {
        // Check if username already exists
        $check_stmt = $conn->prepare("SELECT id FROM borrower_users WHERE username = ? OR nik = ?");
        $check_stmt->bind_param("ss", $username, $nik);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows > 0) {
            $error_msg = "Username/NIK sudah digunakan";
        } else {
            // Hash the password
            $hashed_password = hash_password($password);
            
            // Insert new borrower user
            $insert_stmt = $conn->prepare("INSERT INTO borrower_users (username, nama_borrower, nik, password, email, lokasi_posisi, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $insert_stmt->bind_param("sssssss", $username, $nama_borrower, $nik, $hashed_password, $email, $lokasi_posisi, $status);
            
            if ($insert_stmt->execute()) {
                $success_msg = "Akun borrower berhasil ditambahkan. Password: " . $password;
                
                // Log the action
                $details = "IT ID " . $it_id . " ({$_SESSION['username']}) added new borrower user: " . $username . " (" . $nama_borrower . ")";
                log_activity($conn, $it_id, 'it', 'Add Borrower User', $details);
            } else {
                $error_msg = "Gagal menambahkan borrower: " . $conn->error;
            }
            
            $insert_stmt->close();
        }
        $check_stmt->close();
    }
}

// Process form submission for editing borrower
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_borrower'])) {
    $borrower_id = sanitize_input($conn, $_POST['borrower_id']);
    $username = sanitize_input($conn, $_POST['username']);
    $nama_borrower = sanitize_input($conn, $_POST['nama_borrower']);
    $email = sanitize_input($conn, $_POST['email']);
    $lokasi_posisi = sanitize_input($conn, $_POST['lokasi_posisi']);
    $status = sanitize_input($conn, $_POST['status']);
    
    // Generate NIK (same as username for this system)
    $nik = $username;
    
    // Validate inputs
    if (empty($username) || empty($nama_borrower) || empty($email)) {
        $error_msg = "Username, nama, dan email tidak boleh kosong";
    } elseif (!preg_match('/^KM\d{8}$/', $username)) {
        $error_msg = "Format username harus KM diikuti 8 angka (contoh: KM10000410)";
    } else {
        // Check if username already exists (except for the current user)
        $check_stmt = $conn->prepare("SELECT id FROM borrower_users WHERE (username = ? OR nik = ?) AND id != ?");
        $check_stmt->bind_param("ssi", $username, $nik, $borrower_id);
        $check_stmt->execute();
        $check_result = $check_stmt->get_result();
        
        if ($check_result->num_rows > 0) {
            $error_msg = "Username/NIK sudah digunakan oleh borrower lain";
        } else {
            // Update borrower user
            $update_stmt = $conn->prepare("UPDATE borrower_users SET username = ?, nama_borrower = ?, nik = ?, email = ?, lokasi_posisi = ?, status = ? WHERE id = ?");
            $update_stmt->bind_param("ssssssi", $username, $nama_borrower, $nik, $email, $lokasi_posisi, $status, $borrower_id);
            
            if ($update_stmt->execute()) {
                $success_msg = "Data borrower berhasil diperbarui";
                
                // Log the action
                $details = "IT ID " . $it_id . " ({$_SESSION['username']}) updated borrower user ID: " . $borrower_id . " (" . $nama_borrower . ")";
                log_activity($conn, $it_id, 'it', 'Update Borrower User', $details);
            } else {
                $error_msg = "Gagal memperbarui data borrower: " . $conn->error;
            }
            
            $update_stmt->close();
        }
        $check_stmt->close();
    }
}

// Process form submission for deleting borrower
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_borrower'])) {
    $borrower_id = sanitize_input($conn, $_POST['borrower_id']);
    
    // Check if borrower has active transactions
    $check_stmt = $conn->prepare("SELECT COUNT(*) as transaction_count FROM stock_transactions WHERE borrower_id = ? AND status_peminjaman = 'Dipinjam'");
    $check_stmt->bind_param("i", $borrower_id);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result()->fetch_assoc();
    $check_stmt->close();
    
    if ($check_result['transaction_count'] > 0) {
        $error_msg = "Tidak dapat menghapus borrower yang memiliki transaksi aktif";
    } else {
        // Get borrower name for logging
        $name_stmt = $conn->prepare("SELECT nama_borrower FROM borrower_users WHERE id = ?");
        $name_stmt->bind_param("i", $borrower_id);
        $name_stmt->execute();
        $name_result = $name_stmt->get_result()->fetch_assoc();
        $borrower_name = $name_result ? $name_result['nama_borrower'] : 'Unknown';
        $name_stmt->close();
        
        // Delete borrower user
        $delete_stmt = $conn->prepare("DELETE FROM borrower_users WHERE id = ?");
        $delete_stmt->bind_param("i", $borrower_id);
        
        if ($delete_stmt->execute()) {
            $success_msg = "Borrower berhasil dihapus";
            
            // Log the action
            $details = "IT ID " . $it_id . " ({$_SESSION['username']}) deleted borrower user ID: " . $borrower_id . " (" . $borrower_name . ")";
            log_activity($conn, $it_id, 'it', 'Delete Borrower User', $details);
        } else {
            $error_msg = "Gagal menghapus borrower: " . $conn->error;
        }
        
        $delete_stmt->close();
    }
}

// Fetch Borrower users
$borrower_users = [];
$borrower_stmt = $conn->prepare("SELECT id, username, nama_borrower, nik, email, lokasi_posisi, status FROM borrower_users ORDER BY username");
$borrower_stmt->execute();
$borrower_result = $borrower_stmt->get_result();
while ($row = $borrower_result->fetch_assoc()) {
    $borrower_users[] = $row;
}
$borrower_stmt->close();

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

// 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 Borrower</h2>
        <p class="text-gray-600">Halaman ini digunakan untuk mengelola akun borrower dalam sistem. Anda dapat menambah, mengedit, dan menghapus akun borrower.</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; ?>
    
    <!-- Borrower 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 Borrower</h3>
            <button id="addBorrowerBtn" 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 Borrower
            </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/NIK</th>
                        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Nama</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">Lokasi/Posisi</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-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($borrower_users)): ?>
                    <tr>
                        <td colspan="7" class="px-6 py-4 text-center text-sm text-gray-500">Tidak ada data borrower</td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($borrower_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-900"><?php echo htmlspecialchars($user['nama_borrower']); ?></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 text-gray-500"><?php echo htmlspecialchars($user['lokasi_posisi']); ?></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-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['nama_borrower']); ?>', '<?php echo htmlspecialchars($user['email']); ?>', '<?php echo $user['lokasi_posisi']; ?>', '<?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['nama_borrower']); ?>')">
                                    <i class="fas fa-trash"></i> Hapus
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<!-- Add Borrower Modal -->
<div id="addBorrowerModal" 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 Borrower Baru</h3>
        </div>
        <form id="addBorrowerForm" 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/NIK</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 pattern="KM\d{8}" placeholder="KM10000410" maxlength="10">
                    <p class="mt-1 text-xs text-gray-500">Format: KM diikuti 8 angka (contoh: KM10000410)</p>
                </div>
                
                <div class="mb-4">
                    <label for="nama_borrower" class="block text-sm font-medium text-gray-700 mb-1">Nama Lengkap</label>
                    <input type="text" id="nama_borrower" name="nama_borrower" 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="lokasi_posisi" class="block text-sm font-medium text-gray-700 mb-1">Lokasi/Posisi</label>
                    <select id="lokasi_posisi" name="lokasi_posisi" 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="">Pilih Lokasi/Posisi</option>
                        <option value="PTG 6">PTG 6</option>
                        <option value="PTG MANUAL">PTG MANUAL</option>
                        <option value="PACKING">PACKING</option>
                        <option value="CHAIR">CHAIR</option>
                        <option value="QC OPEN BOX">QC OPEN BOX</option>
                        <option value="PTG 6 CONVEYOR">PTG 6 CONVEYOR</option>
                        <option value="PUSHPULL MANUAL">PUSHPULL MANUAL</option>
                    </select>
                </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="bg-blue-50 p-3 rounded-md">
                    <p class="text-sm text-blue-700">
                        <i class="fas fa-info-circle mr-1"></i>
                        Password akan dibuat otomatis dengan format: password + 3 angka terakhir NIK
                    </p>
                    <p class="text-xs text-blue-600 mt-1" id="passwordPreview">
                        Contoh: Jika NIK KM10000410, maka password = password410
                    </p>
                </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_borrower" 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 Borrower Modal -->
<div id="editBorrowerModal" 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 Borrower <span id="edit-borrower-name" class="font-medium text-primary"></span></h3>
        </div>
        <form id="editBorrowerForm" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
            <div class="p-6">
                <input type="hidden" name="borrower_id" id="edit_borrower_id">
                
                <div class="mb-4">
                    <label for="edit_username" class="block text-sm font-medium text-gray-700 mb-1">Username/NIK</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 pattern="KM\d{8}" maxlength="10">
                    <p class="mt-1 text-xs text-gray-500">Format: KM diikuti 8 angka (contoh: KM10000410)</p>
                </div>
                
                <div class="mb-4">
                    <label for="edit_nama_borrower" class="block text-sm font-medium text-gray-700 mb-1">Nama Lengkap</label>
                    <input type="text" id="edit_nama_borrower" name="nama_borrower" 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_lokasi_posisi" class="block text-sm font-medium text-gray-700 mb-1">Lokasi/Posisi</label>
                    <select id="edit_lokasi_posisi" name="lokasi_posisi" 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="PTG 6">PTG 6</option>
                        <option value="PTG MANUAL">PTG MANUAL</option>
                        <option value="PACKING">PACKING</option>
                        <option value="CHAIR">CHAIR</option>
                        <option value="QC OPEN BOX">QC OPEN BOX</option>
                        <option value="PTG 6 CONVEYOR">PTG 6 CONVEYOR</option>
                        <option value="PUSHPULL MANUAL">PUSHPULL MANUAL</option>
                    </select>
                </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">
                    <i class="fas fa-info-circle mr-1"></i>
                    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_borrower" 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 Borrower Modal -->
<div id="deleteBorrowerModal" 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 Borrower</h3>
        </div>
        <form id="deleteBorrowerForm" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
            <div class="p-6">
                <input type="hidden" name="borrower_id" id="delete_borrower_id">
                
                <p class="text-sm text-gray-600">
                    Apakah Anda yakin ingin menghapus borrower <span id="delete-borrower-name" class="font-semibold"></span>?
                </p>
                <p class="text-sm text-red-600 mt-2">
                    Peringatan: Tindakan ini tidak dapat dibatalkan. Borrower dengan transaksi aktif tidak dapat dihapus.
                </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_borrower" 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 Borrower Modal
        const addBorrowerModal = document.getElementById('addBorrowerModal');
        const addBorrowerBtn = document.getElementById('addBorrowerBtn');
        const closeAddModal = document.getElementById('closeAddModal');
        
        addBorrowerBtn.addEventListener('click', function() {
            addBorrowerModal.classList.remove('hidden');
        });
        
        closeAddModal.addEventListener('click', function() {
            addBorrowerModal.classList.add('hidden');
        });
        
        // Close Add Modal when clicking outside
        addBorrowerModal.addEventListener('click', function(e) {
            if (e.target === addBorrowerModal) {
                addBorrowerModal.classList.add('hidden');
            }
        });
        
        // Edit Borrower Modal
        const editBorrowerModal = document.getElementById('editBorrowerModal');
        const closeEditModal = document.getElementById('closeEditModal');
        
        closeEditModal.addEventListener('click', function() {
            editBorrowerModal.classList.add('hidden');
        });
        
        // Close Edit Modal when clicking outside
        editBorrowerModal.addEventListener('click', function(e) {
            if (e.target === editBorrowerModal) {
                editBorrowerModal.classList.add('hidden');
            }
        });
        
        // Delete Borrower Modal
        const deleteBorrowerModal = document.getElementById('deleteBorrowerModal');
        const closeDeleteModal = document.getElementById('closeDeleteModal');
        
        closeDeleteModal.addEventListener('click', function() {
            deleteBorrowerModal.classList.add('hidden');
        });
        
        // Close Delete Modal when clicking outside
        deleteBorrowerModal.addEventListener('click', function(e) {
            if (e.target === deleteBorrowerModal) {
                deleteBorrowerModal.classList.add('hidden');
            }
        });
        
        // Username input validation and password preview
        const usernameInput = document.getElementById('username');
        const passwordPreview = document.getElementById('passwordPreview');
        
        usernameInput.addEventListener('input', function() {
            const value = this.value;
            
            // Validate format
            if (value.length >= 3) {
                const last3digits = value.slice(-3);
                if (/^\d{3}$/.test(last3digits)) {
                    passwordPreview.textContent = `Password akan dibuat: password${last3digits}`;
                } else {
                    passwordPreview.textContent = 'Format: KM diikuti 8 angka (contoh: KM10000410)';
                }
            } else {
                passwordPreview.textContent = 'Format: KM diikuti 8 angka (contoh: KM10000410)';
            }
        });
        
        // Form validation for Add Modal
        const addBorrowerForm = document.getElementById('addBorrowerForm');
        
        addBorrowerForm.addEventListener('submit', function(e) {
            const username = document.getElementById('username').value;
            const nama = document.getElementById('nama_borrower').value;
            
            // Validate username format
            if (!/^KM\d{8}$/.test(username)) {
                e.preventDefault();
                alert('Format username harus KM diikuti 8 angka (contoh: KM10000410)');
                return;
            }
            
            // Validate nama
            if (nama.trim().length < 2) {
                e.preventDefault();
                alert('Nama harus diisi minimal 2 karakter');
                return;
            }
        });
        
        // Auto-hide notification after 5 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);
            }, 5000);
        }
    });
    
    // Function to open Edit Modal
    function openEditModal(id, username, nama, email, lokasi_posisi, status) {
        document.getElementById('edit_borrower_id').value = id;
        document.getElementById('edit-borrower-name').textContent = nama;
        document.getElementById('edit_username').value = username;
        document.getElementById('edit_nama_borrower').value = nama;
        document.getElementById('edit_email').value = email;
        document.getElementById('edit_lokasi_posisi').value = lokasi_posisi;
        document.getElementById('edit_status').value = status;
        
        document.getElementById('editBorrowerModal').classList.remove('hidden');
    }
    
    // Function to open Delete Modal
    function openDeleteModal(id, nama) {
        document.getElementById('delete_borrower_id').value = id;
        document.getElementById('delete-borrower-name').textContent = nama;
        
        document.getElementById('deleteBorrowerModal').classList.remove('hidden');
    }
</script>

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