Index: .idea/vcs.xml
===================================================================
--- .idea/vcs.xml	(revision 591278cabf928650250cb8d40aabda08753a31c5)
+++ .idea/vcs.xml	(revision 4dff800e0e61b01aeb1b15846b32fb42aed69027)
@@ -1,4 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <project version="4">
-  <component name="VcsDirectoryMappings" defaultProject="true" />
+  <component name="VcsDirectoryMappings">
+    <mapping directory="$PROJECT_DIR$" vcs="Git" />
+  </component>
 </project>
Index: database.js
===================================================================
--- database.js	(revision 591278cabf928650250cb8d40aabda08753a31c5)
+++ database.js	(revision 4dff800e0e61b01aeb1b15846b32fb42aed69027)
@@ -1094,43 +1094,91 @@
 // User functions for admin
 function getAllUsers(callback) {
-    const users = [];
+    const usersMap = new Map(); // Use Map to deduplicate by ID
 
     // Get client users
     database.all(
-        `SELECT client_id as id, first_name, last_name, email, 'client' as user_type
-     FROM client
-     ORDER BY client_id`,
+        `SELECT client_id as id, first_name, last_name, email, 'client' as user_type,
+                NULL as username, NULL as role_priority
+         FROM client
+         ORDER BY client_id`,
         [],
         (err, rows) => {
-            if (!err) {
-                users.push(...(rows || []));
-            }
-
-            // Get personal users
+            if (!err && rows) {
+                rows.forEach(row => {
+                    // Clients have lowest priority (5)
+                    row.role_priority = 5;
+                    usersMap.set(row.id, row);
+                });
+            }
+
+            // Get personal users (employees and store owners)
             database.all(
                 `SELECT p.id, p.first_name, p.last_name, p.email,
-          CASE WHEN b.boss_id IS NOT NULL THEN 'store_owner'
-               WHEN e.employee_id IS NOT NULL THEN 'store_employee'
-               ELSE 'personal' END as user_type
-         FROM personal p
-         LEFT JOIN boss b ON p.id = b.boss_id
-         LEFT JOIN employees e ON p.id = e.employee_id
-         ORDER BY p.id`,
+                        CASE 
+                            WHEN b.boss_id IS NOT NULL THEN 'store_owner'
+                            ELSE 'store_employee'
+                        END as user_type,
+                        NULL as username,
+                        CASE 
+                            WHEN b.boss_id IS NOT NULL THEN 2  -- store_owner priority 2
+                            ELSE 4                             -- store_employee priority 4
+                        END as role_priority
+                 FROM personal p
+                 LEFT JOIN boss b ON p.id = b.boss_id
+                 LEFT JOIN employees e ON p.id = e.employee_id
+                 WHERE b.boss_id IS NOT NULL OR e.employee_id IS NOT NULL
+                 ORDER BY p.id`,
                 [],
                 (err, rows) => {
-                    if (!err) {
-                        users.push(...(rows || []));
+                    if (!err && rows) {
+                        rows.forEach(row => {
+                            // Only add if not exists or current has higher priority (lower number)
+                            const existing = usersMap.get(row.id);
+                            if (!existing || (existing.role_priority && row.role_priority < existing.role_priority)) {
+                                usersMap.set(row.id, row);
+                            }
+                        });
                     }
 
-                    // Get system users
+                    // Get system users (including admin)
                     database.all(
-                        `SELECT id, username, email, user_type
-             FROM users
-             ORDER BY id`,
+                        `SELECT id, username, email, user_type,
+                                CASE 
+                                    WHEN user_type = 'admin' THEN 1  -- admin highest priority
+                                    ELSE 3                            -- other system users priority 3
+                                END as role_priority
+                         FROM users
+                         ORDER BY id`,
                         [],
                         (err, rows) => {
-                            if (!err) {
-                                users.push(...(rows || []));
-                            }
+                            if (!err && rows) {
+                                rows.forEach(row => {
+                                    // System users have priority based on type
+                                    const existing = usersMap.get(row.id);
+                                    if (!existing || (existing.role_priority && row.role_priority < existing.role_priority)) {
+                                        // For system users, format the response properly
+                                        const userData = {
+                                            id: row.id,
+                                            username: row.username,
+                                            email: row.email,
+                                            user_type: row.user_type,
+                                            role_priority: row.role_priority
+                                        };
+                                        // Add first_name/last_name if not present
+                                        if (row.user_type === 'admin') {
+                                            userData.first_name = 'Admin';
+                                            userData.last_name = 'User';
+                                        }
+                                        usersMap.set(row.id, userData);
+                                    }
+                                });
+                            }
+
+                            // Convert Map to array and remove role_priority before sending
+                            const users = Array.from(usersMap.values()).map(user => {
+                                const { role_priority, ...userWithoutPriority } = user;
+                                return userWithoutPriority;
+                            });
+
                             callback(null, users);
                         }
Index: interfejs/change-password.html
===================================================================
--- interfejs/change-password.html	(revision 591278cabf928650250cb8d40aabda08753a31c5)
+++ interfejs/change-password.html	(revision 4dff800e0e61b01aeb1b15846b32fb42aed69027)
@@ -27,10 +27,8 @@
         <p class="form-subtitle" id="password-message">Please set a new password</p>
 
+        <div id="error-message" class="error-message" style="display: none; color: red; margin-bottom: 1rem; padding: 10px; background-color: #ffeeee; border-radius: 5px;"></div>
+        <div id="success-message" class="success-message" style="display: none; color: green; margin-bottom: 1rem; padding: 10px; background-color: #eeffee; border-radius: 5px;"></div>
+
         <form id="change-password-form" class="form">
-            <div class="form-group">
-                <label for="current-password">Current Password</label>
-                <input type="password" id="current-password" name="current-password" required>
-            </div>
-
             <div class="form-group">
                 <label for="new-password">New Password</label>
@@ -45,5 +43,5 @@
 
             <div class="form-group">
-                <button type="submit" class="btn-primary btn-full">Change Password</button>
+                <button type="submit" class="btn-primary btn-full" id="submit-btn">Change Password</button>
             </div>
         </form>
@@ -75,4 +73,5 @@
         const urlParams = new URLSearchParams(window.location.search);
         const isForced = urlParams.get('forced') === 'true';
+        let userType = 'admin'; // Default
 
         if (isForced) {
@@ -82,17 +81,50 @@
 
         const form = document.getElementById('change-password-form');
+        const submitBtn = document.getElementById('submit-btn');
+        const errorDiv = document.getElementById('error-message');
+        const successDiv = document.getElementById('success-message');
+
+        // Check if user is authenticated for password change and get user type
+        checkAuthStatus();
+
         form.addEventListener('submit', async (e) => {
             e.preventDefault();
 
+            // Clear previous messages
+            errorDiv.style.display = 'none';
+            successDiv.style.display = 'none';
+
+            // Disable submit button to prevent double submission
+            submitBtn.disabled = true;
+            submitBtn.textContent = 'Changing Password...';
+
             const newPassword = document.getElementById('new-password').value;
             const confirmPassword = document.getElementById('confirm-password').value;
 
+            // Client-side validation
+            if (!newPassword || !confirmPassword) {
+                showError('All fields are required');
+                submitBtn.disabled = false;
+                submitBtn.textContent = 'Change Password';
+                return;
+            }
+
             if (newPassword !== confirmPassword) {
-                alert('New passwords do not match');
+                showError('New passwords do not match');
+                submitBtn.disabled = false;
+                submitBtn.textContent = 'Change Password';
                 return;
             }
 
+            // Validate password strength
+            const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
+            if (!passwordRegex.test(newPassword)) {
+                showError('Password must have at least 8 characters, including uppercase, lowercase, number and special character');
+                submitBtn.disabled = false;
+                submitBtn.textContent = 'Change Password';
+                return;
+            }
+
             const formData = {
-                currentPassword: document.getElementById('current-password').value,
                 newPassword: newPassword,
                 confirmPassword: confirmPassword
@@ -100,23 +132,93 @@
 
             try {
+                console.log('Sending password change request...');
                 const response = await fetch('/api/force-change-password', {
                     method: 'POST',
-                    headers: { 'Content-Type': 'application/json' },
-                    body: JSON.stringify(formData)
+                    headers: {
+                        'Content-Type': 'application/json'
+                    },
+                    body: JSON.stringify(formData),
+                    credentials: 'include' // Important: include cookies
                 });
 
                 const data = await response.json();
+                console.log('Response:', data);
 
                 if (data.success) {
-                    alert('Password changed successfully!');
-                    window.location.href = data.redirectTo || 'dashboard.html';
+                    showSuccess('Password changed successfully! Redirecting...');
+
+                    // Clear form
+                    form.reset();
+
+                    // Redirect after short delay
+                    setTimeout(() => {
+                        window.location.href = data.redirectTo || 'dashboard.html';
+                    }, 1500);
                 } else {
-                    alert(data.message || 'Failed to change password');
+                    showError(data.message || 'Failed to change password');
+                    submitBtn.disabled = false;
+                    submitBtn.textContent = 'Change Password';
                 }
             } catch (error) {
                 console.error('Password change error:', error);
-                alert('An error occurred');
+                showError('Network error: ' + error.message);
+                submitBtn.disabled = false;
+                submitBtn.textContent = 'Change Password';
             }
         });
+
+        async function checkAuthStatus() {
+            try {
+                const response = await fetch('/api/user', {
+                    credentials: 'include'
+                });
+                const data = await response.json();
+
+                if (!data.success) {
+                    // Not authenticated, redirect to login
+                    window.location.href = 'login.html';
+                } else if (data.isTempSession) {
+                    console.log('Valid temporary session for password change');
+                    if (data.user && data.user.userType) {
+                        userType = data.user.userType;
+                    }
+                } else {
+                    // Already have full session, redirect to appropriate dashboard
+                    if (data.user && data.user.userType) {
+                        switch(data.user.userType) {
+                            case 'admin':
+                                window.location.href = 'admin.html';
+                                break;
+                            case 'store_owner':
+                                window.location.href = 'store-owner.html';
+                                break;
+                            case 'store_employee':
+                                window.location.href = 'store-employee.html';
+                                break;
+                            case 'client':
+                                window.location.href = 'client-dashboard.html';
+                                break;
+                            default:
+                                window.location.href = 'dashboard.html';
+                        }
+                    }
+                }
+            } catch (error) {
+                console.error('Auth check error:', error);
+            }
+        }
+
+        function showError(message) {
+            errorDiv.textContent = message;
+            errorDiv.style.display = 'block';
+            setTimeout(() => {
+                errorDiv.style.display = 'none';
+            }, 5000);
+        }
+
+        function showSuccess(message) {
+            successDiv.textContent = message;
+            successDiv.style.display = 'block';
+        }
     });
 </script>
Index: server.js
===================================================================
--- server.js	(revision 591278cabf928650250cb8d40aabda08753a31c5)
+++ server.js	(revision 4dff800e0e61b01aeb1b15846b32fb42aed69027)
@@ -10,5 +10,4 @@
 
 const port = process.env.PORT || 3000;
-
 const sessions = new Map();
 const verificationCodes = new Map();
@@ -32,7 +31,5 @@
         }
     };
-
     emailTransporter = nodemailer.createTransport(emailConfig);
-
     emailTransporter.verify(function(error, success) {
         if (error) {
@@ -75,16 +72,16 @@
         subject: 'Your Verification Code - Handcraft Marketplace',
         html: `
-      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: linear-gradient(135deg, #4169E1 0%, #FF69B4 100%); color: white; padding: 20px; border-radius: 10px;">
-        <h2 style="text-align: center;">🎨 Handcraft Marketplace</h2>
-        <div style="background-color: white; color: #333; padding: 20px; border-radius: 8px; margin: 20px 0;">
-          <h3 style="color: #4169E1;">Account Verification</h3>
-          <p>Your verification code is:</p>
-          <div style="background-color: #f5f5f5; padding: 15px; border-radius: 5px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 5px; margin: 20px 0; color: #4169E1;">
-            ${code}
-          </div>
-          <p style="color: #e74c3c; font-weight: bold;">⚠️ This code will expire in 30 seconds</p>
-          <p style="color: #666; font-size: 12px;">If you didn't request this verification, please ignore this email.</p>
-        </div>
-      </div>`
+        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: linear-gradient(135deg, #4169E1 0%, #FF69B4 100%); color: white; padding: 20px; border-radius: 10px;">
+            <h2 style="text-align: center;">🎨 Handcraft Marketplace</h2>
+            <div style="background-color: white; color: #333; padding: 20px; border-radius: 8px; margin: 20px 0;">
+                <h3 style="color: #4169E1;">Account Verification</h3>
+                <p>Your verification code is:</p>
+                <div style="background-color: #f5f5f5; padding: 15px; border-radius: 5px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 5px; margin: 20px 0; color: #4169E1;">
+                    ${code}
+                </div>
+                <p style="color: #e74c3c; font-weight: bold;">⚠️ This code will expire in 30 seconds</p>
+                <p style="color: #666; font-size: 12px;">If you didn't request this verification, please ignore this email.</p>
+            </div>
+        </div>`
     };
 
@@ -106,16 +103,16 @@
         subject: 'Your 2FA Code - Handcraft Marketplace',
         html: `
-      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: linear-gradient(135deg, #4169E1 0%, #FF69B4 100%); color: white; padding: 20px; border-radius: 10px;">
-        <h2 style="text-align: center;">🎨 Handcraft Marketplace</h2>
-        <div style="background-color: white; color: #333; padding: 20px; border-radius: 8px; margin: 20px 0;">
-          <h3 style="color: #4169E1;">Two-Factor Authentication</h3>
-          <p>Your login verification code is:</p>
-          <div style="background-color: #f5f5f5; padding: 15px; border-radius: 5px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 5px; margin: 20px 0; color: #4169E1;">
-            ${code}
-          </div>
-          <p style="color: #e74c3c; font-weight: bold;">⚠️ This code will expire in 30 seconds</p>
-          <p style="color: #666; font-size: 12px;">If you're not trying to login, please secure your account immediately.</p>
-        </div>
-      </div>`
+        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: linear-gradient(135deg, #4169E1 0%, #FF69B4 100%); color: white; padding: 20px; border-radius: 10px;">
+            <h2 style="text-align: center;">🎨 Handcraft Marketplace</h2>
+            <div style="background-color: white; color: #333; padding: 20px; border-radius: 8px; margin: 20px 0;">
+                <h3 style="color: #4169E1;">Two-Factor Authentication</h3>
+                <p>Your login verification code is:</p>
+                <div style="background-color: #f5f5f5; padding: 15px; border-radius: 5px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 5px; margin: 20px 0; color: #4169E1;">
+                    ${code}
+                </div>
+                <p style="color: #e74c3c; font-weight: bold;">⚠️ This code will expire in 30 seconds</p>
+                <p style="color: #666; font-size: 12px;">If you're not trying to login, please secure your account immediately.</p>
+            </div>
+        </div>`
     };
 
@@ -137,17 +134,17 @@
         subject: 'Store Registration Verification - Handcraft Marketplace',
         html: `
-      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: linear-gradient(135deg, #4169E1 0%, #FF69B4 100%); color: white; padding: 20px; border-radius: 10px;">
-        <h2 style="text-align: center;">🎨 Handcraft Marketplace</h2>
-        <div style="background-color: white; color: #333; padding: 20px; border-radius: 8px; margin: 20px 0;">
-          <h3 style="color: #4169E1;">Store Registration Verification</h3>
-          <p>Thank you for registering your store "<strong>${storeName}</strong>" on Handcraft Marketplace!</p>
-          <p>Your verification code is:</p>
-          <div style="background-color: #f5f5f5; padding: 15px; border-radius: 5px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 5px; margin: 20px 0; color: #4169E1;">
-            ${code}
-          </div>
-          <p style="color: #e74c3c; font-weight: bold;">⚠️ This code will expire in 30 seconds</p>
-          <p style="color: #666; font-size: 12px;">If you didn't request this verification, please ignore this email.</p>
-        </div>
-      </div>`
+        <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; background: linear-gradient(135deg, #4169E1 0%, #FF69B4 100%); color: white; padding: 20px; border-radius: 10px;">
+            <h2 style="text-align: center;">🎨 Handcraft Marketplace</h2>
+            <div style="background-color: white; color: #333; padding: 20px; border-radius: 8px; margin: 20px 0;">
+                <h3 style="color: #4169E1;">Store Registration Verification</h3>
+                <p>Thank you for registering your store "<strong>${storeName}</strong>" on Handcraft Marketplace!</p>
+                <p>Your verification code is:</p>
+                <div style="background-color: #f5f5f5; padding: 15px; border-radius: 5px; text-align: center; font-size: 24px; font-weight: bold; letter-spacing: 5px; margin: 20px 0; color: #4169E1;">
+                    ${code}
+                </div>
+                <p style="color: #e74c3c; font-weight: bold;">⚠️ This code will expire in 30 seconds</p>
+                <p style="color: #666; font-size: 12px;">If you didn't request this verification, please ignore this email.</p>
+            </div>
+        </div>`
     };
 
@@ -302,19 +299,35 @@
         requireAuth(req, res, (userId) => {
             const userIdStr = String(userId);
-            const personalId = userIdStr.replace('personal_', '');
-
-            database.database.get(
-                'SELECT boss_id FROM boss WHERE boss_id = $1',
-                [personalId],
-                (err, boss) => {
-                    if (err || !boss) {
-                        res.writeHead(403, { 'Content-Type': 'application/json' });
-                        res.end(JSON.stringify({ success: false, message: 'Access denied - not a store owner' }));
-                        return;
-                    }
-
-                    callback(personalId);
-                }
-            );
+
+            // Check if this is the admin user (ID 000000)
+            if (userIdStr === '000000') {
+                // Admin is not a store owner
+                res.writeHead(403, { 'Content-Type': 'application/json' });
+                res.end(JSON.stringify({ success: false, message: 'Access denied - not a store owner' }));
+                return;
+            }
+
+            // Check if it's a personal user
+            if (userIdStr.startsWith('personal_')) {
+                const personalId = userIdStr.replace('personal_', '');
+
+                database.database.get(
+                    'SELECT boss_id FROM boss WHERE boss_id = ?',
+                    [personalId],
+                    (err, boss) => {
+                        if (err || !boss) {
+                            res.writeHead(403, { 'Content-Type': 'application/json' });
+                            res.end(JSON.stringify({ success: false, message: 'Access denied - not a store owner' }));
+                            return;
+                        }
+
+                        callback(personalId);
+                    }
+                );
+            } else {
+                // Not a personal user, so not a store owner
+                res.writeHead(403, { 'Content-Type': 'application/json' });
+                res.end(JSON.stringify({ success: false, message: 'Access denied - not a store owner' }));
+            }
         });
     };
@@ -386,4 +399,6 @@
         } else {
             console.log('✅ All required tables exist');
+            // Even if tables exist, ensure admin user exists with ID 000000
+            await ensureAdminUser();
         }
     } catch (err) {
@@ -401,4 +416,133 @@
         }
     }
+}
+
+// Function to ensure admin user exists with ID 000000
+function ensureAdminUser() {
+    return new Promise((resolve) => {
+        database.database.get(
+            'SELECT * FROM users WHERE id = ? OR username = ? OR email = ?',
+            ['000000', 'admin', 'admin@handcraft.com'],
+            (err, existingAdmin) => {
+                if (err) {
+                    console.error('Error checking for existing admin:', err.message);
+                    resolve();
+                    return;
+                }
+
+                // Insert admin user if it doesn't exist
+                if (!existingAdmin) {
+                    const adminId = '000000';
+                    const adminPassword = bcrypt.hashSync('Admin123!', 10);
+
+                    // Start a transaction
+                    database.database.run('BEGIN TRANSACTION', (err) => {
+                        if (err) {
+                            console.error('Error beginning transaction:', err);
+                            resolve();
+                            return;
+                        }
+
+                        // Insert into users table
+                        database.database.run(
+                            `INSERT INTO users (id, username, email, password, user_type, force_password_change)
+                             VALUES (?, ?, ?, ?, ?, ?)`,
+                            [adminId, 'admin', 'admin@handcraft.com', adminPassword, 'admin', 1],
+                            function(err) {
+                                if (err) {
+                                    database.database.run('ROLLBACK');
+                                    console.error('Error inserting admin user:', err.message);
+                                    resolve();
+                                    return;
+                                }
+
+                                // Insert into personal table (required for boss table)
+                                database.database.run(
+                                    `INSERT INTO personal (id, first_name, last_name, ssn, email, password)
+                                     VALUES (?, ?, ?, ?, ?, ?)`,
+                                    [adminId, 'Admin', 'User', '0000000000000', 'admin@handcraft.com', adminPassword],
+                                    function(err) {
+                                        if (err) {
+                                            database.database.run('ROLLBACK');
+                                            console.error('Error inserting admin personal:', err.message);
+                                            resolve();
+                                            return;
+                                        }
+
+                                        // Insert into boss table (store owner)
+                                        database.database.run(
+                                            `INSERT INTO boss (boss_id, signature)
+                                             VALUES (?, ?)`,
+                                            [adminId, 'Admin Signature'],
+                                            function(err) {
+                                                if (err) {
+                                                    database.database.run('ROLLBACK');
+                                                    console.error('Error inserting admin boss:', err.message);
+                                                    resolve();
+                                                    return;
+                                                }
+
+                                                // Insert into permissions
+                                                database.database.run(
+                                                    `INSERT INTO permissions (personal_id, type, authorisation)
+                                                     VALUES (?, ?, ?)`,
+                                                    [adminId, 'ADMIN', 'full_access'],
+                                                    function(err) {
+                                                        if (err) {
+                                                            console.error('Error inserting admin permissions:', err.message);
+                                                            // Continue even if this fails
+                                                        }
+
+                                                        // Assign admin role
+                                                        database.database.get(
+                                                            'SELECT role_id FROM roles WHERE name = ?',
+                                                            ['admin'],
+                                                            (err, adminRole) => {
+                                                                if (!err && adminRole) {
+                                                                    database.database.run(
+                                                                        'INSERT OR IGNORE INTO user_roles (user_id, role_id) VALUES (?, ?)',
+                                                                        [adminId, adminRole.role_id],
+                                                                        (err) => {
+                                                                            if (err) {
+                                                                                console.error('Error assigning admin role:', err.message);
+                                                                            }
+                                                                        }
+                                                                    );
+                                                                }
+
+                                                                database.database.run('COMMIT', (commitErr) => {
+                                                                    if (commitErr) {
+                                                                        console.error('Error committing transaction:', commitErr);
+                                                                        database.database.run('ROLLBACK');
+                                                                    } else {
+                                                                        console.log('\n');
+                                                                        console.log('🔐 ===== ADMIN CREDENTIALS =====');
+                                                                        console.log('🆔 ID: 000000');
+                                                                        console.log('👤 Username: admin');
+                                                                        console.log('📧 Email: admin@handcraft.com');
+                                                                        console.log('🔑 Password: Admin123!');
+                                                                        console.log('⚠️ This is a first-time login. You will be required to change your password after 2FA verification.');
+                                                                        console.log('================================\n');
+                                                                    }
+                                                                    resolve();
+                                                                });
+                                                            }
+                                                        );
+                                                    }
+                                                );
+                                            }
+                                        );
+                                    }
+                                );
+                            }
+                        );
+                    });
+                } else {
+                    console.log('✅ Admin user already exists with ID:', existingAdmin.id);
+                    resolve();
+                }
+            }
+        );
+    });
 }
 
