<?php
// Database connection configuration
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'asset_management_system';

// Set timezone untuk Indonesia
date_default_timezone_set('Asia/Jakarta');

try {
    $pdo = new PDO("mysql:host=$host;dbname=$database;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    
    // Set MySQL timezone to Asia/Jakarta
    $pdo->exec("SET time_zone = '+07:00'");
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Process form submissions
$message = '';
$message_type = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_user':
                $result = addUser($pdo, $_POST);
                $message = $result['message'];
                $message_type = $result['type'];
                break;
            case 'edit_user':
                $result = editUser($pdo, $_POST);
                $message = $result['message'];
                $message_type = $result['type'];
                break;
            case 'delete_user':
                $result = deleteUser($pdo, $_POST);
                $message = $result['message'];
                $message_type = $result['type'];
                break;
        }
    }
}

// Functions
function addUser($pdo, $data) {
    try {
        $user_type = $data['user_type'];
        $employee_id = trim($data['employee_id']);
        $password = hash('sha256', trim($data['password']));
        $full_name = trim($data['full_name']);
        $branch_name = trim($data['branch_name']);
        $organization = trim($data['organization']);
        $jabatan = trim($data['jabatan']);
        
        // Check if employee_id already exists in any table
        $tables = ['superadmins', 'admins', 'borrowers'];
        foreach ($tables as $table) {
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM $table WHERE employee_id = ?");
            $stmt->execute([$employee_id]);
            if ($stmt->fetchColumn() > 0) {
                return ['message' => 'Employee ID sudah digunakan!', 'type' => 'error'];
            }
        }
        
        // Insert to appropriate table
        $table = $user_type . 's';
        $stmt = $pdo->prepare("
            INSERT INTO $table (employee_id, password, full_name, branch_name, organization, jabatan, is_active, created_at, updated_at) 
            VALUES (?, ?, ?, ?, ?, ?, 1, NOW(), NOW())
        ");
        
        $stmt->execute([$employee_id, $password, $full_name, $branch_name, $organization, $jabatan]);
        
        return ['message' => 'User berhasil ditambahkan!', 'type' => 'success'];
        
    } catch (Exception $e) {
        return ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
    }
}

function editUser($pdo, $data) {
    try {
        $user_type = $data['user_type'];
        $user_id = $data['user_id'];
        $employee_id = trim($data['employee_id']);
        $full_name = trim($data['full_name']);
        $branch_name = trim($data['branch_name']);
        $organization = trim($data['organization']);
        $jabatan = trim($data['jabatan']);
        $is_active = isset($data['is_active']) ? 1 : 0;
        
        $table = $user_type . 's';
        
        // Update without password if not provided
        if (!empty($data['password'])) {
            $password = hash('sha256', trim($data['password']));
            $stmt = $pdo->prepare("
                UPDATE $table 
                SET employee_id = ?, password = ?, full_name = ?, branch_name = ?, organization = ?, jabatan = ?, is_active = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$employee_id, $password, $full_name, $branch_name, $organization, $jabatan, $is_active, $user_id]);
        } else {
            $stmt = $pdo->prepare("
                UPDATE $table 
                SET employee_id = ?, full_name = ?, branch_name = ?, organization = ?, jabatan = ?, is_active = ?, updated_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$employee_id, $full_name, $branch_name, $organization, $jabatan, $is_active, $user_id]);
        }
        
        return ['message' => 'User berhasil diupdate!', 'type' => 'success'];
        
    } catch (Exception $e) {
        return ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
    }
}

function deleteUser($pdo, $data) {
    try {
        $user_type = $data['user_type'];
        $user_id = $data['user_id'];
        
        $table = $user_type . 's';
        
        $stmt = $pdo->prepare("DELETE FROM $table WHERE id = ?");
        $stmt->execute([$user_id]);
        
        return ['message' => 'User berhasil dihapus!', 'type' => 'success'];
        
    } catch (Exception $e) {
        return ['message' => 'Error: ' . $e->getMessage(), 'type' => 'error'];
    }
}

