aboutsummaryrefslogtreecommitdiffstats
path: root/source/resources/js/company/company.js
blob: 372939b0e5026f1015aad72ec607c7edb8229194 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
'use strict';

// function to render home section
function renderHome() {
    // update active button
    document.querySelectorAll('.nav-links a').forEach(button => button.classList.remove('active'));
    document.getElementById('homeBtn').classList.add('active');

    // show home content, hide others
    document.querySelectorAll('.content-container').forEach(section => section.classList.remove('active'));
    document.getElementById('home-content').classList.add('active');
}

// function to render messages section
function renderMessages() {
    // update active button
    document.querySelectorAll('.nav-links a').forEach(button => button.classList.remove('active'));
    document.getElementById('messageBtn').classList.add('active');

    // show messages content, hide others
    document.querySelectorAll('.content-container').forEach(section => section.classList.remove('active'));
    document.getElementById('messages-content').classList.add('active');

    // remove active class from all message list items
    document.querySelectorAll('.message-company').forEach(item => item.classList.remove('active'));

    // show empty state and hide chat
    const chatSection = document.getElementById('chat-section');
    const emptyContainer = chatSection.querySelector('.empty-chat-container');
    const chatContainer = chatSection.querySelector('.chat-container');

    emptyContainer.classList.add('active');
    chatContainer.classList.remove('active');
}

// function to render calendar section
function renderCalendar() {
    // update active button
    document.querySelectorAll('.nav-links a').forEach(button => button.classList.remove('active'));
    document.getElementById('calendarBtn').classList.add('active');

    // show calendar content, hide others
    document.querySelectorAll('.content-container').forEach(section => section.classList.remove('active'));
    document.getElementById('calendar-content').classList.add('active');
}

// function to render settings section
function renderSettings() {
    // hide all content containers
    document.querySelectorAll('.content-container').forEach(section => section.classList.remove('active'));
    document.getElementById('settings-content').classList.add('active');

    // remove active class from nav links
    document.querySelectorAll('.nav-links a').forEach(button => button.classList.remove('active'));
}

// function to handle student selection in chat
function handleStudentSelection() {
    document.querySelectorAll('.message-contact').forEach(studentMatch => {
        studentMatch.addEventListener('click', function() {
            // remove active class from all matches
            document.querySelectorAll('.message-contact').forEach(match => match.classList.remove('active'));

            // add active class to clicked match
            this.classList.add('active');

            // hide empty state and show chat
            const chatSection = document.getElementById('chat-section');
            const emptyContainer = chatSection.querySelector('.empty-chat-container');
            const chatContainer = chatSection.querySelector('.chat-container');

            emptyContainer.classList.remove('active');
            chatContainer.classList.add('active');
              // get student data
            const studentId = this.dataset.userId;
            const studentType = this.dataset.userType;
            const studentName = this.querySelector('.contact-info h4').textContent;

            // set hidden form fields
            document.getElementById('current-student-id').value = studentId;

            // dispatch custom event for chat handler
            window.dispatchEvent(new CustomEvent('studentSelected', {
                detail: { studentId: studentId }
            }));
        });
    });
}

// function to handle profile dropdown
function handleProfileDropdown() {
    const profileArea = document.getElementById('profileArea');
    const profileDropdown = document.getElementById('profileDropdown');

    if (profileArea && profileDropdown) {
        profileArea.addEventListener('click', function(e) {
            e.stopPropagation();
            profileDropdown.classList.toggle('show');
        });

        // Close dropdown when clicking outside
        document.addEventListener('click', function(e) {
            if (!profileArea.contains(e.target)) {
                profileDropdown.classList.remove('show');
            }
        });
    }
}

// function to handle settings navigation
function handleSettingsNavigation() {
    const profileSettingsBtn = document.getElementById('profileSettingsBtn');
    const preferencesBtn = document.getElementById('preferencesBtn');
    const themeBtn = document.getElementById('themeBtn');

    if (profileSettingsBtn) {
        profileSettingsBtn.addEventListener('click', function() {
            document.querySelectorAll('.settings-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.settings-panel').forEach(panel => panel.classList.remove('active'));

            this.classList.add('active');
            document.getElementById('profile-settings').classList.add('active');
        });
    }

    if (preferencesBtn) {
        preferencesBtn.addEventListener('click', function() {
            document.querySelectorAll('.settings-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.settings-panel').forEach(panel => panel.classList.remove('active'));

            this.classList.add('active');
            document.getElementById('preferences-settings').classList.add('active');
        });
    }

    if (themeBtn) {
        themeBtn.addEventListener('click', function() {
            document.querySelectorAll('.settings-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.settings-panel').forEach(panel => panel.classList.remove('active'));

            this.classList.add('active');
            document.getElementById('theme-settings').classList.add('active');
        });
    }

    // handle theme selection
    document.querySelectorAll('.theme-option').forEach(option => {
        option.addEventListener('click', function() {
            document.querySelectorAll('.theme-option').forEach(opt => opt.classList.remove('active'));
            this.classList.add('active');
            const selectedTheme = this.dataset.theme;
            applyTheme(selectedTheme);
        });
    });
}