@@ -463,223 +607,223 @@
             // Client table (SERIAL ID starting from 1000)
             `CREATE TABLE IF NOT EXISTS client (
-        client_id INTEGER PRIMARY KEY AUTOINCREMENT,
-        first_name VARCHAR(100) NOT NULL,
-        last_name VARCHAR(100) NOT NULL,
-        email VARCHAR(255) UNIQUE NOT NULL,
-        password VARCHAR(255) NOT NULL,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                client_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                first_name VARCHAR(100) NOT NULL,
+                last_name VARCHAR(100) NOT NULL,
+                email VARCHAR(255) UNIQUE NOT NULL,
+                password VARCHAR(255) NOT NULL,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Store table (VARCHAR ID)
             `CREATE TABLE IF NOT EXISTS store (
-        store_id VARCHAR(10) PRIMARY KEY,
-        name VARCHAR(255) NOT NULL,
-        date_of_founding DATE NOT NULL,
-        physical_address TEXT NOT NULL,
-        store_email VARCHAR(255) UNIQUE NOT NULL,
-        rating DECIMAL(3,2) DEFAULT 0.0
-      )`,
+                store_id VARCHAR(10) PRIMARY KEY,
+                name VARCHAR(255) NOT NULL,
+                date_of_founding DATE NOT NULL,
+                physical_address TEXT NOT NULL,
+                store_email VARCHAR(255) UNIQUE NOT NULL,
+                rating DECIMAL(3,2) DEFAULT 0.0
+            )`,
 
             // Category table (SERIAL ID starting from 1)
             `CREATE TABLE IF NOT EXISTS category (
-        category_id INTEGER PRIMARY KEY AUTOINCREMENT,
-        name VARCHAR(100) NOT NULL,
-        description TEXT,
-        parent_category_id INTEGER REFERENCES category(category_id) ON DELETE SET NULL
-      )`,
+                category_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                name VARCHAR(100) NOT NULL,
+                description TEXT,
+                parent_category_id INTEGER REFERENCES category(category_id) ON DELETE SET NULL
+            )`,
 
             // Users table (VARCHAR ID)
             `CREATE TABLE IF NOT EXISTS users (
-        id VARCHAR(50) PRIMARY KEY,
-        username VARCHAR(100) UNIQUE NOT NULL,
-        email VARCHAR(255) UNIQUE NOT NULL,
-        password VARCHAR(255) NOT NULL,
-        user_type VARCHAR(50) NOT NULL,
-        force_password_change INTEGER DEFAULT 0,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                id VARCHAR(50) PRIMARY KEY,
+                username VARCHAR(100) UNIQUE NOT NULL,
+                email VARCHAR(255) UNIQUE NOT NULL,
+                password VARCHAR(255) NOT NULL,
+                user_type VARCHAR(50) NOT NULL,
+                force_password_change INTEGER DEFAULT 0,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Personal table (VARCHAR ID - format: storeId(3) + '001' for owner, storeId(3) + employeeNum(3) for employees)
             `CREATE TABLE IF NOT EXISTS personal (
-        id VARCHAR(10) PRIMARY KEY,
-        first_name VARCHAR(100) NOT NULL,
-        last_name VARCHAR(100) NOT NULL,
-        ssn VARCHAR(13) UNIQUE NOT NULL,
-        email VARCHAR(255) UNIQUE NOT NULL,
-        password VARCHAR(255) NOT NULL,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                id VARCHAR(10) PRIMARY KEY,
+                first_name VARCHAR(100) NOT NULL,
+                last_name VARCHAR(100) NOT NULL,
+                ssn VARCHAR(13) UNIQUE NOT NULL,
+                email VARCHAR(255) UNIQUE NOT NULL,
+                password VARCHAR(255) NOT NULL,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Product table (VARCHAR ID)
             `CREATE TABLE IF NOT EXISTS product (
-        id VARCHAR(50) PRIMARY KEY,
-        code VARCHAR(20) UNIQUE NOT NULL,
-        description TEXT NOT NULL,
-        price DECIMAL(10,2) NOT NULL,
-        availability INTEGER NOT NULL DEFAULT 0,
-        weight DECIMAL(10,2),
-        dimensions VARCHAR(50),
-        production_time INTEGER,
-        category_id INTEGER REFERENCES category(category_id) ON DELETE SET NULL,
-        store_id VARCHAR(10) REFERENCES store(store_id) ON DELETE CASCADE,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                id VARCHAR(50) PRIMARY KEY,
+                code VARCHAR(20) UNIQUE NOT NULL,
+                description TEXT NOT NULL,
+                price DECIMAL(10,2) NOT NULL,
+                availability INTEGER NOT NULL DEFAULT 0,
+                weight DECIMAL(10,2),
+                dimensions VARCHAR(50),
+                production_time INTEGER,
+                category_id INTEGER REFERENCES category(category_id) ON DELETE SET NULL,
+                store_id VARCHAR(10) REFERENCES store(store_id) ON DELETE CASCADE,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Boss table (VARCHAR ID - references personal.id)
             `CREATE TABLE IF NOT EXISTS boss (
-        boss_id VARCHAR(10) PRIMARY KEY REFERENCES personal(id) ON DELETE CASCADE,
-        signature TEXT NOT NULL,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                boss_id VARCHAR(10) PRIMARY KEY REFERENCES personal(id) ON DELETE CASCADE,
+                signature TEXT NOT NULL,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Employees table (VARCHAR ID - references personal.id)
             `CREATE TABLE IF NOT EXISTS employees (
-        employee_id VARCHAR(10) PRIMARY KEY REFERENCES personal(id) ON DELETE CASCADE,
-        date_of_hire DATE NOT NULL,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                employee_id VARCHAR(10) PRIMARY KEY REFERENCES personal(id) ON DELETE CASCADE,
+                date_of_hire DATE NOT NULL,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Works_in_store table (junction)
             `CREATE TABLE IF NOT EXISTS works_in_store (
-        personal_id VARCHAR(10) REFERENCES personal(id) ON DELETE CASCADE,
-        store_id VARCHAR(10) REFERENCES store(store_id) ON DELETE CASCADE,
-        PRIMARY KEY (personal_id, store_id)
-      )`,
+                personal_id VARCHAR(10) REFERENCES personal(id) ON DELETE CASCADE,
+                store_id VARCHAR(10) REFERENCES store(store_id) ON DELETE CASCADE,
+                PRIMARY KEY (personal_id, store_id)
+            )`,
 
             // Permissions table
             `CREATE TABLE IF NOT EXISTS permissions (
-        permission_id INTEGER PRIMARY KEY AUTOINCREMENT,
-        personal_id VARCHAR(10) REFERENCES personal(id) ON DELETE CASCADE,
-        type VARCHAR(50) NOT NULL,
-        authorisation TEXT,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                permission_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                personal_id VARCHAR(10) REFERENCES personal(id) ON DELETE CASCADE,
+                type VARCHAR(50) NOT NULL,
+                authorisation TEXT,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Order table (VARCHAR ID)
             `CREATE TABLE IF NOT EXISTS "order" (
-        order_num VARCHAR(20) PRIMARY KEY,
-        client_id INTEGER REFERENCES client(client_id) ON DELETE SET NULL,
-        order_date TIMESTAMP NOT NULL,
-        quantity INTEGER NOT NULL,
-        payment_method VARCHAR(50) NOT NULL,
-        discount DECIMAL(10,2) DEFAULT 0,
-        delivery_address TEXT NOT NULL,
-        store_id VARCHAR(10) REFERENCES store(store_id) ON DELETE SET NULL,
-        status VARCHAR(50) DEFAULT 'pending',
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                order_num VARCHAR(20) PRIMARY KEY,
+                client_id INTEGER REFERENCES client(client_id) ON DELETE SET NULL,
+                order_date TIMESTAMP NOT NULL,
+                quantity INTEGER NOT NULL,
+                payment_method VARCHAR(50) NOT NULL,
+                discount DECIMAL(10,2) DEFAULT 0,
+                delivery_address TEXT NOT NULL,
+                store_id VARCHAR(10) REFERENCES store(store_id) ON DELETE SET NULL,
+                status VARCHAR(50) DEFAULT 'pending',
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Order_items table
             `CREATE TABLE IF NOT EXISTS order_items (
-        item_id INTEGER PRIMARY KEY AUTOINCREMENT,
-        order_num VARCHAR(20) REFERENCES "order"(order_num) ON DELETE CASCADE,
-        product_code VARCHAR(20) REFERENCES product(code) ON DELETE SET NULL,
-        quantity INTEGER NOT NULL,
-        price DECIMAL(10,2) NOT NULL,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                item_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                order_num VARCHAR(20) REFERENCES "order"(order_num) ON DELETE CASCADE,
+                product_code VARCHAR(20) REFERENCES product(code) ON DELETE SET NULL,
+                quantity INTEGER NOT NULL,
+                price DECIMAL(10,2) NOT NULL,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Review table (VARCHAR ID)
             `CREATE TABLE IF NOT EXISTS review (
-        review_id VARCHAR(20) PRIMARY KEY,
-        client_id INTEGER REFERENCES client(client_id) ON DELETE SET NULL,
-        product_code VARCHAR(20) REFERENCES product(code) ON DELETE CASCADE,
-        rating INTEGER NOT NULL CHECK (rating >= 1 AND rating <= 5),
-        comment TEXT,
-        review_date TIMESTAMP NOT NULL,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                review_id VARCHAR(20) PRIMARY KEY,
+                client_id INTEGER REFERENCES client(client_id) ON DELETE SET NULL,
+                product_code VARCHAR(20) REFERENCES product(code) ON DELETE CASCADE,
+                rating INTEGER NOT NULL CHECK (rating >= 1 AND rating <= 5),
+                comment TEXT,
+                review_date TIMESTAMP NOT NULL,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Request table (VARCHAR ID)
             `CREATE TABLE IF NOT EXISTS request (
-        request_num VARCHAR(50) PRIMARY KEY,
-        date_and_time TIMESTAMP NOT NULL,
-        problem TEXT NOT NULL,
-        client_id INTEGER REFERENCES client(client_id) ON DELETE SET NULL,
-        store_id VARCHAR(10) REFERENCES store(store_id) ON DELETE CASCADE,
-        status VARCHAR(50) DEFAULT 'pending',
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                request_num VARCHAR(50) PRIMARY KEY,
+                date_and_time TIMESTAMP NOT NULL,
+                problem TEXT NOT NULL,
+                client_id INTEGER REFERENCES client(client_id) ON DELETE SET NULL,
+                store_id VARCHAR(10) REFERENCES store(store_id) ON DELETE CASCADE,
+                status VARCHAR(50) DEFAULT 'pending',
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Refund table (VARCHAR ID)
             `CREATE TABLE IF NOT EXISTS refund (
-        refund_id VARCHAR(50) PRIMARY KEY,
-        order_num VARCHAR(20) REFERENCES "order"(order_num) ON DELETE CASCADE,
-        amount DECIMAL(10,2) NOT NULL,
-        reason TEXT NOT NULL,
-        status VARCHAR(50) DEFAULT 'pending',
-        request_date TIMESTAMP NOT NULL,
-        processed_date TIMESTAMP,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                refund_id VARCHAR(50) PRIMARY KEY,
+                order_num VARCHAR(20) REFERENCES "order"(order_num) ON DELETE CASCADE,
+                amount DECIMAL(10,2) NOT NULL,
+                reason TEXT NOT NULL,
+                status VARCHAR(50) DEFAULT 'pending',
+                request_date TIMESTAMP NOT NULL,
+                processed_date TIMESTAMP,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Report table (VARCHAR ID)
             `CREATE TABLE IF NOT EXISTS report (
-        id VARCHAR(50) PRIMARY KEY,
-        store_id VARCHAR(10) REFERENCES store(store_id) ON DELETE CASCADE,
-        period VARCHAR(50) NOT NULL,
-        start_date DATE NOT NULL,
-        end_date DATE NOT NULL,
-        type VARCHAR(50) NOT NULL,
-        generated_by VARCHAR(10) REFERENCES personal(id) ON DELETE SET NULL,
-        generated_at TIMESTAMP NOT NULL,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                id VARCHAR(50) PRIMARY KEY,
+                store_id VARCHAR(10) REFERENCES store(store_id) ON DELETE CASCADE,
+                period VARCHAR(50) NOT NULL,
+                start_date DATE NOT NULL,
+                end_date DATE NOT NULL,
+                type VARCHAR(50) NOT NULL,
+                generated_by VARCHAR(10) REFERENCES personal(id) ON DELETE SET NULL,
+                generated_at TIMESTAMP NOT NULL,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Audit_log table (SERIAL ID)
             `CREATE TABLE IF NOT EXISTS audit_log (
-        log_id INTEGER PRIMARY KEY AUTOINCREMENT,
-        user_id VARCHAR(50),
-        action VARCHAR(100) NOT NULL,
-        resource_type VARCHAR(50),
-        resource_id VARCHAR(50),
-        details TEXT,
-        ip_address VARCHAR(45),
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                log_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                user_id VARCHAR(50),
+                action VARCHAR(100) NOT NULL,
+                resource_type VARCHAR(50),
+                resource_id VARCHAR(50),
+                details TEXT,
+                ip_address VARCHAR(45),
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Color table (SERIAL ID)
             `CREATE TABLE IF NOT EXISTS color (
-        color_id INTEGER PRIMARY KEY AUTOINCREMENT,
-        name VARCHAR(50) NOT NULL,
-        hex_code VARCHAR(7) NOT NULL,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                color_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                name VARCHAR(50) NOT NULL,
+                hex_code VARCHAR(7) NOT NULL,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Image table (SERIAL ID)
             `CREATE TABLE IF NOT EXISTS image (
-        image_id INTEGER PRIMARY KEY AUTOINCREMENT,
-        product_code VARCHAR(20) REFERENCES product(code) ON DELETE CASCADE,
-        image_url TEXT NOT NULL,
-        is_primary BOOLEAN DEFAULT FALSE,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                image_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                product_code VARCHAR(20) REFERENCES product(code) ON DELETE CASCADE,
+                image_url TEXT NOT NULL,
+                is_primary BOOLEAN DEFAULT FALSE,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Delivery_address table (SERIAL ID)
             `CREATE TABLE IF NOT EXISTS delivery_address (
-        address_id INTEGER PRIMARY KEY AUTOINCREMENT,
-        client_id INTEGER REFERENCES client(client_id) ON DELETE CASCADE,
-        address TEXT NOT NULL,
-        city VARCHAR(100) NOT NULL,
-        postcode VARCHAR(20) NOT NULL,
-        country VARCHAR(100) NOT NULL,
-        is_default BOOLEAN DEFAULT FALSE,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                address_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                client_id INTEGER REFERENCES client(client_id) ON DELETE CASCADE,
+                address TEXT NOT NULL,
+                city VARCHAR(100) NOT NULL,
+                postcode VARCHAR(20) NOT NULL,
+                country VARCHAR(100) NOT NULL,
+                is_default BOOLEAN DEFAULT FALSE,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // Roles table (SERIAL ID)
             `CREATE TABLE IF NOT EXISTS roles (
-        role_id INTEGER PRIMARY KEY AUTOINCREMENT,
-        name VARCHAR(50) UNIQUE NOT NULL,
-        description TEXT,
-        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
-      )`,
+                role_id INTEGER PRIMARY KEY AUTOINCREMENT,
+                name VARCHAR(50) UNIQUE NOT NULL,
+                description TEXT,
+                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+            )`,
 
             // User_roles table (junction)
             `CREATE TABLE IF NOT EXISTS user_roles (
-        user_id VARCHAR(50) REFERENCES users(id) ON DELETE CASCADE,
-        role_id INTEGER REFERENCES roles(role_id) ON DELETE CASCADE,
-        PRIMARY KEY (user_id, role_id)
-      )`
+                user_id VARCHAR(50) REFERENCES users(id) ON DELETE CASCADE,
+                role_id INTEGER REFERENCES roles(role_id) ON DELETE CASCADE,
+                PRIMARY KEY (user_id, role_id)
+            )`
         ];
 
@@ -766,24 +910,4 @@
         console.log('📝 Inserting initial data...');
 
-        // REMOVED: Category insertion - now handled by database.ensureGeneralCategory()
-
-        // Insert admin user
-        const adminId = 'admin_' + Date.now().toString().slice(-6);
-        const adminPassword = bcrypt.hashSync('Admin123!', 10);
-
-        database.database.run(
-            `INSERT INTO users (id, username, email, password, user_type, force_password_change)
-       VALUES ($1, $2, $3, $4, $5, $6)
-       ON CONFLICT DO NOTHING`,
-            [adminId, 'admin', 'admin@handcraft.com', adminPassword, 'admin', 1],
-            (err) => {
-                if (err) {
-                    console.error('Error inserting admin user:', err.message);
-                } else {
-                    console.log('✅ Admin user created');
-                }
-            }
-        );
-
         // Insert default roles
         const roles = [
@@ -800,6 +924,6 @@
             database.database.run(
                 `INSERT INTO roles (name, description)
-         VALUES ($1, $2)
-         ON CONFLICT DO NOTHING`,
+                 VALUES (?, ?)
+                 ON CONFLICT DO NOTHING`,
                 [role.name, role.description],
                 (err) => {
@@ -810,4 +934,7 @@
                     if (rolesInserted === roles.length) {
                         console.log('✅ Roles inserted');
+
+                        // Create admin user with ID 000000
+                        createAdminUser();
 
                         // Ensure General category exists
@@ -825,4 +952,123 @@
         });
     });
+}
+
+// Function to create admin user with ID 000000
+function createAdminUser() {
+    const adminId = '000000';
+    const adminPassword = bcrypt.hashSync('Admin123!', 10);
+
+    database.database.get(
+        'SELECT * FROM users WHERE id = ? OR username = ? OR email = ?',
+        [adminId, 'admin', 'admin@handcraft.com'],
+        (err, existingAdmin) => {
+            if (err) {
+                console.error('Error checking for existing admin:', err.message);
+                return;
+            }
+
+            if (!existingAdmin) {
+                // Start a transaction
+                database.database.run('BEGIN TRANSACTION', (err) => {
+                    if (err) {
+                        console.error('Error beginning transaction:', err);
+                        return;
+                    }
+
+                    // Insert into users table
+                    database.database.run(
+                        `INSERT INTO users (id, username, email, password, user_type, force_password_change)
+                         VALUES (?, ?, ?, ?, ?, ?)`,
+                        [adminId, 'admin', 'admin@handcraft.com', adminPassword, 'admin', 1],
+                        function(err) {
+                            if (err) {
+                                database.database.run('ROLLBACK');
+                                console.error('Error inserting admin user:', err.message);
+                                return;
+                            }
+
+                            // Insert into personal table (required for boss table)
+                            database.database.run(
+                                `INSERT INTO personal (id, first_name, last_name, ssn, email, password)
+                                 VALUES (?, ?, ?, ?, ?, ?)`,
+                                [adminId, 'Admin', 'User', '0000000000000', 'admin@handcraft.com', adminPassword],
+                                function(err) {
+                                    if (err) {
+                                        database.database.run('ROLLBACK');
+                                        console.error('Error inserting admin personal:', err.message);
+                                        return;
+                                    }
+
+                                    // Insert into boss table (store owner)
+                                    database.database.run(
+                                        `INSERT INTO boss (boss_id, signature)
+                                         VALUES (?, ?)`,
+                                        [adminId, 'Admin Signature'],
+                                        function(err) {
+                                            if (err) {
+                                                database.database.run('ROLLBACK');
+                                                console.error('Error inserting admin boss:', err.message);
+                                                return;
+                                            }
+
+                                            // Insert into permissions
+                                            database.database.run(
+                                                `INSERT INTO permissions (personal_id, type, authorisation)
+                                                 VALUES (?, ?, ?)`,
+                                                [adminId, 'ADMIN', 'full_access'],
+                                                function(err) {
+                                                    if (err) {
+                                                        console.error('Error inserting admin permissions:', err.message);
+                                                        // Continue even if this fails
+                                                    }
+
+                                                    // Assign admin role
+                                                    database.database.get(
+                                                        'SELECT role_id FROM roles WHERE name = ?',
+                                                        ['admin'],
+                                                        (err, adminRole) => {
+                                                            if (!err && adminRole) {
+                                                                database.database.run(
+                                                                    'INSERT OR IGNORE INTO user_roles (user_id, role_id) VALUES (?, ?)',
+                                                                    [adminId, adminRole.role_id],
+                                                                    (err) => {
+                                                                        if (err) {
+                                                                            console.error('Error assigning admin role:', err.message);
+                                                                        }
+                                                                    }
+                                                                );
+                                                            }
+
+                                                            database.database.run('COMMIT', (commitErr) => {
+                                                                if (commitErr) {
+                                                                    console.error('Error committing transaction:', commitErr);
+                                                                    database.database.run('ROLLBACK');
+                                                                } else {
+                                                                    console.log('\n');
+                                                                    console.log('🔐 ===== ADMIN CREDENTIALS =====');
+                                                                    console.log('🆔 ID: 000000');
+                                                                    console.log('👤 Username: admin');
+                                                                    console.log('📧 Email: admin@handcraft.com');
+                                                                    console.log('🔑 Password: Admin123!');
+                                                                    console.log('⚠️ This is a first-time login. You will be required to change your password after 2FA verification.');
+                                                                    console.log('================================\n');
+                                                                }
+                                                            });
+                                                        }
+                                                    );
+                                                }
+                                            );
+                                        }
+                                    );
+                                }
+                            );
+                        }
+                    );
+                });
+            } else {
+                console.log('✅ Admin user already exists with ID:', existingAdmin.id);
+            }
+        }
+    );
 }
 
@@ -884,4 +1130,45 @@
         serveStaticFile(res, 'verify-2fa.html', 'text/html');
     } else if (pathname === '/admin.html') {
+        // Check if user is authenticated
+        const cookies = parseCookies(req);
+        const sessionId = cookies.sessionId;
+
+        if (!sessionId || !sessions.has(sessionId)) {
+            res.writeHead(302, { 'Location': '/login.html' });
+            res.end();
+            return;
+        }
+
+        // Get user from session
+        const userId = sessions.get(sessionId);
+
+        // Check if this is the admin user
+        if (userId !== '000000') {
+            // Not admin, redirect to appropriate dashboard
+            if (userId.startsWith('client_')) {
+                res.writeHead(302, { 'Location': '/client-dashboard.html' });
+            } else if (userId.startsWith('personal_')) {
+                // Check if store owner or employee
+                const personalId = userId.replace('personal_', '');
+                database.database.get(
+                    'SELECT boss_id FROM boss WHERE boss_id = ?',
+                    [personalId],
+                    (err, boss) => {
+                        if (boss) {
+                            res.writeHead(302, { 'Location': '/store-owner.html' });
+                        } else {
+                            res.writeHead(302, { 'Location': '/store-employee.html' });
+                        }
+                        res.end();
+                    }
+                );
+                return;
+            } else {
+                res.writeHead(302, { 'Location': '/dashboard.html' });
+            }
+            res.end();
+            return;
+        }
+
         serveStaticFile(res, 'admin.html', 'text/html');
     } else if (pathname === '/store-owner.html') {
@@ -1089,5 +1376,5 @@
 
                 database.database.get(
-                    'SELECT store_id FROM store WHERE store_email = $1',
+                    'SELECT store_id FROM store WHERE store_email = ?',
                     [formData.storeEmail],
                     (err, existingStore) => {
@@ -1473,5 +1760,5 @@
                     // Insert into store table (store_id is VARCHAR)
                     database.database.run(
-                        'INSERT INTO store (store_id, name, date_of_founding, physical_address, store_email, rating) VALUES ($1, $2, $3, $4, $5, $6)',
+                        'INSERT INTO store (store_id, name, date_of_founding, physical_address, store_email, rating) VALUES (?, ?, ?, ?, ?, ?)',
                         [
                             tempStoreData.storeId,
@@ -1493,5 +1780,5 @@
                             // Insert into personal table (id is VARCHAR)
                             database.database.run(
-                                'INSERT INTO personal (id, first_name, last_name, ssn, email, password) VALUES ($1, $2, $3, $4, $5, $6)',
+                                'INSERT INTO personal (id, first_name, last_name, ssn, email, password) VALUES (?, ?, ?, ?, ?, ?)',
                                 [
                                     tempStoreData.personalId,
@@ -1521,5 +1808,5 @@
                                     // Insert into boss table (boss_id is VARCHAR, references personal.id)
                                     database.database.run(
-                                        'INSERT INTO boss (boss_id, signature) VALUES ($1, $2)',
+                                        'INSERT INTO boss (boss_id, signature) VALUES (?, ?)',
                                         [tempStoreData.personalId, tempStoreData.signature],
                                         (err) => {
@@ -1534,5 +1821,5 @@
                                             // Insert into works_in_store table (personal_id is VARCHAR, store_id is VARCHAR)
                                             database.database.run(
-                                                'INSERT INTO works_in_store (personal_id, store_id) VALUES ($1, $2)',
+                                                'INSERT INTO works_in_store (personal_id, store_id) VALUES (?, ?)',
                                                 [tempStoreData.personalId, tempStoreData.storeId],
                                                 (err) => {
@@ -1547,5 +1834,5 @@
                                                     // Insert into permissions table (personal_id is VARCHAR)
                                                     database.database.run(
-                                                        'INSERT INTO permissions (personal_id, type, authorisation) VALUES ($1, $2, $3)',
+                                                        'INSERT INTO permissions (personal_id, type, authorisation) VALUES (?, ?, ?)',
                                                         [tempStoreData.personalId, 'BOSS', 'full_access'],
                                                         (err) => {
@@ -1631,5 +1918,5 @@
                         if (tempUserData.address && tempUserData.city && tempUserData.postcode && tempUserData.country) {
                             database.database.run(
-                                'INSERT INTO delivery_address (client_id, address, city, postcode, country, is_default) VALUES ($1, $2, $3, $4, $5, $6)',
+                                'INSERT INTO delivery_address (client_id, address, city, postcode, country, is_default) VALUES (?, ?, ?, ?, ?, ?)',
                                 [
                                     clientId,
@@ -1665,5 +1952,4 @@
             } else {
                 const userId = 'user_' + Date.now().toString().slice(-8);
-
                 database.createUser(userId, tempUserData.username, tempUserData.email, tempUserData.password, tempUserData.userType, (err, userId) => {
                     if (err) {
@@ -1701,4 +1987,67 @@
 
             console.log(`🔍 Login attempt for email: ${email}`);
+
+            // First check if it's the admin user (special case)
+            if (email === 'admin@handcraft.com') {
+                database.getUserByUsername('admin', (err, adminUser) => {
+                    if (err || !adminUser) {
+                        console.error('Admin user not found');
+                        database.logAudit(null, 'LOGIN_FAILED', 'auth', null, `Admin login failed - user not found`, ipAddress);
+                        res.writeHead(401, { 'Content-Type': 'application/json' });
+                        res.end(JSON.stringify({ success: false, message: 'Invalid email or password' }));
+                        return;
+                    }
+
+                    if (database.verifyPassword(password, adminUser.password)) {
+                        const isFirstTimeLogin = adminUser.force_password_change === 1;
+
+                        const twoFACode = generateVerificationCode();
+
+                        verificationCodes.set(adminUser.email, {
+                            code: twoFACode,
+                            timestamp: Date.now(),
+                            userId: adminUser.id,
+                            isFirstTimeLogin: isFirstTimeLogin,
+                            userType: 'admin',
+                            needsPasswordChange: isFirstTimeLogin
+                        });
+
+                        console.log(`⏰ Generated 2FA code for admin ${adminUser.email}`);
+
+                        send2FACode(adminUser.email, twoFACode)
+                            .then(() => {
+                                res.writeHead(200, { 'Content-Type': 'application/json' });
+                                res.end(JSON.stringify({
+                                    success: true,
+                                    message: 'Two-factor authentication code sent to your email',
+                                    requires2FA: true,
+                                    email: adminUser.email,
+                                    username: adminUser.username,
+                                    isFirstTimeLogin: isFirstTimeLogin,
+                                    userType: 'admin'
+                                }));
+                            })
+                            .catch(error => {
+                                console.error('Error sending 2FA email:', error);
+                                res.writeHead(200, { 'Content-Type': 'application/json' });
+                                res.end(JSON.stringify({
+                                    success: true,
+                                    message: 'Two-factor authentication required',
+                                    requires2FA: true,
+                                    email: adminUser.email,
+                                    username: adminUser.username,
+                                    isFirstTimeLogin: isFirstTimeLogin,
+                                    userType: 'admin',
+                                    developmentCode: twoFACode
+                                }));
+                            });
+                    } else {
+                        database.logAudit(adminUser.id, 'LOGIN_FAILED', 'auth', adminUser.id.toString(), 'Invalid password for admin', ipAddress);
+                        res.writeHead(401, { 'Content-Type': 'application/json' });
+                        res.end(JSON.stringify({ success: false, message: 'Invalid email or password' }));
+                    }
+                });
+                return;
+            }
 
             // First check if it's a client
@@ -1733,5 +2082,4 @@
                         const sessionId = generateSessionId();
                         const clientId = client.client_ID;
-
                         sessions.set(sessionId, `client_${clientId}`);
 
@@ -1759,4 +2107,5 @@
                         }));
                     });
+
                     return;
                 }
@@ -1845,4 +2194,5 @@
                                             }
                                         );
+
                                         return;
                                     }
@@ -1905,4 +2255,5 @@
                                                     }
                                                 );
+
                                                 return;
                                             }
@@ -1924,6 +2275,5 @@
 
                                                             if (database.verifyPassword(password, userByUsername.password)) {
-                                                                const isAdminUser = userByUsername.username === 'admin';
-                                                                const isFirstTimeLogin = isAdminUser && userByUsername.force_password_change === 1;
+                                                                const isFirstTimeLogin = userByUsername.force_password_change === 1;
 
                                                                 const twoFACode = generateVerificationCode();
@@ -1934,5 +2284,5 @@
                                                                     userId: userByUsername.id,
                                                                     isFirstTimeLogin: isFirstTimeLogin,
-                                                                    userType: isAdminUser ? 'admin' : userByUsername.user_type,
+                                                                    userType: userByUsername.user_type,
                                                                     needsPasswordChange: isFirstTimeLogin
                                                                 });
@@ -1948,5 +2298,5 @@
                                                                             username: userByUsername.username,
                                                                             isFirstTimeLogin: isFirstTimeLogin,
-                                                                            userType: isAdminUser ? 'admin' : userByUsername.user_type
+                                                                            userType: userByUsername.user_type
                                                                         }));
                                                                     })
@@ -1961,5 +2311,5 @@
                                                                             username: userByUsername.username,
                                                                             isFirstTimeLogin: isFirstTimeLogin,
-                                                                            userType: isAdminUser ? 'admin' : userByUsername.user_type,
+                                                                            userType: userByUsername.user_type,
                                                                             developmentCode: twoFACode
                                                                         }));
@@ -1971,10 +2321,10 @@
                                                             }
                                                         });
+
                                                         return;
                                                     }
 
                                                     if (database.verifyPassword(password, user.password)) {
-                                                        const isAdminUser = user.username === 'admin';
-                                                        const isFirstTimeLogin = isAdminUser && user.force_password_change === 1;
+                                                        const isFirstTimeLogin = user.force_password_change === 1;
 
                                                         const twoFACode = generateVerificationCode();
@@ -1985,5 +2335,5 @@
                                                             userId: user.id,
                                                             isFirstTimeLogin: isFirstTimeLogin,
-                                                            userType: isAdminUser ? 'admin' : user.user_type,
+                                                            userType: user.user_type,
                                                             needsPasswordChange: isFirstTimeLogin
                                                         });
@@ -1999,5 +2349,5 @@
                                                                     username: user.username,
                                                                     isFirstTimeLogin: isFirstTimeLogin,
-                                                                    userType: isAdminUser ? 'admin' : user.user_type
+                                                                    userType: user.user_type
                                                                 }));
                                                             })
@@ -2012,5 +2362,5 @@
                                                                     username: user.username,
                                                                     isFirstTimeLogin: isFirstTimeLogin,
-                                                                    userType: isAdminUser ? 'admin' : user.user_type,
+                                                                    userType: user.user_type,
                                                                     developmentCode: twoFACode
                                                                 }));
@@ -2028,4 +2378,5 @@
                             );
                         });
+
                         return;
                     }
@@ -2056,5 +2407,5 @@
 
             database.database.get(
-                'SELECT * FROM users WHERE email = $1',
+                'SELECT * FROM users WHERE email = ?',
                 [email],
                 (err, user) => {
@@ -2073,6 +2424,6 @@
                                 timestamp: Date.now(),
                                 userId: userByUsername.id,
-                                isAdmin: userByUsername.username === 'admin' && userByUsername.force_password_change === 1,
-                                needsPasswordChange: userByUsername.username === 'admin' && userByUsername.force_password_change === 1,
+                                isFirstTimeLogin: userByUsername.force_password_change === 1,
+                                needsPasswordChange: userByUsername.force_password_change === 1,
                                 userType: userByUsername.user_type
                             });
@@ -2100,4 +2451,5 @@
                                 });
                         });
+
                         return;
                     }
@@ -2109,6 +2461,6 @@
                         timestamp: Date.now(),
                         userId: user.id,
-                        isAdmin: user.username === 'admin' && user.force_password_change === 1,
-                        needsPasswordChange: user.username === 'admin' && user.force_password_change === 1,
+                        isFirstTimeLogin: user.force_password_change === 1,
+                        needsPasswordChange: user.force_password_change === 1,
                         userType: user.user_type
                     });
@@ -2191,4 +2543,5 @@
                     redirectTo: 'change-password.html?forced=true'
                 }));
+
                 return;
             }
@@ -2272,20 +2625,94 @@
 
             if (tempAdminSessions.has(sessionId)) {
-                res.writeHead(200, { 'Content-Type': 'application/json' });
-                res.end(JSON.stringify({
-                    success: true,
-                    user: {
-                        id: userId,
-                        username: 'admin',
-                        needsPasswordChange: true
-                    },
-                    isTempSession: true
-                }));
-                return;
-            }
-
+                // This is a temporary session (password change required)
+                // Get user info to determine type
+                database.getUserById(userId, (err, user) => {
+                    if (err || !user) {
+                        // Check if it's a personal user
+                        database.getPersonalById(userId, (err, personal) => {
+                            if (err || !personal) {
+                                res.writeHead(200, { 'Content-Type': 'application/json' });
+                                res.end(JSON.stringify({
+                                    success: true,
+                                    user: {
+                                        id: userId,
+                                        username: 'admin',
+                                        userType: 'admin',
+                                        needsPasswordChange: true
+                                    },
+                                    isTempSession: true
+                                }));
+                            } else {
+                                // Personal user (store owner/employee)
+                                database.database.get(
+                                    'SELECT boss_id FROM boss WHERE boss_id = ?',
+                                    [userId],
+                                    (err, boss) => {
+                                        let userType = 'store_employee';
+                                        if (boss) {
+                                            userType = 'store_owner';
+                                        }
+
+                                        res.writeHead(200, { 'Content-Type': 'application/json' });
+                                        res.end(JSON.stringify({
+                                            success: true,
+                                            user: {
+                                                id: personal.id,
+                                                firstName: personal.first_name,
+                                                lastName: personal.last_name,
+                                                email: personal.email,
+                                                userType: userType,
+                                                needsPasswordChange: true
+                                            },
+                                            isTempSession: true
+                                        }));
+                                    }
+                                );
+                            }
+                        });
+                    } else {
+                        // Regular user (admin)
+                        res.writeHead(200, { 'Content-Type': 'application/json' });
+                        res.end(JSON.stringify({
+                            success: true,
+                            user: {
+                                id: user.id,
+                                username: user.username,
+                                email: user.email,
+                                userType: user.user_type || 'admin',
+                                needsPasswordChange: true
+                            },
+                            isTempSession: true
+                        }));
+                    }
+                });
+
+                return;
+            }
+
+            // Regular session
             const userIdStr = String(userId);
 
-            if (userIdStr.startsWith('client_')) {
+            if (userIdStr === '000000') {
+                // Admin user
+                database.getUserById(userIdStr, (err, user) => {
+                    if (err || !user) {
+                        res.writeHead(404, { 'Content-Type': 'application/json' });
+                        res.end(JSON.stringify({ success: false, message: 'User not found' }));
+                    } else {
+                        res.writeHead(200, { 'Content-Type': 'application/json' });
+                        res.end(JSON.stringify({
+                            success: true,
+                            user: {
+                                id: user.id,
+                                username: user.username,
+                                email: user.email,
+                                userType: 'admin'
+                            }
+                        }));
+                    }
+                });
+            }
+            else if (userIdStr.startsWith('client_')) {
                 const clientId = parseInt(userIdStr.replace('client_', ''));
 
@@ -2321,5 +2748,5 @@
 
                     database.database.get(
-                        'SELECT boss_id FROM boss WHERE boss_id = $1',
+                        'SELECT boss_id FROM boss WHERE boss_id = ?',
                         [personalId],
                         (err, boss) => {
@@ -2331,6 +2758,6 @@
                                 database.database.all(
                                     `SELECT s.* FROM store s
-                   JOIN works_in_store w ON s.store_id = w.store_id
-                   WHERE w.personal_id = $1`,
+                                     JOIN works_in_store w ON s.store_id = w.store_id
+                                     WHERE w.personal_id = ?`,
                                     [personalId],
                                     (err, stores) => {
@@ -2356,5 +2783,5 @@
                             } else {
                                 database.database.get(
-                                    'SELECT employee_id FROM employees WHERE employee_id = $1',
+                                    'SELECT employee_id FROM employees WHERE employee_id = ?',
                                     [personalId],
                                     (err, employee) => {
@@ -2366,6 +2793,6 @@
                                             database.database.all(
                                                 `SELECT s.* FROM store s
-                         JOIN works_in_store w ON s.store_id = w.store_id
-                         WHERE w.personal_id = $1`,
+                                                 JOIN works_in_store w ON s.store_id = w.store_id
+                                                 WHERE w.personal_id = ?`,
                                                 [personalId],
                                                 (err, stores) => {
@@ -2559,6 +2986,6 @@
 
                     database.database.get(
-                        'SELECT COUNT(*) as order_count FROM "order" WHERE store_id = $1 AND EXTRACT(YEAR FROM order_date) = $2',
-                        [storeId, new Date().getFullYear()],
+                        'SELECT COUNT(*) as order_count FROM "order" WHERE store_id = ? AND strftime("%Y", order_date) = ?',
+                        [storeId, new Date().getFullYear().toString()],
                         (err, result) => {
                             if (err) {
@@ -2569,5 +2996,5 @@
                             }
 
-                            const orderCount = result && result[0] ? parseInt(result[0].order_count) + 1 : 1;
+                            const orderCount = result ? result.order_count + 1 : 1;
                             const orderNumPadded = orderCount.toString().padStart(5, '0');
 
@@ -2693,6 +3120,6 @@
 
                     database.database.get(
-                        'SELECT COUNT(*) as request_count FROM request WHERE store_id = $1 AND EXTRACT(YEAR FROM date_and_time) = $2 AND EXTRACT(MONTH FROM date_and_time) = $3',
-                        [storeId, now.getFullYear(), now.getMonth() + 1],
+                        'SELECT COUNT(*) as request_count FROM request WHERE store_id = ? AND strftime("%Y", date_and_time) = ? AND strftime("%m", date_and_time) = ?',
+                        [storeId, now.getFullYear().toString(), (now.getMonth() + 1).toString().padStart(2, '0')],
                         (err, result) => {
                             if (err) {
@@ -2703,5 +3130,5 @@
                             }
 
-                            const requestCount = result && result[0] ? parseInt(result[0].request_count) + 1 : 1;
+                            const requestCount = result ? result.request_count + 1 : 1;
                             const requestSeqPadded = requestCount.toString().padStart(2, '0');
 
@@ -2752,8 +3179,8 @@
 
                     database.database.get(
-                        'SELECT store_id FROM "order" WHERE order_num = $1',
+                        'SELECT store_id FROM "order" WHERE order_num = ?',
                         [refundData.order_num],
                         (err, result) => {
-                            if (err || !result || result.length === 0) {
+                            if (err || !result) {
                                 res.writeHead(404, { 'Content-Type': 'application/json' });
                                 res.end(JSON.stringify({ success: false, message: 'Order not found' }));
@@ -2761,5 +3188,5 @@
                             }
 
-                            const storeId = result[0].store_id;
+                            const storeId = result.store_id;
                             const now = new Date();
                             const month = (now.getMonth() + 1).toString().padStart(2, '0');
@@ -2767,6 +3194,6 @@
 
                             database.database.get(
-                                'SELECT COUNT(*) as refund_count FROM refund WHERE EXTRACT(YEAR FROM request_date) = $1 AND EXTRACT(MONTH FROM request_date) = $2',
-                                [now.getFullYear(), now.getMonth() + 1],
+                                'SELECT COUNT(*) as refund_count FROM refund WHERE strftime("%Y", request_date) = ? AND strftime("%m", request_date) = ?',
+                                [now.getFullYear().toString(), (now.getMonth() + 1).toString().padStart(2, '0')],
                                 (err, result) => {
                                     if (err) {
@@ -2777,5 +3204,5 @@
                                     }
 
-                                    const refundCount = result && result[0] ? parseInt(result[0].refund_count) + 1 : 1;
+                                    const refundCount = result ? result.refund_count + 1 : 1;
                                     const refundSeqPadded = refundCount.toString().padStart(2, '0');
 
@@ -2818,5 +3245,5 @@
 
                 database.database.get(
-                    'SELECT store_id FROM works_in_store WHERE personal_id = $1',
+                    'SELECT store_id FROM works_in_store WHERE personal_id = ?',
                     [personalId],
                     (err, bossStore) => {
@@ -2836,5 +3263,5 @@
 
                         database.database.get(
-                            'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                            'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                             [personalId, storeId],
                             (err, ownsStore) => {
@@ -2847,5 +3274,5 @@
                                 // FIXED: Changed SQL syntax from SUBSTRING(code FROM 4) to SUBSTR(code, 4) for SQLite compatibility
                                 database.database.get(
-                                    'SELECT MAX(CAST(SUBSTR(code, 4) AS INTEGER)) as max_product_num FROM product WHERE store_id = $1',
+                                    'SELECT MAX(CAST(SUBSTR(code, 4) AS INTEGER)) as max_product_num FROM product WHERE store_id = ?',
                                     [storeId],
                                     (err, result) => {
@@ -2881,5 +3308,4 @@
                                             } else {
                                                 database.logAudit(personalId, 'PRODUCT_ADDED', 'product', productId.toString(), 'New product added', ipAddress);
-
                                                 res.writeHead(200, { 'Content-Type': 'application/json' });
                                                 res.end(JSON.stringify({
@@ -2918,5 +3344,5 @@
 
                 database.database.get(
-                    'SELECT store_id FROM product WHERE code = $1',
+                    'SELECT store_id FROM product WHERE code = ?',
                     [productData.code],
                     (err, product) => {
@@ -2928,5 +3354,5 @@
 
                         database.database.get(
-                            'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                            'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                             [personalId, product.store_id],
                             (err, ownsStore) => {
@@ -3013,4 +3439,5 @@
 
         let body = '';
+
         req.on('data', chunk => {
             body += chunk.toString();
@@ -3018,67 +3445,191 @@
 
         req.on('end', () => {
-            const { currentPassword, newPassword, confirmPassword } = JSON.parse(body);
-
-            if (!currentPassword || !newPassword || !confirmPassword) {
-                res.writeHead(400, { 'Content-Type': 'application/json' });
-                res.end(JSON.stringify({ success: false, message: 'All fields are required' }));
-                return;
-            }
-
-            if (newPassword !== confirmPassword) {
-                res.writeHead(400, { 'Content-Type': 'application/json' });
-                res.end(JSON.stringify({ success: false, message: 'New passwords do not match' }));
-                return;
-            }
-
-            if (!validatePassword(newPassword)) {
-                res.writeHead(400, { 'Content-Type': 'application/json' });
-                res.end(JSON.stringify({
-                    success: false,
-                    message: 'Password must have at least 8 characters, including uppercase, lowercase, number and special character'
-                }));
-                return;
-            }
-
-            database.getUserByUsername('admin', (err, user) => {
-                if (err || !user) {
-                    res.writeHead(404, { 'Content-Type': 'application/json' });
-                    res.end(JSON.stringify({ success: false, message: 'User not found' }));
+            try {
+                const { newPassword, confirmPassword } = JSON.parse(body);
+
+                if (!newPassword || !confirmPassword) {
+                    res.writeHead(400, { 'Content-Type': 'application/json' });
+                    res.end(JSON.stringify({ success: false, message: 'All fields are required' }));
                     return;
                 }
 
-                database.verifyPassword(currentPassword, user.password, (err, isValid) => {
-                    if (err || !isValid) {
-                        res.writeHead(400, { 'Content-Type': 'application/json' });
-                        res.end(JSON.stringify({ success: false, message: 'Current password is incorrect' }));
-                        return;
-                    }
-
-                    database.updatePasswordAndClearForce(userId, newPassword, (err) => {
-                        if (err) {
-                            res.writeHead(500, { 'Content-Type': 'application/json' });
-                            res.end(JSON.stringify({ success: false, message: 'Failed to update password' }));
-                        } else {
-                            tempAdminSessions.delete(sessionId);
-
-                            const newSessionId = generateSessionId();
-                            sessions.set(newSessionId, String(userId));
-
-                            database.logAudit(userId, 'FORCED_PASSWORD_CHANGE', 'auth', userId.toString(),
-                                'Admin forced password change completed', ipAddress);
-
-                            res.writeHead(200, {
-                                'Content-Type': 'application/json',
-                                'Set-Cookie': `sessionId=${newSessionId}; HttpOnly; Path=/; Max-Age=3600; SameSite=Strict`
-                            });
-                            res.end(JSON.stringify({
-                                success: true,
-                                message: 'Password changed successfully. You can now access the dashboard.',
-                                redirectTo: 'admin.html'
-                            }));
-                        }
-                    });
+                if (newPassword !== confirmPassword) {
+                    res.writeHead(400, { 'Content-Type': 'application/json' });
+                    res.end(JSON.stringify({ success: false, message: 'New passwords do not match' }));
+                    return;
+                }
+
+                if (!validatePassword(newPassword)) {
+                    res.writeHead(400, { 'Content-Type': 'application/json' });
+                    res.end(JSON.stringify({
+                        success: false,
+                        message: 'Password must have at least 8 characters, including uppercase, lowercase, number and special character'
+                    }));
+                    return;
+                }
+
+                // First, try to find the user in the users table (for admin)
+                database.getUserById(userId, (err, user) => {
+                    if (err) {
+                        console.error('Error finding user by ID:', err);
+                    }
+
+                    if (user) {
+                        // Found in users table (admin or regular user)
+                        console.log('Found user in users table:', user);
+
+                        const hashedPassword = bcrypt.hashSync(newPassword, 10);
+
+                        database.database.run(
+                            'UPDATE users SET password = ?, force_password_change = 0 WHERE id = ?',
+                            [hashedPassword, userId],
+                            function(err) {
+                                if (err) {
+                                    console.error('Error updating password:', err);
+                                    res.writeHead(500, { 'Content-Type': 'application/json' });
+                                    res.end(JSON.stringify({ success: false, message: 'Failed to update password' }));
+                                    return;
+                                }
+
+                                // Also update password in personal table if it exists (for admin)
+                                database.database.run(
+                                    'UPDATE personal SET password = ? WHERE id = ?',
+                                    [hashedPassword, userId],
+                                    function(err) {
+                                        if (err) {
+                                            console.log('No personal record to update for ID:', userId);
+                                        }
+                                    }
+                                );
+
+                                // Clear temp session
+                                tempAdminSessions.delete(sessionId);
+
+                                // Create new permanent session
+                                const newSessionId = generateSessionId();
+                                sessions.set(newSessionId, String(userId));
+
+                                // Determine redirect based on user type
+                                let redirectTo = 'dashboard.html';
+
+                                if (user.username === 'admin' || user.user_type === 'admin') {
+                                    redirectTo = 'admin.html';
+                                } else if (user.user_type === 'store_owner') {
+                                    redirectTo = 'store-owner.html';
+                                } else if (user.user_type === 'store_employee') {
+                                    redirectTo = 'store-employee.html';
+                                } else if (user.user_type === 'client') {
+                                    redirectTo = 'client-dashboard.html';
+                                }
+
+                                console.log(`Password changed successfully for user ${userId}, redirecting to ${redirectTo}`);
+
+                                database.logAudit(userId, 'FORCED_PASSWORD_CHANGE', 'auth', userId.toString(),
+                                    `${user.user_type || 'user'} forced password change completed`, ipAddress);
+
+                                // Set the cookie with proper options
+                                res.writeHead(200, {
+                                    'Content-Type': 'application/json',
+                                    'Set-Cookie': `sessionId=${newSessionId}; HttpOnly; Path=/; Max-Age=3600; SameSite=Strict`
+                                });
+                                res.end(JSON.stringify({
+                                    success: true,
+                                    message: 'Password changed successfully.',
+                                    redirectTo: redirectTo,
+                                    userType: user.user_type || 'user'
+                                }));
+                            }
+                        );
+                    } else {
+                        // Not found in users table, check personal table (for store owners/employees)
+                        console.log('User not found in users table, checking personal table for ID:', userId);
+
+                        database.getPersonalById(userId, (err, personal) => {
+                            if (err) {
+                                console.error('Error finding personal by ID:', err);
+                            }
+
+                            if (personal) {
+                                console.log('Found user in personal table:', personal);
+
+                                // Update password in personal table
+                                const hashedPassword = bcrypt.hashSync(newPassword, 10);
+
+                                database.database.run(
+                                    'UPDATE personal SET password = ? WHERE id = ?',
+                                    [hashedPassword, userId],
+                                    function(err) {
+                                        if (err) {
+                                            console.error('Error updating personal password:', err);
+                                            res.writeHead(500, { 'Content-Type': 'application/json' });
+                                            res.end(JSON.stringify({ success: false, message: 'Failed to update password' }));
+                                            return;
+                                        }
+
+                                        // Also update in users table if exists
+                                        database.database.run(
+                                            'UPDATE users SET password = ?, force_password_change = 0 WHERE email = ?',
+                                            [hashedPassword, personal.email],
+                                            function(err) {
+                                                if (err) {
+                                                    console.log('No users record to update for email:', personal.email);
+                                                }
+                                            }
+                                        );
+
+                                        // Determine user type (boss/owner or employee)
+                                        database.database.get(
+                                            'SELECT boss_id FROM boss WHERE boss_id = ?',
+                                            [userId],
+                                            (err, boss) => {
+                                                let userType = 'store_employee';
+                                                let redirectTo = 'store-employee.html';
+
+                                                if (boss) {
+                                                    userType = 'store_owner';
+                                                    redirectTo = 'store-owner.html';
+                                                }
+
+                                                // Clear temp session
+                                                tempAdminSessions.delete(sessionId);
+
+                                                // Create new permanent session
+                                                const newSessionId = generateSessionId();
+                                                sessions.set(newSessionId, `personal_${userId}`);
+
+                                                console.log(`Password changed successfully for ${userType} ${userId}, redirecting to ${redirectTo}`);
+
+                                                database.logAudit(userId, 'FORCED_PASSWORD_CHANGE', 'auth', userId.toString(),
+                                                    `${userType} forced password change completed`, ipAddress);
+
+                                                // Set the cookie with proper options
+                                                res.writeHead(200, {
+                                                    'Content-Type': 'application/json',
+                                                    'Set-Cookie': `sessionId=${newSessionId}; HttpOnly; Path=/; Max-Age=3600; SameSite=Strict`
+                                                });
+                                                res.end(JSON.stringify({
+                                                    success: true,
+                                                    message: 'Password changed successfully.',
+                                                    redirectTo: redirectTo,
+                                                    userType: userType
+                                                }));
+                                            }
+                                        );
+                                    }
+                                );
+                            } else {
+                                // User not found in any table
+                                console.error('User not found in any table with ID:', userId);
+                                res.writeHead(404, { 'Content-Type': 'application/json' });
+                                res.end(JSON.stringify({ success: false, message: 'User not found' }));
+                            }
+                        });
+                    }
                 });
-            });
+            } catch (parseError) {
+                console.error('JSON parse error:', parseError);
+                res.writeHead(400, { 'Content-Type': 'application/json' });
+                res.end(JSON.stringify({ success: false, message: 'Invalid request format' }));
+            }
         });
     }
@@ -3088,4 +3639,11 @@
             const userIdStr = String(userId);
 
+            // Check if this is the admin user
+            if (userIdStr === '000000') {
+                res.writeHead(403, { 'Content-Type': 'application/json' });
+                res.end(JSON.stringify({ success: false, message: 'Only store owners can register employees' }));
+                return;
+            }
+
             if (!userIdStr.startsWith('personal_')) {
                 res.writeHead(403, { 'Content-Type': 'application/json' });
@@ -3097,5 +3655,5 @@
 
             database.database.get(
-                'SELECT boss_id FROM boss WHERE boss_id = $1',
+                'SELECT boss_id FROM boss WHERE boss_id = ?',
                 [personalId],
                 (err, boss) => {
@@ -3204,5 +3762,5 @@
 
                                         database.database.run(
-                                            'INSERT INTO personal (id, first_name, last_name, ssn, email, password) VALUES ($1, $2, $3, $4, $5, $6)',
+                                            'INSERT INTO personal (id, first_name, last_name, ssn, email, password) VALUES (?, ?, ?, ?, ?, ?)',
                                             [
                                                 newPersonalId,
@@ -3228,5 +3786,5 @@
 
                                                 database.database.run(
-                                                    'INSERT INTO employees (employee_id, date_of_hire) VALUES ($1, $2)',
+                                                    'INSERT INTO employees (employee_id, date_of_hire) VALUES (?, ?)',
                                                     [newPersonalId, dateOfHire],
                                                     (err) => {
@@ -3240,5 +3798,5 @@
 
                                                         database.database.run(
-                                                            'INSERT INTO works_in_store (personal_id, store_id) VALUES ($1, $2)',
+                                                            'INSERT INTO works_in_store (personal_id, store_id) VALUES (?, ?)',
                                                             [newPersonalId, storeId],
                                                             (err) => {
@@ -3252,5 +3810,5 @@
 
                                                                 database.database.run(
-                                                                    'INSERT INTO permissions (personal_id, type, authorisation) VALUES ($1, $2, $3)',
+                                                                    'INSERT INTO permissions (personal_id, type, authorisation) VALUES (?, ?, ?)',
                                                                     [newPersonalId, 'EMPLOYEE', 'limited_access'],
                                                                     (err) => {
@@ -3300,4 +3858,11 @@
             const userIdStr = String(userId);
 
+            // Check if this is the admin user
+            if (userIdStr === '000000') {
+                res.writeHead(403, { 'Content-Type': 'application/json' });
+                res.end(JSON.stringify({ success: false, message: 'Only store owners can delete employees' }));
+                return;
+            }
+
             if (!userIdStr.startsWith('personal_')) {
                 res.writeHead(403, { 'Content-Type': 'application/json' });
@@ -3309,5 +3874,5 @@
 
             database.database.get(
-                'SELECT boss_id FROM boss WHERE boss_id = $1',
+                'SELECT boss_id FROM boss WHERE boss_id = ?',
                 [personalId],
                 (err, boss) => {
@@ -3333,5 +3898,5 @@
 
                         database.database.get(
-                            'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                            'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                             [personalId, storeId],
                             (err, bossStore) => {
@@ -3343,5 +3908,5 @@
 
                                 database.database.get(
-                                    'SELECT personal_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                                    'SELECT personal_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                                     [employeeId, storeId],
                                     (err, employeeStore) => {
@@ -3353,5 +3918,5 @@
 
                                         database.database.get(
-                                            'SELECT boss_id FROM boss WHERE boss_id = $1',
+                                            'SELECT boss_id FROM boss WHERE boss_id = ?',
                                             [employeeId],
                                             (err, isBoss) => {
@@ -3375,5 +3940,5 @@
 
                                                     database.database.run(
-                                                        'DELETE FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                                                        'DELETE FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                                                         [employeeId, storeId],
                                                         (err) => {
@@ -3387,5 +3952,5 @@
 
                                                             database.database.run(
-                                                                'DELETE FROM employees WHERE employee_id = $1',
+                                                                'DELETE FROM employees WHERE employee_id = ?',
                                                                 [employeeId],
                                                                 (err) => {
@@ -3395,5 +3960,5 @@
 
                                                                     database.database.run(
-                                                                        'DELETE FROM permissions WHERE personal_id = $1',
+                                                                        'DELETE FROM permissions WHERE personal_id = ?',
                                                                         [employeeId],
                                                                         (err) => {
@@ -3403,5 +3968,5 @@
 
                                                                             database.database.run(
-                                                                                'DELETE FROM personal WHERE id = $1',
+                                                                                'DELETE FROM personal WHERE id = ?',
                                                                                 [employeeId],
                                                                                 (err) => {
@@ -3452,4 +4017,11 @@
             const userIdStr = String(userId);
 
+            // Check if this is the admin user
+            if (userIdStr === '000000') {
+                res.writeHead(403, { 'Content-Type': 'application/json' });
+                res.end(JSON.stringify({ success: false, message: 'Only store owners can update employee status' }));
+                return;
+            }
+
             if (!userIdStr.startsWith('personal_')) {
                 res.writeHead(403, { 'Content-Type': 'application/json' });
@@ -3461,5 +4033,5 @@
 
             database.database.get(
-                'SELECT boss_id FROM boss WHERE boss_id = $1',
+                'SELECT boss_id FROM boss WHERE boss_id = ?',
                 [personalId],
                 (err, boss) => {
@@ -3485,5 +4057,5 @@
 
                         database.database.get(
-                            'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                            'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                             [personalId, storeId],
                             (err, bossStore) => {
@@ -3495,5 +4067,5 @@
 
                                 database.database.get(
-                                    'SELECT personal_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                                    'SELECT personal_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                                     [employeeId, storeId],
                                     (err, employeeStore) => {
@@ -3519,5 +4091,5 @@
 
                                         database.database.run(
-                                            'UPDATE permissions SET type = $1, authorisation = $2 WHERE personal_id = $3',
+                                            'UPDATE permissions SET type = ?, authorisation = ? WHERE personal_id = ?',
                                             [permissionType, authorization, employeeId],
                                             function(err) {
@@ -3552,4 +4124,11 @@
             const userIdStr = String(userId);
 
+            // Check if this is the admin user
+            if (userIdStr === '000000') {
+                res.writeHead(403, { 'Content-Type': 'application/json' });
+                res.end(JSON.stringify({ success: false, message: 'Only store owners can update employees' }));
+                return;
+            }
+
             if (!userIdStr.startsWith('personal_')) {
                 res.writeHead(403, { 'Content-Type': 'application/json' });
@@ -3561,5 +4140,5 @@
 
             database.database.get(
-                'SELECT boss_id FROM boss WHERE boss_id = $1',
+                'SELECT boss_id FROM boss WHERE boss_id = ?',
                 [personalId],
                 (err, boss) => {
@@ -3585,5 +4164,5 @@
 
                         database.database.get(
-                            'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                            'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                             [personalId, storeId],
                             (err, bossStore) => {
@@ -3595,5 +4174,5 @@
 
                                 database.database.get(
-                                    'SELECT personal_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                                    'SELECT personal_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                                     [employeeId, storeId],
                                     (err, employeeStore) => {
@@ -3608,10 +4187,10 @@
 
                                         if (firstName) {
-                                            updates.push('first_name = $' + (params.length + 1));
+                                            updates.push('first_name = ?');
                                             params.push(firstName);
                                         }
 
                                         if (lastName) {
-                                            updates.push('last_name = $' + (params.length + 1));
+                                            updates.push('last_name = ?');
                                             params.push(lastName);
                                         }
@@ -3623,5 +4202,5 @@
                                                 return;
                                             }
-                                            updates.push('email = $' + (params.length + 1));
+                                            updates.push('email = ?');
                                             params.push(email);
                                         }
@@ -3636,5 +4215,5 @@
 
                                         database.database.run(
-                                            `UPDATE personal SET ${updates.join(', ')} WHERE id = $${params.length}`,
+                                            `UPDATE personal SET ${updates.join(', ')} WHERE id = ?`,
                                             params,
                                             function(err) {
@@ -3671,5 +4250,5 @@
             if (!storeId) {
                 database.database.get(
-                    'SELECT store_id FROM works_in_store WHERE personal_id = $1 LIMIT 1',
+                    'SELECT store_id FROM works_in_store WHERE personal_id = ? LIMIT 1',
                     [personalId],
                     (err, store) => {
@@ -3691,9 +4270,10 @@
                     }
                 );
+
                 return;
             }
 
             database.database.get(
-                'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                 [personalId, storeId],
                 (err, ownsStore) => {
@@ -3724,5 +4304,5 @@
             if (!storeId) {
                 database.database.get(
-                    'SELECT store_id FROM works_in_store WHERE personal_id = $1 LIMIT 1',
+                    'SELECT store_id FROM works_in_store WHERE personal_id = ? LIMIT 1',
                     [personalId],
                     (err, store) => {
@@ -3744,9 +4324,10 @@
                     }
                 );
+
                 return;
             }
 
             database.database.get(
-                'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                 [personalId, storeId],
                 (err, ownsStore) => {
@@ -3777,5 +4358,5 @@
             if (!storeId) {
                 database.database.get(
-                    'SELECT store_id FROM works_in_store WHERE personal_id = $1 LIMIT 1',
+                    'SELECT store_id FROM works_in_store WHERE personal_id = ? LIMIT 1',
                     [personalId],
                     (err, store) => {
@@ -3797,9 +4378,10 @@
                     }
                 );
+
                 return;
             }
 
             database.database.get(
-                'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                 [personalId, storeId],
                 (err, ownsStore) => {
@@ -3830,5 +4412,5 @@
             if (!storeId) {
                 database.database.get(
-                    'SELECT store_id FROM works_in_store WHERE personal_id = $1 LIMIT 1',
+                    'SELECT store_id FROM works_in_store WHERE personal_id = ? LIMIT 1',
                     [personalId],
                     (err, store) => {
@@ -3850,9 +4432,10 @@
                     }
                 );
+
                 return;
             }
 
             database.database.get(
-                'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                 [personalId, storeId],
                 (err, ownsStore) => {
@@ -3883,5 +4466,5 @@
             if (!storeId) {
                 database.database.get(
-                    'SELECT store_id FROM works_in_store WHERE personal_id = $1 LIMIT 1',
+                    'SELECT store_id FROM works_in_store WHERE personal_id = ? LIMIT 1',
                     [personalId],
                     (err, store) => {
@@ -3903,9 +4486,10 @@
                     }
                 );
+
                 return;
             }
 
             database.database.get(
-                'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                 [personalId, storeId],
                 (err, ownsStore) => {
@@ -3934,4 +4518,11 @@
             const userIdStr = String(userId);
 
+            // Check if this is the admin user
+            if (userIdStr === '000000') {
+                res.writeHead(403, { 'Content-Type': 'application/json' });
+                res.end(JSON.stringify({ success: false, message: 'Only store employees can access this endpoint' }));
+                return;
+            }
+
             if (!userIdStr.startsWith('personal_')) {
                 res.writeHead(403, { 'Content-Type': 'application/json' });
@@ -4002,5 +4593,5 @@
 
                 database.database.get(
-                    'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                    'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                     [personalId, storeId],
                     (err, ownsStore) => {
@@ -4072,5 +4663,5 @@
 
                 database.database.get(
-                    'SELECT store_id FROM works_in_store WHERE personal_id = $1 AND store_id = $2',
+                    'SELECT store_id FROM works_in_store WHERE personal_id = ? AND store_id = ?',
                     [personalId, storeId],
                     (err, ownsStore) => {
@@ -4084,5 +4675,5 @@
 
                         database.database.run(
-                            'INSERT INTO report (id, store_id, period, start_date, end_date, type, generated_by, generated_at) VALUES ($1, $2, $3, $4, $5, $6, $7, CURRENT_TIMESTAMP)',
+                            'INSERT INTO report (id, store_id, period, start_date, end_date, type, generated_by, generated_at) VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)',
                             [reportId, storeId, period, startDate, endDate, type, personalId],
                             function(err) {
