<?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 password update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_password'])) {
    $user_id = sanitize_input($conn, $_POST['user_id']);
    $user_type = sanitize_input($conn, $_POST['user_type']);
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];
    
    // Validate passwords
    if (empty($new_password) || empty($confirm_password)) {
        $error_msg = "Password baru dan konfirmasi password tidak boleh kosong";
    } elseif ($new_password !== $confirm_password) {
        $error_msg = "Password baru dan konfirmasi password tidak cocok";
    } elseif (strlen($new_password) < 8) {
        $error_msg = "Password baru harus minimal 8 karakter";
    } else {
        // Hash the new password
        $hashed_password = hash_password($new_password);
        
        // Update password based on user type
        switch ($user_type) {
            case 'admin':
                $update_stmt = $conn->prepare("UPDATE admin_users SET password = ? WHERE id = ?");
                break;
            case 'borrower':
                $update_stmt = $conn->prepare("UPDATE borrower_users SET password = ? WHERE id = ?");
                break;
            default:
                $error_msg = "Tipe pengguna tidak valid";
                break;
        }
        
        if (isset($update_stmt)) {
            $update_stmt->bind_param("si", $hashed_password, $user_id);
            
            if ($update_stmt->execute()) {
                $success_msg = "Password berhasil diperbarui untuk " . ucfirst($user_type) . " ID: " . $user_id;
                
                // Log the password change in audit_logs only
                $details = "IT ID " . $it_id . " ({$_SESSION['username']}) updated password for " . $user_type . " user ID " . $user_id;
                create_audit_log($conn, 'password_update', $it_id, 'it', $details);
            } else {
                $error_msg = "Gagal memperbarui password: " . $conn->error;
            }
            
            $update_stmt->close();
        }
    }
}

// Process form submission for status update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $user_id = sanitize_input($conn, $_POST['user_id']);
    $user_type = sanitize_input($conn, $_POST['user_type']);
    $new_status = sanitize_input($conn, $_POST['new_status']);
    
    // Validate status value
    if ($new_status !== 'active' && $new_status !== 'nonactive') {
        $error_msg = "Status tidak valid";
    } else {
        // Update status based on user type
        switch ($user_type) {
            case 'admin':
                $update_stmt = $conn->prepare("UPDATE admin_users SET status = ? WHERE id = ?");
                break;
            case 'borrower':
                $update_stmt = $conn->prepare("UPDATE borrower_users SET status = ? WHERE id = ?");
                break;
            default:
                $error_msg = "Tipe pengguna tidak valid";
                break;
        }
        
        if (isset($update_stmt)) {
            $update_stmt->bind_param("si", $new_status, $user_id);
            
            if ($update_stmt->execute()) {
                $success_msg = "Status berhasil diperbarui menjadi '" . ucfirst($new_status) . "' untuk " . ucfirst($user_type) . " ID: " . $user_id;
                
                // Log the status change in audit_logs only
                $details = "IT ID " . $it_id . " ({$_SESSION['username']}) updated status to " . $new_status . " for " . $user_type . " user ID " . $user_id;
                create_audit_log($conn, 'status_update', $it_id, 'it', $details);
            } else {
                $error_msg = "Gagal memperbarui status: " . $conn->error;
            }
            
            $update_stmt->close();
        }
    }
}

// Set page title
$page_title = "Pembaharuan Password & Status";