// Profile settings change tracking
let originalProfileData = {};
let hasUnsavedChanges = false;

function profileChangeTracking() {
    // Store original values
    const profileInputs = document.querySelectorAll('#profile-settings input, #profile-settings select, #profile-settings textarea');
    profileInputs.forEach(input => {
        originalProfileData[input.id] = input.value;
    });

    // Add change listeners
    profileInputs.forEach(input => {
        input.addEventListener('input', handleProfileChange);
        input.addEventListener('change', handleProfileChange);
    });

    // Add save button handler
    const saveBtn = document.querySelector('#profile-settings .save-btn');
    if (saveBtn) {
        saveBtn.addEventListener('click', handleProfileSave);
    }

    // Add undo button handler
    const undoBtn = document.getElementById('undoChangesBtn');
    if (undoBtn) {
        undoBtn.addEventListener('click', handleProfileUndo);
    }
}

function handleProfileChange() {
    const profilePanel = document.getElementById('profile-settings');
    const undoBtn = document.getElementById('undoChangesBtn');
    let hasChanges = false;

    // Check if any field has changed
    const profileInputs = document.querySelectorAll('#profile-settings input, #profile-settings select, #profile-settings textarea');
    profileInputs.forEach(input => {
        if (input.value !== originalProfileData[input.id]) {
            hasChanges = true;
            input.classList.add('changed');
        } else {
            input.classList.remove('changed');
        }
    });

    hasUnsavedChanges = hasChanges;

    if (hasChanges) {
        profilePanel.classList.add('profile-settings-changed');
        undoBtn.style.display = 'inline-block';
    } else {
        profilePanel.classList.remove('profile-settings-changed');
        undoBtn.style.display = 'none';
    }
}