// Get all users
function getAllUsers($pdo) {
    $users = [];
    
    // Get superadmins
    $stmt = $pdo->prepare("SELECT *, 'superadmin' as user_type FROM superadmins ORDER BY created_at DESC");
    $stmt->execute();
    $users = array_merge($users, $stmt->fetchAll());
    
    // Get admins
    $stmt = $pdo->prepare("SELECT *, 'admin' as user_type FROM admins ORDER BY created_at DESC");
    $stmt->execute();
    $users = array_merge($users, $stmt->fetchAll());
    
    // Get borrowers
    $stmt = $pdo->prepare("SELECT *, 'borrower' as user_type FROM borrowers ORDER BY created_at DESC");
    $stmt->execute();
    $users = array_merge($users, $stmt->fetchAll());
    
    return $users;
}

$all_users = getAllUsers($pdo);
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Account Management - Asset Management System</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'leaf-green': '#90EE90',
                        'dark-leaf': '#32CD32',
                        'soft-gray': '#F5F5F5',
                        'medium-gray': '#9CA3AF'
                    }
                }
            }
        }
    </script>
</head>
<body class="bg-soft-gray min-h-screen">
    <!-- Header -->
    <header class="bg-white shadow-sm border-b-2 border-leaf-green">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between items-center py-4">
                <div class="flex items-center space-x-4">
                    <div>
                        <h1 class="text-xl font-bold text-gray-800">Account Management System</h1>
                        <p class="text-sm text-medium-gray">Kelola Semua User - Superadmin, Admin, Borrower</p>
                    </div>
                </div>
                <div class="flex items-center space-x-4">
                    <button onclick="showAddModal()" class="bg-dark-leaf hover:bg-green-600 text-white px-4 py-2 rounded-lg text-sm transition duration-200">
                        Tambah User
                    </button>
                </div>
            </div>
        </div>
    </header>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <!-- Alert Messages -->
        <?php if ($message): ?>
        <div class="mb-6 p-4 rounded-lg <?php echo $message_type === 'success' ? 'bg-green-100 text-green-700 border border-green-200' : 'bg-red-100 text-red-700 border border-red-200'; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
        <?php endif; ?>

        <!-- Stats Cards -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <?php
            $superadmin_count = count(array_filter($all_users, function($u) { return $u['user_type'] === 'superadmin'; }));
            $admin_count = count(array_filter($all_users, function($u) { return $u['user_type'] === 'admin'; }));
            $borrower_count = count(array_filter($all_users, function($u) { return $u['user_type'] === 'borrower'; }));
            ?>
            
            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-red-400">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Superadmin</p>
                        <p class="text-3xl font-bold text-red-600"><?php echo $superadmin_count; ?></p>
                    </div>
                    <div class="bg-red-100 p-3 rounded-full">
                        <svg class="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-blue-400">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Admin</p>
                        <p class="text-3xl font-bold text-blue-600"><?php echo $admin_count; ?></p>
                    </div>
                    <div class="bg-blue-100 p-3 rounded-full">
                        <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                        </svg>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-lg p-6 border-l-4 border-green-400">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-medium-gray text-sm font-medium">Borrower</p>
                        <p class="text-3xl font-bold text-green-600"><?php echo $borrower_count; ?></p>
                    </div>
                    <div class="bg-green-100 p-3 rounded-full">
                        <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                        </svg>
                    </div>
                </div>
            </div>
        </div>

        <!-- Users Table -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800">Semua User</h3>
            </div>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">User Info</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Organization</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php foreach ($all_users as $user): ?>
                        <tr>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div>
                                    <div class="text-sm font-medium text-gray-900"><?php echo htmlspecialchars($user['full_name']); ?></div>
                                    <div class="text-sm text-gray-500"><?php echo htmlspecialchars($user['employee_id']); ?></div>
                                    <div class="text-xs text-gray-400"><?php echo htmlspecialchars($user['jabatan']); ?></div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full 
                                    <?php 
                                    echo $user['user_type'] === 'superadmin' ? 'bg-red-100 text-red-800' : 
                                        ($user['user_type'] === 'admin' ? 'bg-blue-100 text-blue-800' : 'bg-green-100 text-green-800'); 
                                    ?>">
                                    <?php echo ucfirst($user['user_type']); ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="text-sm text-gray-900"><?php echo htmlspecialchars($user['organization']); ?></div>
                                <div class="text-sm text-gray-500"><?php echo htmlspecialchars($user['branch_name']); ?></div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full 
                                    <?php echo $user['is_active'] ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                    <?php echo $user['is_active'] ? 'Aktif' : 'Tidak Aktif'; ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                <button onclick="showEditModal(<?php echo htmlspecialchars(json_encode($user)); ?>)" 
                                        class="text-indigo-600 hover:text-indigo-900 mr-3">Edit</button>
                                <button onclick="deleteUser('<?php echo $user['user_type']; ?>', <?php echo $user['id']; ?>, '<?php echo htmlspecialchars($user['full_name']); ?>')" 
                                        class="text-red-600 hover:text-red-900">Hapus</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Add User Modal -->
    <div id="addModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <h3 class="text-lg font-medium text-gray-900 mb-4">Tambah User Baru</h3>
                <form method="POST">
                    <input type="hidden" name="action" value="add_user">
                    
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Tipe User</label>
                        <select name="user_type" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                            <option value="">Pilih Tipe User</option>
                            <option value="superadmin">Superadmin</option>
                            <option value="admin">Admin</option>
                            <option value="borrower">Borrower</option>
                        </select>
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Employee ID</label>
                        <input type="text" name="employee_id" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Password</label>
                        <input type="password" name="password" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Nama Lengkap</label>
                        <input type="text" name="full_name" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Branch Name</label>
                        <input type="text" name="branch_name" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Organization</label>
                        <input type="text" name="organization" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Jabatan</label>
                        <input type="text" name="jabatan" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="flex justify-end space-x-3">
                        <button type="button" onclick="hideAddModal()" class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200">
                            Batal
                        </button>
                        <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-dark-leaf rounded-md hover:bg-green-600">
                            Tambah
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Edit User Modal -->
    <div id="editModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
        <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
            <div class="mt-3">
                <h3 class="text-lg font-medium text-gray-900 mb-4">Edit User</h3>
                <form method="POST" id="editForm">
                    <input type="hidden" name="action" value="edit_user">
                    <input type="hidden" name="user_type" id="edit_user_type">
                    <input type="hidden" name="user_id" id="edit_user_id">
                    
                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Employee ID</label>
                        <input type="text" name="employee_id" id="edit_employee_id" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Password (kosongkan jika tidak ingin mengubah)</label>
                        <input type="password" name="password" id="edit_password" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Nama Lengkap</label>
                        <input type="text" name="full_name" id="edit_full_name" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Branch Name</label>
                        <input type="text" name="branch_name" id="edit_branch_name" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Organization</label>
                        <input type="text" name="organization" id="edit_organization" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="mb-4">
                        <label class="block text-sm font-medium text-gray-700 mb-2">Jabatan</label>
                        <input type="text" name="jabatan" id="edit_jabatan" required class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-dark-leaf">
                    </div>

                    <div class="mb-4">
                        <label class="flex items-center">
                            <input type="checkbox" name="is_active" id="edit_is_active" class="mr-2">
                            <span class="text-sm font-medium text-gray-700">User Aktif</span>
                        </label>
                    </div>

                    <div class="flex justify-end space-x-3">
                        <button type="button" onclick="hideEditModal()" class="px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200">
                            Batal
                        </button>
                        <button type="submit" class="px-4 py-2 text-sm font-medium text-white bg-dark-leaf rounded-md hover:bg-green-600">
                            Update
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function showAddModal() {
            document.getElementById('addModal').classList.remove('hidden');
        }

        function hideAddModal() {
            document.getElementById('addModal').classList.add('hidden');
        }

        function showEditModal(user) {
            document.getElementById('edit_user_type').value = user.user_type;
            document.getElementById('edit_user_id').value = user.id;
            document.getElementById('edit_employee_id').value = user.employee_id;
            document.getElementById('edit_full_name').value = user.full_name;
            document.getElementById('edit_branch_name').value = user.branch_name;
            document.getElementById('edit_organization').value = user.organization;
            document.getElementById('edit_jabatan').value = user.jabatan;
            document.getElementById('edit_is_active').checked = user.is_active == 1;
            
            document.getElementById('editModal').classList.remove('hidden');
        }

        function hideEditModal() {
            document.getElementById('editModal').classList.add('hidden');
        }

        function deleteUser(userType, userId, userName) {
            if (confirm(`Apakah Anda yakin ingin menghapus user "${userName}"?`)) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_user">
                    <input type="hidden" name="user_type" value="${userType}">
                    <input type="hidden" name="user_id" value="${userId}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        // Close modals when clicking outside
        window.onclick = function(event) {
            const addModal = document.getElementById('addModal');
            const editModal = document.getElementById('editModal');
            
            if (event.target == addModal) {
                hideAddModal();
            }
            if (event.target == editModal) {
                hideEditModal();
            }
        }
    </script>
</body>
</html>