// Fetch Admin users
$admin_users = [];
$admin_stmt = $conn->prepare("SELECT id, username, email, status 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();

// Fetch Borrower users
$borrower_users = [];
$borrower_stmt = $conn->prepare("SELECT id, username, 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();

// 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">Selamat Datang di Master Color Panel</h2>
        
        <div class="border-t border-gray-200 pt-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 class="flex items-center">
                    <div class="p-3 rounded-full bg-green-100 text-green-500 mr-3">
                        <i class="fas fa-user-check text-xl"></i>
                    </div>
                    <div>
                        <p class="text-sm text-gray-500">Status</p>
                        <p class="text-lg font-medium text-green-500">Active</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; ?>
    
    <!-- User Management Section -->
    <div class="mb-6">
        <h3 class="text-xl font-semibold text-gray-800 mb-4">Manajemen Pengguna</h3>
        <p class="mb-4 text-sm font-bold text-gray-700">Di halaman ini Anda dapat mengubah password dan status untuk pengguna (Active/Nonactive).</p>
        
        <!-- Tab Navigation -->
        <div class="border-b border-gray-200 mb-6">
            <ul class="flex flex-wrap -mb-px" id="userTabs" role="tablist">
                <li class="mr-2" role="presentation">
                    <button class="inline-block py-2 px-4 text-primary border-b-2 border-primary font-medium text-sm focus:outline-none" id="admin-tab" data-tab="admin-content" type="button" role="tab" aria-selected="true">
                        Admin Users
                    </button>
                </li>
                <li class="mr-2" role="presentation">
                    <button class="inline-block py-2 px-4 text-gray-500 hover:text-primary font-medium text-sm focus:outline-none" id="borrower-tab" data-tab="borrower-content" type="button" role="tab" aria-selected="false">
                        borrower
                    </button>
                </li>
            </ul>
        </div>
        
        <!-- Admin Users Tab Content -->
        <div id="admin-content" class="tab-content block">
            <div class="overflow-x-auto bg-white rounded-lg shadow">
                <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-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="5" class="px-6 py-4 text-center text-sm text-gray-500">Tidak ada data pengguna 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-right text-sm font-medium">
                                    <button class="text-primary hover:text-primary-dark focus:outline-none mr-3" 
                                            onclick="openPasswordModal('<?php echo $user['id']; ?>', '<?php echo htmlspecialchars($user['username']); ?>', 'admin')">
                                        Ubah Password
                                    </button>
                                    <button class="<?php echo $user['status'] == 'active' ? 'text-red-600 hover:text-red-800' : 'text-green-600 hover:text-green-800'; ?> focus:outline-none" 
                                            onclick="openStatusModal('<?php echo $user['id']; ?>', '<?php echo htmlspecialchars($user['username']); ?>', 'admin', '<?php echo $user['status']; ?>')">
                                        <?php echo $user['status'] == 'active' ? 'Nonaktifkan' : 'Aktifkan'; ?>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <!-- Borrower Users Tab Content -->
        <div id="borrower-content" class="tab-content hidden">
            <div class="overflow-x-auto bg-white rounded-lg shadow">
                <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">Lokasi</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="6" 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-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-primary hover:text-primary-dark focus:outline-none mr-3" 
                                            onclick="openPasswordModal('<?php echo $user['id']; ?>', '<?php echo htmlspecialchars($user['username']); ?>', 'borrower')">
                                        Ubah Password
                                    </button>
                                    <button class="<?php echo $user['status'] == 'active' ? 'text-red-600 hover:text-red-800' : 'text-green-600 hover:text-green-800'; ?> focus:outline-none" 
                                            onclick="openStatusModal('<?php echo $user['id']; ?>', '<?php echo htmlspecialchars($user['username']); ?>', 'borrower', '<?php echo $user['status']; ?>')">
                                        <?php echo $user['status'] == 'active' ? 'Nonaktifkan' : 'Aktifkan'; ?>
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</main>

<!-- Password Change Modal -->
<div id="passwordModal" 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">Ubah Password <span id="modal-username" class="font-medium text-primary"></span></h3>
        </div>
        <form id="passwordForm" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
            <div class="p-6">
                <input type="hidden" name="user_id" id="user_id">
                <input type="hidden" name="user_type" id="user_type">
                
                <div class="mb-4">
                    <label for="new_password" class="block text-sm font-medium text-gray-700 mb-1">Password Baru</label>
                    <input type="password" id="new_password" name="new_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="flex items-center mt-2">
                    <input type="checkbox" id="show_password" class="rounded text-primary focus:ring-primary">
                    <label for="show_password" 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="closePasswordModal" 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="update_password" 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
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Status Change Modal -->
<div id="statusModal" 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">Ubah Status <span id="status-modal-username" class="font-medium text-primary"></span></h3>
        </div>
        <form id="statusForm" method="POST" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
            <div class="p-6">
                <input type="hidden" name="user_id" id="status_user_id">
                <input type="hidden" name="user_type" id="status_user_type">
                <input type="hidden" name="new_status" id="new_status">
                
                <div class="mb-4">
                    <p class="text-sm text-gray-600" id="status-confirmation-message"></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="closeStatusModal" 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="update_status" id="confirmStatusBtn" 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">
                    Konfirmasi
                </button>
            </div>
        </form>
    </div>
</div>

<!-- JavaScript for tabs and modals -->
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Tab functionality
        const tabButtons = document.querySelectorAll('#userTabs button');
        const tabContents = document.querySelectorAll('.tab-content');
        
        tabButtons.forEach(button => {
            button.addEventListener('click', function() {
                const tabId = this.getAttribute('data-tab');
                
                // Hide all tab contents
                tabContents.forEach(content => {
                    content.classList.add('hidden');
                });
                
                // Show selected tab content
                document.getElementById(tabId).classList.remove('hidden');
                
                // Update tab button styles
                tabButtons.forEach(btn => {
                    btn.classList.remove('text-primary', 'border-b-2', 'border-primary');
                    btn.classList.add('text-gray-500', 'hover:text-primary');
                    btn.setAttribute('aria-selected', 'false');
                });
                
                this.classList.remove('text-gray-500', 'hover:text-primary');
                this.classList.add('text-primary', 'border-b-2', 'border-primary');
                this.setAttribute('aria-selected', 'true');
            });
        });
        
        // Password modal functionality
        const passwordModal = document.getElementById('passwordModal');
        const closePasswordModal = document.getElementById('closePasswordModal');
        
        window.openPasswordModal = function(userId, username, userType) {
            document.getElementById('user_id').value = userId;
            document.getElementById('user_type').value = userType;
            document.getElementById('modal-username').textContent = username;
            
            // Clear password fields
            document.getElementById('new_password').value = '';
            document.getElementById('confirm_password').value = '';
            
            // Show modal
            passwordModal.classList.remove('hidden');
        };
        
        closePasswordModal.addEventListener('click', function() {
            passwordModal.classList.add('hidden');
        });
        
        // Close password modal when clicking outside
        passwordModal.addEventListener('click', function(e) {
            if (e.target === passwordModal) {
                passwordModal.classList.add('hidden');
            }
        });
        
        // Status modal functionality
        const statusModal = document.getElementById('statusModal');
        const closeStatusModal = document.getElementById('closeStatusModal');
        
        window.openStatusModal = function(userId, username, userType, currentStatus) {
            document.getElementById('status_user_id').value = userId;
            document.getElementById('status_user_type').value = userType;
            document.getElementById('status-modal-username').textContent = username;
            
            // Set the new status (opposite of current)
            const newStatus = currentStatus === 'active' ? 'nonactive' : 'active';
            document.getElementById('new_status').value = newStatus;
            
            // Set confirmation message
            const message = currentStatus === 'active' 
                ? `Apakah Anda yakin ingin menonaktifkan akun pengguna "${username}"?` 
                : `Apakah Anda yakin ingin mengaktifkan kembali akun pengguna "${username}"?`;
            document.getElementById('status-confirmation-message').textContent = message;
            
            // Set button color based on action
            const confirmBtn = document.getElementById('confirmStatusBtn');
            if (currentStatus === 'active') {
                confirmBtn.classList.remove('bg-primary', 'hover:bg-primary-dark');
                confirmBtn.classList.add('bg-red-600', 'hover:bg-red-800');
            } else {
                confirmBtn.classList.remove('bg-red-600', 'hover:bg-red-800');
                confirmBtn.classList.add('bg-green-600', 'hover:bg-green-800');
            }
            
            // Show modal
            statusModal.classList.remove('hidden');
        };
        
        closeStatusModal.addEventListener('click', function() {
            statusModal.classList.add('hidden');
        });
        
        // Close status modal when clicking outside
        statusModal.addEventListener('click', function(e) {
            if (e.target === statusModal) {
                statusModal.classList.add('hidden');
            }
        });
        
        // Show/hide password
        const showPasswordCheckbox = document.getElementById('show_password');
        const passwordInputs = document.querySelectorAll('input[type="password"]');
        
        showPasswordCheckbox.addEventListener('change', function() {
            const type = this.checked ? 'text' : 'password';
            passwordInputs.forEach(input => {
                input.type = type;
            });
        });
        
        // 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);
        }
        
        // Form validation for matching passwords
        const passwordForm = document.getElementById('passwordForm');
        if (passwordForm) {
            passwordForm.addEventListener('submit', function(e) {
                const newPassword = document.getElementById('new_password').value;
                const confirmPassword = document.getElementById('confirm_password').value;
                
                if (newPassword !== confirmPassword) {
                    e.preventDefault();
                    alert('Password baru dan konfirmasi password tidak cocok');
                }
                
                if (newPassword.length < 8) {
                    e.preventDefault();
                    alert('Password harus minimal 8 karakter');
                }
            });
        }
    });
</script>

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