function handleProfileSave(e) {
    e.preventDefault();

    // Get current company ID from URL or data attribute
    const currentUrl = window.location.pathname;
    const companyId = currentUrl.split('/').pop();

    // Collect form data
    const formData = {
        name: document.getElementById('companyName').value,
        job_domain: document.getElementById('jobDomain').value,
        job_types: document.getElementById('jobTypes').value,
        booth_location: document.getElementById('boothLocation').value,
        plan_type: document.getElementById('planType').value,
        company_description: document.getElementById('companyDescription').value,
        job_description: document.getElementById('jobDescription').value,
        job_requirements: document.getElementById('jobRequirements').value,
        speeddate_duration: document.getElementById('speeddateDuration').value
    };

    // Send PATCH request
    fetch(`/company/${companyId}`, {
        method: 'PATCH',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
        },
        body: JSON.stringify(formData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Update original data and reset change tracking
            Object.keys(formData).forEach(key => {
                const input = document.getElementById(key === 'name' ? 'companyName' : key);
                if (input) {
                    originalProfileData[input.id] = input.value;
                }
            });
            resetProfileChangeTracking();

            // Show success message
            alert('Profile updated successfully!');
        } else {
            alert('Error updating profile: ' + (data.message || 'Unknown error'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error updating profile. Please try again.');
    });
}

function handleProfileUndo() {
    // Restore original values
    Object.keys(originalProfileData).forEach(fieldId => {
        const field = document.getElementById(fieldId);
        if (field) {
            field.value = originalProfileData[fieldId];
        }
    });

    resetProfileChangeTracking();
}

function resetProfileChangeTracking() {
    hasUnsavedChanges = false;
    const profilePanel = document.getElementById('profile-settings');
    const undoBtn = document.getElementById('undoChangesBtn');

    profilePanel.classList.remove('profile-settings-changed');
    undoBtn.style.display = 'none';

    // Remove changed class from all inputs
    document.querySelectorAll('#profile-settings input, #profile-settings select, #profile-settings textarea').forEach(input => {
        input.classList.remove('changed');
    });
}

function preventNavigationIfUnsaved(callback) {
    if (hasUnsavedChanges) {
        if (confirm('You have unsaved changes. Are you sure you want to leave this section?')) {
            callback();
            return true;
        }
        return false;
    }
    callback();
    return true;
}

// Theme selection and persistence
function applyTheme(theme) {
    if (theme === 'dark') {
        document.body.classList.add('dark-theme');
    } else {
        document.body.classList.remove('dark-theme');
    }
    localStorage.setItem('company-theme', theme);
}

function loadTheme() {
    const savedTheme = localStorage.getItem('company-theme') || 'light';
    applyTheme(savedTheme);
    // Set active class on theme options
    document.querySelectorAll('.theme-option').forEach(opt => {
        opt.classList.remove('active');
        if (opt.dataset.theme === savedTheme) {
            opt.classList.add('active');
        }
    });
}

// CalendarTable: appointments in kalender zetten
function getTimeRowIndex(time) {
    const hour = time.split(":")[0];
    const mapping = { "09": 1, "10": 2, "11": 3, "12": 4, "13": 5, "14": 6, "15": 7 };
    return mapping[hour] ?? 1;
}
function getMinuteColumnIndex(time) {
    const minute = time.split(":")[1];
    const mapping = { "00": 1, "15": 2, "30": 3, "45": 4 };
    return mapping[minute] ?? 1;
}
function setAppointment(rowIndex, colIndex, text) {
    const table = document.getElementById("calendar-table");
    if (!table) return;
    const row = table.rows[rowIndex];
    if (row && row.cells[colIndex]) {
        const current = row.cells[colIndex].innerText.trim();
        if (current === "–" || current === "") {
            row.cells[colIndex].innerText = text;
            row.cells[colIndex].style.backgroundColor = "#4CAF50";
            row.cells[colIndex].style.color = "white";
        }
    }
}
function fillCalendarTable(appointments) {
    appointments.forEach(appointment => {
        // Gebruik time_start voor plaatsing
        if (appointment.time_start) {
            const time = appointment.time_start;
            const rowIndex = getTimeRowIndex(time);
            const colIndex = getMinuteColumnIndex(time);
            // Gebruik student_name als beschikbaar, anders fallback naar student_id
            setAppointment(rowIndex, colIndex, appointment.student_name ? appointment.student_name : (appointment.student_id ? `Student ${appointment.student_id}` : 'Student'));
        }
    });
}

function fillAppointmentList(appointments) {
    const list = document.getElementById('appointment-list');
    if (!list) return;
    list.innerHTML = '';
    appointments.forEach(app => {
        // Gebruik student_name als beschikbaar, anders fallback naar student_id
        const li = document.createElement('li');
        li.textContent = `${app.student_name ? app.student_name : 'Student ' + app.student_id} | ${app.time_start} - ${app.time_end}`;
        list.appendChild(li);
    });
}

// Vul de kalender en appointment list met afspraken van de juiste company
async function fetchAndRenderAppointmentsForCompany(companyId) {
    try {
        console.log("companyId:", companyId);
        const response = await fetch('/api/appointments');
        const result = await response.json();
        const allAppointments = result.data || [];
        console.log("Appointments from API:", allAppointments);
        // Filter op company_id
        const appointments = allAppointments.filter(app => String(app.company_id) === String(companyId));
        console.log("Filtered appointments:", appointments);

        // Haal studentenlijst uit window of meta-tag (zoals bij berichten)
        let students = window.studentsList;
        if (!students && document.getElementById('message-list')) {
            students = Array.from(document.querySelectorAll('#message-list [data-user-id]')).map(el => ({
                id: el.getAttribute('data-user-id'),
                name: el.querySelector('.contact-info h4')?.textContent || 'Student'
            }));
        }
        // Map student_id naar naam
        if (students) {
            appointments.forEach(app => {
                const found = students.find(s => String(s.id) === String(app.student_id));
                if (found) app.student_name = found.name;
            });
        }

        fillCalendarTable(appointments);
        fillAppointmentList(appointments);
    } catch (err) {
        console.error('Fout bij ophalen afspraken:', err);
    }
}

// add event listeners when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    // home button click handler
    document.getElementById('homeBtn').addEventListener('click', (e) => {
        e.preventDefault();
        if (preventNavigationIfUnsaved(() => renderHome())) {
            renderHome();
        }
    });

    // messages button click handler
    document.getElementById('messageBtn').addEventListener('click', (e) => {
        e.preventDefault();
        if (preventNavigationIfUnsaved(() => renderMessages())) {
            renderMessages();
        }
    });

    // calendar button click handler
    document.getElementById('calendarBtn').addEventListener('click', (e) => {
        e.preventDefault();
        if (preventNavigationIfUnsaved(() => renderCalendar())) {
            renderCalendar();
        }
    });

    // settings button click handler
    document.getElementById('settingsBtn').addEventListener('click', (e) => {
        e.preventDefault();
        if (preventNavigationIfUnsaved(() => renderSettings())) {
            renderSettings();
        }
    });

    // Vul de kalender met afspraken als ze beschikbaar zijn
    if (window.appointmentsForCalendar) {
        fillCalendarTable(window.appointmentsForCalendar);
    }

    // initialize other handlers
    handleStudentSelection();
    handleProfileDropdown();
    handleSettingsNavigation();
    profileChangeTracking();
    loadTheme();

    // Start na DOM load
    // companyId moet beschikbaar zijn in een global of via een meta-tag
    const companyId = window.companyId || document.querySelector('meta[name="company-id"]')?.getAttribute('content');
    if (companyId) {
        fetchAndRenderAppointmentsForCompany(companyId);
    }

    // start with home view
    renderHome();
});