Compare commits

..

15 Commits

Author SHA1 Message Date
I-Fun
0d27befed0 fix: resolve 5 bugs — auth, ownership, crash, notification, and HTML issues
- dashboard.php: fix PDO parameter count crash for users with no groups
  (used max(count,1) for placeholder count but provided 0 group params)
- index.php: add missing auth check on get_tasks_status API endpoint
  (was accessible without a session, exposing all task data)
- index.php: enforce ownership check on delete_comment API
  (any logged-in user could delete any comment; now requires authorship or admin)
- tasks.php: fix task creation notification using undefined $_SESSION['username']
  (replaced with $current_user['username'] so {assignor} template works correctly)
- tasks.php: remove duplicate id attribute on att-lightbox-body element

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-30 23:21:15 +07:00
root
83ba58ddcd chore: remove database.sqlite from version control and ignore local database file 2026-03-30 12:28:18 +07:00
root
596a233898 refactor: replace global WAHA notifications with granular user and group-specific templates and dispatch logic 2026-03-30 01:02:23 +07:00
root
68a764c0df feat: enhance task tracking with comment metadata, tag support, improved audit logging, and flatpickr integration. 2026-03-29 23:34:27 +07:00
root
97649d9a98 add tag button 2026-03-29 21:38:48 +07:00
root
513de7813f feat: replace subtasks with task commenting system and update task view UI 2026-03-29 20:32:15 +07:00
root
78d309ae4e feat: implement subtasks, track task completion/archival users, and enhance kanban UI with drag-and-drop states 2026-03-29 19:46:21 +07:00
root
afb7ef2a37 feat: migrate WAHA configuration from system-wide to per-user settings with API key support 2026-03-29 17:11:05 +07:00
root
dbe02e52fd feat: integrate WAHA WhatsApp notifications for tasks, notes, and passwords with admin configuration settings 2026-03-29 16:42:30 +07:00
root
8dedb57692 feat: integrate Tagify for multi-tag support and add a new view-note modal across the application 2026-03-29 16:25:45 +07:00
root
f4f842d658 feat: add dev tools page and update sidebar toggle and team mood dashboard UI 2026-03-29 15:04:44 +07:00
root
2a670d80d1 feat: implement task API for status retrieval and expand task assignment logic to support custom assignee names 2026-03-29 14:33:15 +07:00
root
99f948ba5d Enhance note-taking features by adding label support, improving modal styles, and refining CSS for better responsiveness. Update login page title and adjust password management UI for better usability. 2026-03-27 20:04:52 +07:00
root
937033ea07 credit abis 2026-03-27 00:14:49 +07:00
root
f89fcbee1c major change 2026-03-27 00:03:48 +07:00
16 changed files with 4228 additions and 587 deletions

6
.gitignore vendored
View File

@@ -1,5 +1,9 @@
# Don't Commit
uploads/*
database.sqlite
*.log
.env
.agents/*
.antigravity/*
.vscode/*
.gemini/*
.cursor/*

BIN
database.sqlite Normal file

Binary file not shown.

94
db.php
View File

@@ -29,26 +29,108 @@ function get_user_groups($user_id) {
return $stmt->fetchAll();
}
function notify_user($user_id, $message) {
function compile_waha_template($template, $context) {
if (!$template) return "";
$action = $context['action'] ?? 'Update';
$module = $context['module'] ?? 'System';
$item = $context['item'] ?? '';
$user = $context['user'] ?? null;
if (!$user && isset($_SESSION['user_id'])) {
$u = get_user($_SESSION['user_id']);
$user = $u ? $u['username'] : 'System';
} elseif (!$user) {
$user = 'System';
}
$attachment_count = $context['attachment_count'] ?? '0';
$due_date = $context['due_date'] ?? 'None';
$created_date = $context['created_date'] ?? date('Y-m-d H:i');
$updated_date = $context['updated_date'] ?? date('Y-m-d H:i');
$assignor = $context['assignor'] ?? 'N/A';
$assignee = $context['assignee'] ?? 'N/A';
return str_replace(
['{action}', '{module}', '{item}', '{user}', '{attachment_count}', '{due_date}', '{created_date}', '{updated_date}', '{assignor}', '{assignee}'],
[$action, $module, $item, $user, $attachment_count, $due_date, $created_date, $updated_date, $assignor, $assignee],
$template
);
}
function dispatch_waha_message($endpoint, $chat_id, $session, $api_key, $text) {
try {
$payload = json_encode([
"chatId" => $chat_id,
"text" => $text,
"session" => $session ?: 'default'
]);
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
$headers = ['Content-Type: application/json'];
if (!empty($api_key)) $headers[] = 'X-Api-Key: ' . $api_key;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_exec($ch);
curl_close($ch);
} catch(Exception $e) {}
}
function notify_user($user_id, $message, $context = []) {
global $pdo;
$stmt = $pdo->prepare("INSERT INTO notifications (user_id, message) VALUES (?, ?)");
$stmt->execute([$user_id, $message]);
// Virtual hook for Email/Telegram/WhatsApp based on user features
$user = get_user($user_id);
if($user && isset($user['notify_channels'])) {
$channels = explode(',', $user['notify_channels']);
// Here we would actually send the message to the third party API.
// For MVP we just assume it's sent.
if (in_array('whatsapp', $channels) && $user['waha_endpoint'] && $user['waha_chat_id']) {
$module = $context['module'] ?? '';
$template = '';
if (stripos($module, 'Note') !== false) $template = $user['waha_template_note'];
elseif (stripos($module, 'Password') !== false) $template = $user['waha_template_password'];
elseif (stripos($module, 'File') !== false || stripos($module, 'Folder') !== false) $template = $user['waha_template_file'];
else $template = $user['waha_template_task'];
if (!$template) $template = "*Alert:* {action} on {module} '{item}' by {user}";
$text = compile_waha_template($template, $context);
dispatch_waha_message($user['waha_endpoint'], $user['waha_chat_id'], $user['waha_session'], $user['waha_api_key'], $text);
}
}
}
function notify_group($group_id, $message) {
function notify_group($group_id, $message, $context = []) {
global $pdo;
// Notify all individual group members in their UI notifications
$stmt = $pdo->prepare("SELECT user_id FROM user_groups WHERE group_id = ?");
$stmt->execute([$group_id]);
$users = $stmt->fetchAll();
foreach ($users as $u) {
notify_user($u['user_id'], $message);
$s = $pdo->prepare("INSERT INTO notifications (user_id, message) VALUES (?, ?)");
$s->execute([$u['user_id'], $message]);
}
// Check if the group itself has WAHA configured
$stmt = $pdo->prepare("SELECT * FROM groups WHERE id = ?");
$stmt->execute([$group_id]);
$group = $stmt->fetch();
if($group && isset($group['notify_channels'])) {
$channels = explode(',', $group['notify_channels']);
if (in_array('whatsapp', $channels) && $group['waha_endpoint'] && $group['waha_chat_id']) {
$module = $context['module'] ?? '';
$template = '';
if (stripos($module, 'Note') !== false) $template = $group['waha_template_note'];
elseif (stripos($module, 'Password') !== false) $template = $group['waha_template_password'];
elseif (stripos($module, 'File') !== false || stripos($module, 'Folder') !== false) $template = $group['waha_template_file'];
else $template = $group['waha_template_task'];
if (!$template) $template = "*Group Alert:* {action} on {module} '{item}' by {user}";
$text = compile_waha_template($template, $context);
dispatch_waha_message($group['waha_endpoint'], $group['waha_chat_id'], $group['waha_session'], $group['waha_api_key'], $text);
}
}
}

0
db.sqlite Normal file
View File

370
index.php
View File

@@ -1,5 +1,6 @@
<?php
session_start();
date_default_timezone_set('Etc/GMT-7');
require_once 'db.php';
$action = (string)($_GET['action'] ?? 'dashboard');
@@ -7,14 +8,304 @@ $action = (string)($_GET['action'] ?? 'dashboard');
// API updates for task kanban drag n drop
if ($action === 'api') {
$api_action = $_GET['api_action'] ?? '';
if(!isset($_SESSION['user_id'])) die(json_encode(['status'=>'error','msg'=>'unauthorized']));
header('Content-Type: application/json; charset=utf-8');
// Ensure newer task columns exist (API might be called without visiting the tasks page first).
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN assignor_type TEXT DEFAULT 'user'"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN assignor_group_id INTEGER"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN status_updated_at DATETIME"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN due_date DATETIME"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN custom_assignee_name TEXT"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN completed_by INTEGER DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN archived_by INTEGER DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("CREATE TABLE IF NOT EXISTS task_attachments (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER, file_name TEXT, file_path TEXT, owner_id INTEGER, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)"); } catch(Exception $e) {}
try { $pdo->exec("CREATE TABLE IF NOT EXISTS task_comments (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER, comment TEXT NOT NULL, created_by INTEGER, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)"); } catch(Exception $e) {}
$format_dt = function($value) {
$value = is_string($value) ? trim($value) : $value;
if(!$value) return null;
$ts = strtotime((string)$value);
if($ts === false) return null;
return date('Y-m-d H:i', $ts);
};
$format_status = function($value) {
if(!$value) return null;
$s = strtolower(trim((string)$value));
if($s === 'in_progress') return 'In Progress';
$s = str_replace('_', ' ', $s);
return ucfirst($s);
};
if($api_action === 'update_task_status') {
if(!isset($_SESSION['user_id'])) die(json_encode(['status'=>'error','msg'=>'unauthorized']));
$task_id = $_POST['task_id'] ?? null;
$status = $_POST['status'] ?? null;
$stmt = $pdo->prepare("UPDATE tasks SET status = ?, status_updated_at = CURRENT_TIMESTAMP WHERE id = ?");
$stmt->execute([$status, $task_id]);
echo json_encode(['status'=>'ok']);
$user_id = $_SESSION['user_id'];
$set_clause = "status = ?, status_updated_at = CURRENT_TIMESTAMP";
$params = [$status];
if ($status === 'completed') {
$set_clause .= ", completed_by = ?";
$params[] = $user_id;
} elseif ($status === 'archived') {
$set_clause .= ", archived_by = ?";
$params[] = $user_id;
}
$params[] = $task_id;
$stmt = $pdo->prepare("UPDATE tasks SET $set_clause WHERE id = ?");
$stmt->execute($params);
$t = query("SELECT title, assignee_type, assignee_id FROM tasks WHERE id=?", [$task_id])->fetch();
if($t) {
$ctx = ['action' => 'Moved to '.$status, 'module' => 'Task', 'item' => $t['title']];
if($t['assignee_type'] === 'user' && $t['assignee_id']) {
notify_user($t['assignee_id'], "Task '{$t['title']}' moved to $status", $ctx);
} elseif($t['assignee_type'] === 'group' && $t['assignee_id']) {
notify_group($t['assignee_id'], "Group task '{$t['title']}' moved to $status", $ctx);
}
}
echo json_encode(['status'=>'ok']);
exit;
}
if($api_action === 'add_comment') {
if(!isset($_SESSION['user_id'])) die(json_encode(['status'=>'error','msg'=>'unauthorized']));
$task_id = $_POST['task_id'] ?? null;
$comment = $_POST['comment'] ?? null;
$user_id = $_SESSION['user_id'];
if($task_id && $comment) {
$stmt = $pdo->prepare("INSERT INTO task_comments (task_id, comment, created_by) VALUES (?, ?, ?)");
$stmt->execute([$task_id, $comment, $user_id]);
$t = query("SELECT title, assignee_type, assignee_id FROM tasks WHERE id=?", [$task_id])->fetch();
if($t) {
$ctx = ['action' => 'New Comment', 'module' => 'Task', 'item' => $t['title']];
if($t['assignee_type'] === 'user' && $t['assignee_id']) {
notify_user($t['assignee_id'], "New comment on '{$t['title']}'", $ctx);
} elseif($t['assignee_type'] === 'group' && $t['assignee_id']) {
notify_group($t['assignee_id'], "New comment on group task '{$t['title']}'", $ctx);
}
}
}
echo json_encode(['status'=>'ok']);
exit;
}
if($api_action === 'delete_comment') {
if(!isset($_SESSION['user_id'])) die(json_encode(['status'=>'error','msg'=>'unauthorized']));
$comment_id = $_POST['comment_id'] ?? null;
if($comment_id) {
$user_id = $_SESSION['user_id'];
$is_admin = !empty($_SESSION['is_admin']);
$comment_check = query("SELECT created_by FROM task_comments WHERE id = ?", [$comment_id])->fetch();
if($comment_check && ($comment_check['created_by'] == $user_id || $is_admin)) {
$stmt = $pdo->prepare("DELETE FROM task_comments WHERE id = ?");
$stmt->execute([$comment_id]);
} else {
echo json_encode(['status'=>'error','msg'=>'forbidden']);
exit;
}
}
echo json_encode(['status'=>'ok']);
exit;
}
if($api_action === 'get_tasks_status') {
if(!isset($_SESSION['user_id'])) die(json_encode(['status'=>'error','msg'=>'unauthorized']));
$task_id = $_GET['task_id'] ?? null;
// Correlated subquery gives attachment count per task.
$sql = "
SELECT
t.*,
u.username as assignor_user_name,
g.name as assignor_group_name,
au.username as assignee_user_name,
ag.name as assignee_group_name,
(SELECT COUNT(*) FROM task_attachments ta WHERE ta.task_id = t.id) AS attachments_count,
(SELECT COUNT(*) FROM task_comments tc WHERE tc.task_id = t.id) AS comments_count,
(SELECT comment FROM task_comments tc WHERE tc.task_id = t.id ORDER BY tc.created_at DESC LIMIT 1) AS last_comment,
(SELECT created_at FROM task_comments tc WHERE tc.task_id = t.id ORDER BY tc.created_at DESC LIMIT 1) AS last_comment_date,
(SELECT cu.username FROM task_comments tc JOIN users cu ON tc.created_by = cu.id WHERE tc.task_id = t.id ORDER BY tc.created_at DESC LIMIT 1) AS last_commenter,
t.status_updated_at,
t.completed_by,
t.archived_by,
t.tags,
t.title
FROM tasks t
LEFT JOIN users u ON t.assignor_id = u.id
LEFT JOIN groups g ON t.assignor_group_id = g.id
LEFT JOIN users au ON (t.assignee_type='user' AND t.assignee_id = au.id)
LEFT JOIN groups ag ON (t.assignee_type='group' AND t.assignee_id = ag.id)
";
$params = [];
if($task_id !== null && $task_id !== '') {
if(!ctype_digit((string)$task_id)) {
echo json_encode(['status'=>'error','msg'=>'Invalid task_id']);
exit;
}
$sql .= " WHERE t.id = ? LIMIT 1";
$params[] = (int)$task_id;
} else {
$sql .= " ORDER BY t.created_at DESC";
}
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();
if($task_id !== null && $task_id !== '') {
$row = $rows ? $rows[0] : null;
if(!$row) {
echo json_encode(['status'=>'error','msg'=>'Task not found']);
exit;
}
$from = null;
if(($row['assignor_type'] ?? null) === 'group') $from = $row['assignor_group_name'] ?? null;
elseif(($row['assignor_type'] ?? null) === 'user') $from = $row['assignor_user_name'] ?? null;
$to = null;
if(($row['assignee_type'] ?? null) === 'user') $to = $row['assignee_user_name'] ?? null;
elseif(($row['assignee_type'] ?? null) === 'group') $to = $row['assignee_group_name'] ?? null;
elseif(($row['assignee_type'] ?? null) === 'custom') $to = $row['custom_assignee_name'] ?? null;
$desc = (string)($row['description'] ?? '');
$desc = trim($desc) !== '' ? $desc : (string)($row['title'] ?? '');
$tags = !empty($row['tags']) ? array_filter(array_map('trim', explode(',', $row['tags']))) : [];
// Logic for last_modified_by
// If it's archived, 'Archived by' user; if completed, 'Completed by' user; otherwise latest commenter or creator.
$last_mod_by = 'System';
if ($row['status'] === 'archived' && $row['archived_by']) {
$last_mod_by = query("SELECT username FROM users WHERE id=?", [$row['archived_by']])->fetchColumn() ?: 'System';
} elseif ($row['status'] === 'completed' && $row['completed_by']) {
$last_mod_by = query("SELECT username FROM users WHERE id=?", [$row['completed_by']])->fetchColumn() ?: 'System';
} else {
$last_mod_by = $row['last_commenter'] ?: $row['assignor_user_name'];
}
$payload = [
'task_id' => (string)$row['id'],
'task_name' => (string)$row['title'],
'task_created_date' => $format_dt($row['created_at'] ? $row['created_at'] . ' UTC' : null),
'from' => $from,
'to' => $to,
'task_description' => $desc,
'due_date' => $format_dt($row['due_date'] ?? null),
'current_status' => $format_status($row['status'] ?? null),
'attachments_count' => (int)($row['attachments_count'] ?? 0),
'tags_count' => count($tags),
'comments_count' => (int)($row['comments_count'] ?? 0),
'last_modified_by' => $last_mod_by,
'last_modified_date' => $format_dt(($row['status_updated_at'] ?: $row['created_at']) . ' UTC'),
'last_comment' => $row['last_comment'] ?: null,
'last_comment_date' => $format_dt($row['last_comment_date'] ? $row['last_comment_date'] . ' UTC' : null),
];
echo json_encode($payload);
exit;
}
$result = [];
foreach($rows as $row) {
$from = null;
if(($row['assignor_type'] ?? null) === 'group') $from = $row['assignor_group_name'] ?? null;
elseif(($row['assignor_type'] ?? null) === 'user') $from = $row['assignor_user_name'] ?? null;
$to = null;
if(($row['assignee_type'] ?? null) === 'user') $to = $row['assignee_user_name'] ?? null;
elseif(($row['assignee_type'] ?? null) === 'group') $to = $row['assignee_group_name'] ?? null;
elseif(($row['assignee_type'] ?? null) === 'custom') $to = $row['custom_assignee_name'] ?? null;
$desc = (string)($row['description'] ?? '');
$desc = trim($desc) !== '' ? $desc : (string)($row['title'] ?? '');
$tags = !empty($row['tags']) ? array_filter(array_map('trim', explode(',', $row['tags']))) : [];
$last_mod_by = 'System';
if ($row['status'] === 'archived' && $row['archived_by']) {
$last_mod_by = query("SELECT username FROM users WHERE id=?", [$row['archived_by']])->fetchColumn() ?: 'System';
} elseif ($row['status'] === 'completed' && $row['completed_by']) {
$last_mod_by = query("SELECT username FROM users WHERE id=?", [$row['completed_by']])->fetchColumn() ?: 'System';
} else {
$last_mod_by = $row['last_commenter'] ?: $row['assignor_user_name'];
}
$result[] = [
'task_id' => (string)$row['id'],
'task_name' => (string)$row['title'],
'task_created_date' => $format_dt($row['created_at'] ? $row['created_at'] . ' UTC' : null),
'from' => $from,
'to' => $to,
'task_description' => $desc,
'due_date' => $format_dt($row['due_date'] ?? null),
'current_status' => $format_status($row['status'] ?? null),
'attachments_count' => (int)($row['attachments_count'] ?? 0),
'tags_count' => count($tags),
'comments_count' => (int)($row['comments_count'] ?? 0),
'last_modified_by' => $last_mod_by,
'last_modified_date' => $format_dt(($row['status_updated_at'] ?: $row['created_at']) . ' UTC'),
'last_comment' => $row['last_comment'] ?: null,
'last_comment_date' => $format_dt($row['last_comment_date'] ? $row['last_comment_date'] . ' UTC' : null),
];
}
echo json_encode($result);
exit;
}
if($api_action === 'add_task_tag') {
if(!isset($_SESSION['user_id'])) die(json_encode(['success'=>false,'error'=>'unauthorized']));
$task_id = $_POST['task_id'] ?? null;
$tag = trim($_POST['tag'] ?? '');
$user_id = $_SESSION['user_id'];
if($task_id && $tag) {
$stmt = $pdo->prepare("SELECT tags FROM tasks WHERE id = ?");
$stmt->execute([$task_id]);
$row = $stmt->fetch();
$current_tags = $row ? ($row['tags'] ?? '') : '';
$tags_array = $current_tags ? array_filter(array_map('trim', explode(',', $current_tags))) : [];
if(!in_array($tag, $tags_array)) {
$tags_array[] = $tag;
$new_tags = implode(',', $tags_array);
$pdo->prepare("UPDATE tasks SET tags = ? WHERE id = ?")->execute([$new_tags, $task_id]);
}
echo json_encode(['success'=>true]);
} else {
echo json_encode(['success'=>false,'error'=>'Missing task_id or tag']);
}
exit;
}
if($api_action === 'remove_task_tag') {
if(!isset($_SESSION['user_id'])) die(json_encode(['success'=>false,'error'=>'unauthorized']));
$task_id = $_POST['task_id'] ?? null;
$tag = trim($_POST['tag'] ?? '');
if($task_id && $tag) {
$stmt = $pdo->prepare("SELECT tags FROM tasks WHERE id = ?");
$stmt->execute([$task_id]);
$row = $stmt->fetch();
$current_tags = $row ? ($row['tags'] ?? '') : '';
$tags_array = $current_tags ? array_filter(array_map('trim', explode(',', $current_tags))) : [];
$tags_array = array_diff($tags_array, [$tag]);
$new_tags = implode(',', $tags_array);
$pdo->prepare("UPDATE tasks SET tags = ? WHERE id = ?")->execute([$new_tags, $task_id]);
echo json_encode(['success'=>true]);
} else {
echo json_encode(['success'=>false,'error'=>'Missing task_id or tag']);
}
exit;
}
echo json_encode(['status'=>'error','msg'=>'Unknown api_action']);
exit;
}
@@ -66,7 +357,6 @@ if ($action === 'login') {
}
// Handle POST actions that need a redirect BEFORE layout outputs any HTML.
// Adding new redirect-based POST keys here keeps header() calls safe.
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $user_id) {
// Mood setter
if (isset($_POST['set_mood'])) {
@@ -86,19 +376,81 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST' && $user_id) {
header('Location: ?action=dashboard');
exit;
}
// Profile picture upload
if (isset($_POST['upload_profile_pic'])) {
// Ensure column exists
try { $pdo->exec("ALTER TABLE users ADD COLUMN profile_pic TEXT DEFAULT NULL"); } catch(Exception $e) {}
if (isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] === 0) {
$allowed_types = ['image/jpeg','image/png','image/gif','image/webp'];
if (in_array($_FILES['profile_pic']['type'], $allowed_types)) {
$ext = pathinfo($_FILES['profile_pic']['name'], PATHINFO_EXTENSION);
$filename = 'avatar_' . $user_id . '_' . time() . '.' . $ext;
$dest = 'uploads/' . $filename;
if (move_uploaded_file($_FILES['profile_pic']['tmp_name'], $dest)) {
// Delete old pic
$old = $pdo->prepare("SELECT profile_pic FROM users WHERE id=?");
$old->execute([$user_id]);
$old_pic = $old->fetchColumn();
if ($old_pic && file_exists($old_pic)) @unlink($old_pic);
$pdo->prepare("UPDATE users SET profile_pic=? WHERE id=?")->execute([$dest, $user_id]);
}
}
}
header('Location: ?action=' . ($_POST['redirect_to'] ?? 'dashboard'));
exit;
}
// Delete profile picture
if (isset($_POST['delete_profile_pic'])) {
try { $pdo->exec("ALTER TABLE users ADD COLUMN profile_pic TEXT DEFAULT NULL"); } catch(Exception $e) {}
$old = $pdo->prepare("SELECT profile_pic FROM users WHERE id=?");
$old->execute([$user_id]);
$old_pic = $old->fetchColumn();
if ($old_pic && file_exists($old_pic)) @unlink($old_pic);
$pdo->prepare("UPDATE users SET profile_pic=NULL WHERE id=?")->execute([$user_id]);
header('Location: ?action=' . ($_POST['redirect_to'] ?? 'dashboard'));
exit;
}
// Mark all notifications as read
if (isset($_POST['mark_all_read'])) {
$pdo->prepare("UPDATE notifications SET is_read=1 WHERE user_id=?")->execute([$user_id]);
header('Location: ?action=' . ($_POST['redirect_to'] ?? 'dashboard'));
exit;
}
// Change password
if (isset($_POST['change_password'])) {
$cur = trim($_POST['current_password'] ?? '');
$new = trim($_POST['new_password'] ?? '');
$cnf = trim($_POST['confirm_password'] ?? '');
$user = get_user($user_id);
$pw_error = '';
if (!password_verify($cur, $user['password_hash'])) {
$pw_error = 'Current password is incorrect.';
} elseif (strlen($new) < 6) {
$pw_error = 'New password must be at least 6 characters.';
} elseif ($new !== $cnf) {
$pw_error = 'Passwords do not match.';
} else {
$pdo->prepare("UPDATE users SET password_hash=? WHERE id=?")
->execute([password_hash($new, PASSWORD_DEFAULT), $user_id]);
}
$_SESSION['pw_change_msg'] = $pw_error ?: 'success';
header('Location: ?action=' . ($_POST['redirect_to'] ?? 'dashboard'));
exit;
}
}
$view_file = 'views/' . basename($action) . '.php';
if (file_exists($view_file)) {
// AJAX-only POST requests must not have the HTML layout wrapped around them,
// otherwise the JSON response gets embedded inside the HTML document and
// JSON.parse() fails on the client side.
$is_ajax_post = isset($_POST['ajax_submit'])
|| isset($_POST['delete_attachment_ajax'])
|| isset($_POST['upload_attachment_ajax']);
if ($is_ajax_post) {
include $view_file; // view handles its own output + exit
include $view_file;
} else {
include 'views/layout_top.php';
include $view_file;

View File

@@ -30,29 +30,85 @@ a { text-decoration: none; color: var(--primary); }
a:hover { text-decoration: underline; }
.app-container { display: flex; min-height: 100vh; }
.sidebar { width: 250px; background: var(--surface); border-right: 1px solid var(--border); padding: 1.5rem; display: flex; flex-direction: column; gap: 1rem; }
.sidebar h2 { font-size: 1.2rem; margin-bottom: 2rem; color: var(--primary); }
.nav-link { padding: 0.75rem 1rem; border-radius: 0.5rem; text-decoration: none !important; color: var(--text); font-weight: 500; transition: background 0.2s; display: flex; justify-content: space-between; align-items: center; }
.nav-link:hover, .nav-link.active { background: rgba(var(--primary-rgb), 0.1); color: var(--primary); }
.nav-link .badge { background: #EF4444; color: white; padding: 2px 6px; border-radius: 12px; font-size: 0.75rem; }
.main-content { flex: 1; padding: 2rem; overflow-y: auto; }
.header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; }
/* ── Sidebar ─────────────────────────────────────────────────────────────── */
.sidebar {
width: 240px; background: var(--surface); border-right: 1px solid var(--border);
padding: 1.25rem 1rem; display: flex; flex-direction: column; gap: 0.75rem;
position: sticky; top: 0; height: 100vh; overflow-y: auto; overflow-x: hidden;
transition: width 0.25s cubic-bezier(.4,0,.2,1); flex-shrink: 0;
position: relative;
}
.sidebar-brand {
display: flex; align-items: center; gap: 8px; font-size: 1.1rem;
font-weight: 700; color: var(--primary); margin-bottom: 0.75rem;
white-space: nowrap; overflow: hidden;
}
/* Toggle button pinned to right edge */
.sidebar-toggle-btn {
position: fixed; top: 1.5rem; left: 226px;
width: 28px; height: 28px; border-radius: 50%;
border: 1px solid var(--border); background: var(--surface);
color: var(--text-light); font-size: 0.65rem;
cursor: pointer; display: flex; align-items: center; justify-content: center;
z-index: 20; transition: left 0.25s cubic-bezier(.4,0,.2,1), background 0.15s, color 0.15s, border-color 0.15s;
box-shadow: 0 2px 6px rgba(0,0,0,0.12);
}
.sidebar-toggle-btn:hover { background: var(--primary); color: #fff; border-color: var(--primary); }
/* Nav link: icon always visible, label collapses */
.nav-link {
padding: 0.6rem 0.75rem; border-radius: 0.5rem;
text-decoration: none !important; color: var(--text); font-weight: 500;
transition: background 0.2s; display: flex; align-items: center;
gap: 0.65rem; font-size: 0.875rem; white-space: nowrap; overflow: hidden;
position: relative;
}
.nav-link:hover, .nav-link.active { background: rgba(var(--primary-rgb), 0.1); color: var(--primary); }
.nav-icon { width: 18px; text-align: center; flex-shrink: 0; font-size: 0.95rem; }
.sidebar-label { overflow: hidden; transition: opacity 0.2s; opacity: 1; flex: 1; }
.nav-link .badge { background: #EF4444; color: white; padding: 2px 6px; border-radius: 12px; font-size: 0.72rem; margin-left: auto; }
/* ── Collapsed State ────────────────────────────────────────────────────── */
body.sidebar-collapsed .sidebar { width: 64px; }
body.sidebar-collapsed .sidebar-label { opacity: 0; width: 0; pointer-events: none; }
body.sidebar-collapsed .nav-link { justify-content: center; padding: 0.65rem; gap: 0; }
body.sidebar-collapsed .nav-link .badge { position: absolute; top: 2px; right: 2px; padding: 1px 4px; font-size: 0.6rem; }
body.sidebar-collapsed .sidebar-toggle-btn { left: 50px; }
body.sidebar-collapsed .sidebar-toggle-btn .fa-chevron-left { display: block; }
/* Tooltip on collapsed nav links */
body.sidebar-collapsed .nav-link { position: relative; }
body.sidebar-collapsed .nav-link::after {
content: attr(title); position: absolute; left: calc(100% + 12px); top: 50%;
transform: translateY(-50%); background: var(--text); color: var(--surface);
padding: 4px 10px; border-radius: 6px; font-size: 0.78rem; white-space: nowrap;
opacity: 0; pointer-events: none; transition: opacity 0.15s; z-index: 100;
}
body.sidebar-collapsed .nav-link:hover::after { opacity: 1; }
.main-content { flex: 1; padding: 1.5rem 2rem; overflow-y: auto; max-height: 100vh; }
.header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; }
.card { background: var(--surface); padding: 1.5rem; border-radius: 1rem; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); margin-bottom: 1.5rem; }
.btn { display: inline-flex; align-items: center; gap: 0.5rem; justify-content:center; padding: 0.5rem 1rem; background: var(--primary); color: white !important; border-radius: 0.5rem; border: none; cursor: pointer; text-decoration: none !important; font-weight: 500; transition: opacity 0.2s; }
.btn:hover { opacity: 0.9; }
.btn-sm { padding: 0.25rem 0.5rem; font-size: 0.875rem; }
.btn { display: inline-flex; align-items: center; gap: 0.5rem; justify-content:center; padding: 0.5rem 1rem; background: var(--primary); color: white !important; border-radius: 0.5rem; border: none; cursor: pointer; text-decoration: none !important; font-weight: 500; transition: opacity 0.2s; font-size: 0.875rem; }
.btn:hover { opacity: 0.9; text-decoration: none !important; }
.btn-sm { padding: 0.25rem 0.5rem; font-size: 0.8rem; }
.btn-secondary { background: var(--text-light); }
.btn-danger { background: #EF4444; }
.form-group { margin-bottom: 1rem; }
.form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; }
.form-control { width: 100%; padding: 0.75rem; border: 1px solid var(--border); border-radius: 0.5rem; font-family: inherit; background: var(--input-bg); color: var(--text); }
.form-group label { display: block; margin-bottom: 0.5rem; font-weight: 500; font-size: 0.875rem; }
.form-control { width: 100%; padding: 0.65rem 0.75rem; border: 1px solid var(--border); border-radius: 0.5rem; font-family: inherit; background: var(--input-bg); color: var(--text); font-size: 0.9rem; }
.form-control:focus { outline: none; border-color: var(--primary); box-shadow: 0 0 0 3px rgba(var(--primary-rgb),0.12); }
table { width: 100%; border-collapse: collapse; margin-top: 1rem; }
th, td { padding: 0.75rem; text-align: left; border-bottom: 1px solid var(--border); }
th { color: var(--text-light); font-weight: 500; }
table { width: 100%; border-collapse: collapse; margin-top: 1rem; font-size: 0.875rem; }
th, td { padding: 0.65rem 0.75rem; text-align: left; border-bottom: 1px solid var(--border); }
th { color: var(--text-light); font-weight: 600; font-size: 0.78rem; text-transform: uppercase; letter-spacing: 0.04em; background: rgba(0,0,0,0.02); }
body.dark-mode th { background: rgba(255,255,255,0.02); }
tr:hover td { background: rgba(var(--primary-rgb),0.03); }
.kanban-board { display: flex; gap: 1.5rem; overflow-x: auto; padding-bottom: 1rem; }
.kanban-col { background: rgba(0,0,0,0.03); border-radius: 1rem; width: 320px; min-width: 320px; display: flex; flex-direction: column; }
@@ -62,22 +118,223 @@ body.dark-mode .kanban-col { background: rgba(255,255,255,0.03); }
.kanban-task { background: var(--surface); padding: 1rem; border-radius: 0.5rem; box-shadow: 0 2px 4px rgba(0,0,0,0.05); border: 1px solid var(--border); cursor: grab; }
.kanban-task:active { cursor: grabbing; }
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; opacity: 0; pointer-events: none; transition: opacity 0.2s; }
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.55); display: flex; align-items: center; justify-content: center; z-index: 1000; opacity: 0; pointer-events: none; transition: opacity 0.2s; backdrop-filter: blur(3px); }
.modal-overlay.active { opacity: 1; pointer-events: auto; }
.modal-content { background: var(--surface); padding: 2rem; border-radius: 1rem; width: 100%; max-width: 400px; transform: translateY(-20px); transition: transform 0.2s; }
.modal-content { background: var(--surface); padding: 2rem; border-radius: 1rem; width: 100%; max-width: 500px; transform: translateY(-20px); transition: transform 0.2s; box-shadow: 0 25px 50px rgba(0,0,0,0.3); }
.modal-overlay.active .modal-content { transform: translateY(0); }
#toast { position: fixed; bottom: 20px; right: 20px; background: var(--text); color: var(--surface); padding: 1rem; border-radius: 0.5rem; z-index: 9999; transform: translateY(100px); opacity: 0; transition: all 0.3s; }
#toast { position: fixed; bottom: 20px; right: 20px; background: var(--text); color: var(--surface); padding: 1rem 1.25rem; border-radius: 0.5rem; z-index: 9999; transform: translateY(100px); opacity: 0; transition: all 0.3s; font-size: 0.875rem; }
#toast.show { transform: translateY(0); opacity: 1; }
.dropzone { border: 2px dashed var(--border); padding: 3rem; text-align: center; border-radius: 1rem; cursor: pointer; transition: background 0.2s; }
.dropzone { border: 2px dashed var(--border); padding: 2rem; text-align: center; border-radius: 1rem; cursor: pointer; transition: background 0.2s; color: var(--text-light); }
.dropzone.dragover { background: rgba(var(--primary-rgb), 0.1); border-color: var(--primary); }
.project-item { display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; border-bottom: 1px solid var(--border); }
.project-item:hover { background: rgba(0,0,0,0.02); }
body.dark-mode .project-item:hover { background: rgba(255,255,255,0.02); }
.project-item { display: flex; justify-content: space-between; align-items: center; padding: 0.6rem 0.75rem; border-bottom: 1px solid var(--border); transition: background 0.15s; }
.project-item:hover { background: rgba(var(--primary-rgb),0.04); }
body.dark-mode .project-item:hover { background: rgba(255,255,255,0.03); }
.login-container { min-height: 100vh; display: flex; align-items: center; justify-content: center; background: linear-gradient(135deg, #4F46E5 0%, #10B981 100%); }
.login-card { background: var(--surface); padding: 2.5rem; border-radius: 1rem; width: 100%; max-width: 400px; box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1); }
.login-card h1 { text-align: center; margin-bottom: 1.5rem; color: var(--text); }
.alert { padding: 1rem; border-radius: 0.5rem; margin-bottom: 1rem; background: #FEF2F2; color: #991B1B; }
.alert { padding: 1rem; border-radius: 0.5rem; margin-bottom: 1rem; background: #FEF2F2; color: #991B1B; font-size: 0.875rem; }
/* ── User Avatar Dropdown ─────────────────────────────────────────────────── */
.user-dropdown-wrap { position: relative; }
.user-avatar-btn {
width: 40px; height: 40px; border-radius: 50%;
background: var(--primary); color: #fff;
border: 2px solid transparent;
cursor: pointer; display: flex; align-items: center; justify-content: center;
font-size: 1rem; font-weight: 700; overflow: hidden;
transition: box-shadow 0.2s, border-color 0.2s;
flex-shrink: 0;
}
.user-avatar-btn:hover { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(var(--primary-rgb),0.2); }
/* Notification count badge overlaid on avatar */
.avatar-notif-badge {
position: absolute; top: -3px; right: -3px;
background: #EF4444; color: #fff; font-size: 0.6rem; font-weight: 700;
min-width: 17px; height: 17px; border-radius: 10px; border: 2px solid var(--bg);
display: flex; align-items: center; justify-content: center;
cursor: pointer; z-index: 10; padding: 0 3px; line-height: 1;
animation: badge-pop 0.3s cubic-bezier(.17,.67,.83,.67);
}
@keyframes badge-pop { 0%{transform:scale(0)}70%{transform:scale(1.2)}100%{transform:scale(1)} }
.user-dropdown-menu {
display: none; position: absolute; top: calc(100% + 8px); right: 0;
background: var(--surface); border: 1px solid var(--border); border-radius: 0.75rem;
box-shadow: 0 10px 25px rgba(0,0,0,0.15); min-width: 200px; z-index: 500;
overflow: hidden; animation: dropdown-in 0.15s ease;
}
.user-dropdown-menu.open { display: block; }
@keyframes dropdown-in { from { opacity:0; transform:translateY(-6px); } to { opacity:1; transform:translateY(0); } }
.user-dropdown-header { padding: 0.9rem 1rem; background: rgba(var(--primary-rgb),0.06); }
.user-dropdown-name { font-weight: 700; font-size: 0.9rem; color: var(--text); }
.user-dropdown-role { font-size: 0.75rem; color: var(--text-light); margin-top: 2px; }
.user-dropdown-divider { height: 1px; background: var(--border); margin: 0; }
.user-dropdown-item {
display: flex; align-items: center; gap: 0.65rem;
padding: 0.65rem 1rem; width: 100%; border: none;
background: none; color: var(--text); font-size: 0.875rem;
cursor: pointer; text-decoration: none !important; font-family: inherit;
transition: background 0.15s;
}
.user-dropdown-item:hover { background: rgba(var(--primary-rgb),0.07); color: var(--primary); }
.user-dropdown-item i { width: 16px; text-align: center; color: var(--text-light); }
.user-dropdown-item:hover i { color: var(--primary); }
.user-dropdown-logout { color: #EF4444 !important; }
.user-dropdown-logout:hover { background: rgba(239,68,68,0.07) !important; }
.user-dropdown-logout i { color: #EF4444 !important; }
/* ── Activity log scrollbar fix ────────────────────────────────────────── */
.log-list {
display: flex; flex-direction: column; gap: 0.5rem;
overflow-y: auto; flex: 1; max-height: 360px;
padding-right: 8px; /* prevent scrollbar from eating time */
scrollbar-gutter: stable; /* modern browsers reserve scrollbar space */
scrollbar-width: thin;
scrollbar-color: var(--border) transparent;
}
.log-list::-webkit-scrollbar { width: 4px; }
.log-list::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }
.log-list::-webkit-scrollbar-track { background: transparent; }
/* ── Notes / Google Keep Style ───────────────────────────────────────────── */
.notes-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 1rem; }
.note-card {
background: var(--surface); border: 1px solid var(--border);
border-radius: 0.75rem; padding: 1rem; cursor: pointer;
transition: box-shadow 0.2s, transform 0.15s; position: relative;
display: flex; flex-direction: column; gap: 0.5rem; min-height: 120px;
}
.note-card:hover { box-shadow: 0 8px 20px rgba(0,0,0,0.12); transform: translateY(-2px); }
.note-card-title { font-weight: 600; font-size: 0.95rem; color: var(--text); word-break: break-word; }
.note-card-preview { font-size: 0.8rem; color: var(--text-light); overflow: hidden; max-height: 80px; line-height: 1.5; word-break: break-word; }
.note-card-img { width: 100%; height: 120px; object-fit: cover; border-radius: 0.5rem; margin-bottom: 0.25rem; }
.note-card-footer { display: flex; align-items: center; justify-content: space-between; margin-top: auto; padding-top: 0.5rem; border-top: 1px solid var(--border); gap: 0.5rem; }
.note-card-actions { display: none; gap: 0.25rem; }
.note-card:hover .note-card-actions { display: flex; }
.note-color-dot { width: 10px; height: 10px; border-radius: 50%; flex-shrink: 0; }
.note-card-shared-badge { background: #10B981; color: #fff; font-size: 0.65rem; padding: 2px 6px; border-radius: 10px; font-weight: 600; letter-spacing: 0.03em; }
/* Note editor toolbar */
.note-editor-toolbar { display: flex; flex-wrap: wrap; gap: 0.25rem; margin-bottom: 0.5rem; padding: 0.35rem; background: var(--bg); border-radius: 0.5rem; border: 1px solid var(--border); }
.note-toolbar-btn { background: none; border: none; cursor: pointer; padding: 4px 7px; border-radius: 4px; color: var(--text-light); font-size: 0.85rem; transition: background 0.15s, color 0.15s; }
.note-toolbar-btn:hover { background: rgba(var(--primary-rgb),0.1); color: var(--primary); }
.note-content-area { width: 100%; min-height: 160px; border: 1px solid var(--border); border-radius: 0.5rem; padding: 0.75rem; outline: none; font-size: 0.9rem; line-height: 1.6; background: var(--input-bg); color: var(--text); resize: vertical; }
.note-content-area:focus { border-color: var(--primary); box-shadow: 0 0 0 3px rgba(var(--primary-rgb),0.1); }
.note-modal-compact { padding: 1rem 1.1rem; }
.note-modal-compact .form-group { margin-bottom: 0.75rem; }
.note-modal-compact .note-editor-toolbar { margin-bottom: 0.45rem; padding: 0.28rem; }
.note-modal-compact .note-toolbar-btn { padding: 3px 6px; font-size: 0.82rem; }
.note-modal-compact .form-control { padding: 0.55rem 0.68rem; font-size: 0.88rem; }
.note-modal-compact .note-content-area { min-height: 200px; }
@media (max-width: 760px) {
.note-modal-top-fields { grid-template-columns: 1fr !important; }
}
/* Note color palette */
.note-color-palette { display: flex; gap: 0.4rem; flex-wrap: wrap; margin-top: 0.5rem; }
.color-swatch { width: 24px; height: 24px; border-radius: 50%; cursor: pointer; border: 2px solid transparent; transition: transform 0.15s, border-color 0.15s; }
.color-swatch:hover, .color-swatch.selected { transform: scale(1.2); border-color: var(--text); }
/* ── Passwords Vault / Bitwarden Style ───────────────────────────────────── */
.vault-layout { display: grid; grid-template-columns: 220px 1fr; gap: 0; min-height: 500px; }
.vault-sidebar {
background: rgba(var(--primary-rgb),0.05); border-right: 1px solid var(--border);
border-radius: 1rem 0 0 1rem; padding: 1rem; display: flex; flex-direction: column; gap: 0.25rem;
}
.vault-folder-item {
display: flex; align-items: center; gap: 0.5rem; padding: 0.5rem 0.65rem;
border-radius: 0.5rem; cursor: pointer; font-size: 0.875rem; color: var(--text);
border: none; background: none; width: 100%; text-align: left; transition: background 0.15s;
font-family: inherit;
}
.vault-folder-item:hover, .vault-folder-item.active { background: rgba(var(--primary-rgb),0.12); color: var(--primary); font-weight: 600; }
.vault-folder-item i { width: 16px; color: var(--text-light); }
.vault-folder-item.active i { color: var(--primary); }
.vault-main { padding: 1.5rem; }
.vault-search { display: flex; align-items:center; gap: 0.5rem; margin-bottom: 1rem; }
.vault-entry { display: flex; align-items: center; gap: 1rem; padding: 0.75rem; border-radius: 0.5rem; border: 1px solid transparent; transition: background 0.15s, border-color 0.15s; cursor: pointer; }
.vault-entry:hover { background: rgba(var(--primary-rgb),0.04); border-color: var(--border); }
.vault-entry-icon { width: 36px; height: 36px; border-radius: 8px; background: rgba(var(--primary-rgb),0.12); color: var(--primary); display: flex; align-items: center; justify-content: center; font-size: 0.9rem; flex-shrink: 0; overflow: hidden; }
.vault-entry-icon img { width: 100%; height: 100%; object-fit: contain; }
.vault-entry-info { flex: 1; min-width: 0; }
.vault-entry-title { font-weight: 600; font-size: 0.9rem; color: var(--text); }
.vault-entry-user { font-size: 0.78rem; color: var(--text-light); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.vault-entry-actions { display: flex; gap: 0.25rem; opacity: 0; transition: opacity 0.15s; }
.vault-entry:hover .vault-entry-actions { opacity: 1; }
/* ── Projects / Windows Explorer Detail View ─────────────────────────────── */
.explorer-toolbar { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 1rem; padding: 0.5rem; background: var(--surface); border: 1px solid var(--border); border-radius: 0.5rem; flex-wrap: wrap; }
.explorer-path { display: flex; align-items: center; gap: 0.25rem; flex: 1; min-width: 0; font-size: 0.875rem; }
.explorer-path-part { color: var(--text-light); }
.explorer-path-part.current { color: var(--text); font-weight: 600; }
.explorer-path-sep { color: var(--text-light); font-size: 0.75rem; margin: 0 2px; }
.explorer-table { width: 100%; border-collapse: collapse; }
.explorer-table thead tr { background: rgba(var(--primary-rgb),0.05); }
.explorer-table th { padding: 0.55rem 0.75rem; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--text-light); font-weight: 600; cursor: pointer; user-select: none; border-bottom: 2px solid var(--border); white-space: nowrap; }
.explorer-table th:hover { color: var(--primary); }
.explorer-table td { padding: 0.55rem 0.75rem; border-bottom: 1px solid var(--border); font-size: 0.875rem; vertical-align: middle; }
.explorer-row { transition: background 0.12s; }
.explorer-row:hover { background: rgba(var(--primary-rgb),0.04); }
.explorer-row.selected { background: rgba(var(--primary-rgb),0.1); }
.explorer-icon { font-size: 1rem; width: 22px; display: inline-block; text-align: center; }
.explorer-name { display: flex; align-items: center; gap: 0.5rem; }
.explorer-name a { font-weight: 500; color: var(--text); }
.explorer-name a:hover { color: var(--primary); text-decoration: none; }
.explorer-actions { display: flex; gap: 0.25rem; opacity: 0; transition: opacity 0.15s; }
.explorer-row:hover .explorer-actions { opacity: 1; }
.explorer-status-bar { display: flex; gap: 1rem; align-items: center; padding: 0.4rem 0.75rem; background: var(--bg); border: 1px solid var(--border); border-radius: 0.5rem; font-size: 0.78rem; color: var(--text-light); margin-top: 0.5rem; }
/* ── Admin Panel ─────────────────────────────────────────────────────────── */
.admin-tabs { display: flex; gap: 0; border-bottom: 2px solid var(--border); margin-bottom: 1.5rem; overflow-x: auto; }
.admin-tab { padding: 0.65rem 1.25rem; border: none; background: none; cursor: pointer; font-size: 0.875rem; font-weight: 600; color: var(--text-light); font-family: inherit; transition: color 0.15s; border-bottom: 2px solid transparent; margin-bottom: -2px; white-space: nowrap; }
.admin-tab.active { color: var(--primary); border-bottom-color: var(--primary); }
.admin-tab-pane { display: none; }
.admin-tab-pane.active { display: block; }
.admin-user-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 1rem; }
.admin-user-card { background: var(--bg); border: 1px solid var(--border); border-radius: 0.75rem; padding: 1rem; }
.admin-user-card-header { display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.75rem; }
.admin-user-avatar { width: 38px; height: 38px; border-radius: 50%; background: var(--primary); color: #fff; display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 1rem; overflow: hidden; flex-shrink: 0; }
.admin-badge-admin { background: rgba(79,70,229,0.1); color: var(--primary); font-size: 0.7rem; padding: 2px 8px; border-radius: 20px; font-weight: 700; letter-spacing: 0.04em; }
.admin-badge-user { background: rgba(107,114,128,0.1); color: var(--text-light); font-size: 0.7rem; padding: 2px 8px; border-radius: 20px; font-weight: 600; }
/* ── Misc utils ──────────────────────────────────────────────────────────── */
.flex-between { display: flex; justify-content: space-between; align-items: center; }
.badge { background: #EF4444; color: white; padding: 2px 6px; border-radius: 12px; font-size: 0.75rem; }
/* ── Dashboard stat card (also used in admin) ────────────────────────────── */
.db-stat-card {
background: var(--surface); border-radius: 1rem; padding: 1.25rem 1.5rem;
box-shadow: 0 4px 6px -1px rgba(0,0,0,0.07); border: 1px solid var(--border);
display: flex; flex-direction: column; gap: 0.5rem;
transition: transform 0.15s, box-shadow 0.15s;
text-decoration: none !important; color: var(--text) !important;
}
.db-stat-card:hover { transform: translateY(-3px); box-shadow: 0 8px 15px -3px rgba(0,0,0,0.1); }
/* ── Activity Log (shared) ───────────────────────────────────────────────── */
.log-item { display: flex; gap: 0.75rem; align-items: flex-start; font-size: 0.8rem; padding: 0.35rem 0; }
.log-avatar { width: 26px; height: 26px; border-radius: 50%; background: var(--primary); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 0.65rem; font-weight: 700; flex-shrink: 0; }
.log-body { flex: 1; min-width: 0; }
.log-body strong { color: var(--text); }
.log-body .log-detail { color: var(--text-light); }
.log-time { font-size: 0.7rem; color: var(--text-light); white-space: nowrap; flex-shrink: 0; }
/* ── Markdown body styles ────────────────────────────────────────────────── */
.markdown-body h1,.markdown-body h2,.markdown-body h3 { margin: 0.75rem 0 0.4rem; font-weight: 700; color: var(--text); }
.markdown-body h1 { font-size: 1.3rem; }
.markdown-body h2 { font-size: 1.1rem; }
.markdown-body h3 { font-size: 1rem; }
.markdown-body p { margin: 0.4rem 0; line-height: 1.6; }
.markdown-body ul,.markdown-body ol { padding-left: 1.5rem; margin: 0.4rem 0; }
.markdown-body li { margin: 0.2rem 0; }
.markdown-body code { background: rgba(var(--primary-rgb),0.1); padding: 2px 5px; border-radius: 4px; font-size: 0.85em; font-family: monospace; }
.markdown-body pre { background: rgba(0,0,0,0.07); padding: 0.75rem; border-radius: 6px; overflow-x: auto; }
.markdown-body pre code { background: none; padding: 0; }
body.dark-mode .markdown-body pre { background: rgba(255,255,255,0.05); }
.markdown-body blockquote { border-left: 3px solid var(--primary); padding-left: 0.75rem; color: var(--text-light); margin: 0.5rem 0; }
.markdown-body hr { border: none; border-top: 1px solid var(--border); margin: 0.75rem 0; }
.markdown-body a { color: var(--primary); }

View File

@@ -1,158 +1,756 @@
<?php
if(empty($_SESSION['is_admin'])) die("Access Denied");
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_POST['create_user'])) {
$username = $_POST['username'];
$pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
$is_admin = isset($_POST['is_admin']) ? 1 : 0;
$stmt = $pdo->prepare("INSERT INTO users (username, password_hash, is_admin) VALUES (?, ?, ?)");
$stmt->execute([$username, $pass, $is_admin]);
}
if(isset($_POST['create_group'])) {
$stmt = $pdo->prepare("INSERT INTO groups (name) VALUES (?)");
$stmt->execute([$_POST['group_name']]);
}
if(isset($_POST['assign_group'])) {
$stmt = $pdo->prepare("INSERT OR IGNORE INTO user_groups (user_id, group_id) VALUES (?, ?)");
$stmt->execute([$_POST['user_id'], $_POST['group_id']]);
}
if(isset($_POST['update_user_channels'])) {
$ch = $_POST['channels'] ?? [];
$ch_str = is_array($ch) ? implode(',', $ch) : '';
$stmt = $pdo->prepare("UPDATE users SET notify_channels=?, telegram_id=?, email=?, whatsapp_number=? WHERE id=?");
$stmt->execute([$ch_str, $_POST['telegram_id'], $_POST['email'], $_POST['whatsapp_number'], $_POST['user_id']]);
echo "<div class='alert' style='background:#10B981; color:white;'>User preferences updated!</div>";
}
if(isset($_POST['update_sys_config'])) {
$stmt = $pdo->prepare("UPDATE system_config SET v=? WHERE k=?");
$stmt->execute([$_POST['completed_days'], 'completed_days']);
$stmt->execute([$_POST['archived_days'], 'archived_days']);
echo "<div class='alert' style='background:#10B981; color:white;'>System Kanban Configuration updated!</div>";
}
}
$users = query("SELECT id, username, is_admin, notify_channels, telegram_id, email, whatsapp_number FROM users")->fetchAll();
$all_groups = query("SELECT * FROM groups")->fetchAll();
// ── DB Migrations ─────────────────────────────────────────────────────────────
try { $pdo->exec("ALTER TABLE users ADD COLUMN profile_pic TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE users ADD COLUMN waha_endpoint TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE users ADD COLUMN waha_chat_id TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE users ADD COLUMN waha_session TEXT DEFAULT 'default'"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE users ADD COLUMN waha_api_key TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE users ADD COLUMN waha_template_task TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE users ADD COLUMN waha_template_note TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE users ADD COLUMN waha_template_password TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE users ADD COLUMN waha_template_file TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE groups ADD COLUMN notify_channels TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE groups ADD COLUMN waha_endpoint TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE groups ADD COLUMN waha_chat_id TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE groups ADD COLUMN waha_api_key TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE groups ADD COLUMN waha_session TEXT DEFAULT 'default'"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE groups ADD COLUMN waha_template_task TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE groups ADD COLUMN waha_template_note TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE groups ADD COLUMN waha_template_password TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE groups ADD COLUMN waha_template_file TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE groups ADD COLUMN profile_pic TEXT DEFAULT NULL"); } catch(Exception $e) {}
try {
$pdo->exec("CREATE TABLE IF NOT EXISTS system_config (k TEXT PRIMARY KEY, v TEXT)");
$pdo->exec("INSERT OR IGNORE INTO system_config (k, v) VALUES ('completed_days', '7')");
$pdo->exec("INSERT OR IGNORE INTO system_config (k, v) VALUES ('archived_days', '90')");
} catch(Exception $e) {}
// ── Handle POST ───────────────────────────────────────────────────────────────
$success_msg = '';
$error_msg = '';
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_POST['create_user'])) {
$username = trim($_POST['username']);
$pass = password_hash($_POST['password'], PASSWORD_DEFAULT);
$is_admin = isset($_POST['is_admin']) ? 1 : 0;
try {
$stmt = $pdo->prepare("INSERT INTO users (username, password_hash, is_admin) VALUES (?, ?, ?)");
$stmt->execute([$username, $pass, $is_admin]);
$success_msg = "User '{$username}' created successfully!";
} catch(Exception $e) {
$error_msg = "Error: Username may already exist.";
}
}
if(isset($_POST['delete_user'])) {
$del_id = (int)$_POST['del_user_id'];
if($del_id != $user_id) {
$pdo->prepare("DELETE FROM users WHERE id=?")->execute([$del_id]);
$success_msg = "User deleted.";
} else {
$error_msg = "You cannot delete your own account.";
}
}
if(isset($_POST['toggle_admin'])) {
$tid = (int)$_POST['toggle_user_id'];
$newVal = (int)$_POST['new_admin_val'];
if($tid != $user_id) {
$pdo->prepare("UPDATE users SET is_admin=? WHERE id=?")->execute([$newVal, $tid]);
$success_msg = "User admin status updated.";
}
}
if(isset($_POST['create_group'])) {
try {
$name = trim($_POST['group_name']);
$pic_path = null;
if(isset($_FILES['group_pic']) && $_FILES['group_pic']['error'] === UPLOAD_ERR_OK) {
$ext = pathinfo($_FILES['group_pic']['name'], PATHINFO_EXTENSION);
$pic_path = 'uploads/group_' . time() . '_' . uniqid() . '.' . $ext;
move_uploaded_file($_FILES['group_pic']['tmp_name'], $pic_path);
}
$stmt = $pdo->prepare("INSERT INTO groups (name, profile_pic) VALUES (?, ?)");
$stmt->execute([$name, $pic_path]);
$success_msg = "Group '{$name}' created!";
} catch(Exception $e) {
$error_msg = "Error: Group name may already exist.";
}
}
if(isset($_POST['delete_group'])) {
$gid = (int)$_POST['del_group_id'];
$pdo->prepare("DELETE FROM groups WHERE id=?")->execute([$gid]);
$success_msg = "Group deleted.";
}
if(isset($_POST['assign_group'])) {
$stmt = $pdo->prepare("INSERT OR IGNORE INTO user_groups (user_id, group_id) VALUES (?, ?)");
$stmt->execute([$_POST['user_id'], $_POST['group_id']]);
$success_msg = "User assigned to group.";
}
if(isset($_POST['remove_from_group'])) {
$pdo->prepare("DELETE FROM user_groups WHERE user_id=? AND group_id=?")->execute([$_POST['user_id'], $_POST['group_id']]);
$success_msg = "User removed from group.";
}
if(isset($_POST['update_user_channels'])) {
$ch = $_POST['channels'] ?? [];
$ch_str = is_array($ch) ? implode(',', $ch) : '';
$waha_ep = trim($_POST['waha_endpoint'] ?? '');
$waha_cid = trim($_POST['waha_chat_id'] ?? '');
$waha_ses = trim($_POST['waha_session'] ?? '') ?: 'default';
$waha_key = trim($_POST['waha_api_key'] ?? '');
$tpl_task = trim($_POST['waha_template_task'] ?? '');
$tpl_note = trim($_POST['waha_template_note'] ?? '');
$tpl_pass = trim($_POST['waha_template_password'] ?? '');
$tpl_file = trim($_POST['waha_template_file'] ?? '');
$stmt = $pdo->prepare("UPDATE users SET notify_channels=?, telegram_id=?, email=?, whatsapp_number=?, waha_endpoint=?, waha_chat_id=?, waha_template_task=?, waha_template_note=?, waha_template_password=?, waha_template_file=?, waha_session=?, waha_api_key=? WHERE id=?");
$stmt->execute([$ch_str, $_POST['telegram_id'], $_POST['email'], $_POST['whatsapp_number'], $waha_ep ?: null, $waha_cid ?: null, $tpl_task ?: null, $tpl_note ?: null, $tpl_pass ?: null, $tpl_file ?: null, $waha_ses, $waha_key ?: null, $_POST['user_id']]);
$success_msg = "User notification preferences updated!";
}
if(isset($_POST['update_group_channels'])) {
$ch = $_POST['channels'] ?? [];
$ch_str = is_array($ch) ? implode(',', $ch) : '';
$waha_ep = trim($_POST['waha_endpoint'] ?? '');
$waha_cid = trim($_POST['waha_chat_id'] ?? '');
$waha_ses = trim($_POST['waha_session'] ?? '') ?: 'default';
$waha_key = trim($_POST['waha_api_key'] ?? '');
$tpl_task = trim($_POST['waha_template_task'] ?? '');
$tpl_note = trim($_POST['waha_template_note'] ?? '');
$tpl_pass = trim($_POST['waha_template_password'] ?? '');
$tpl_file = trim($_POST['waha_template_file'] ?? '');
$group_id = $_POST['group_id'];
$name = trim($_POST['group_name'] ?? '');
// Handle profile pic update
$pic_sql = "";
$pic_params = [];
if(isset($_POST['remove_pic']) && $_POST['remove_pic'] == '1') {
$old = query("SELECT profile_pic FROM groups WHERE id=?", [$group_id])->fetch();
if($old && $old['profile_pic'] && file_exists($old['profile_pic'])) @unlink($old['profile_pic']);
$pic_sql = ", profile_pic = NULL";
} elseif(isset($_FILES['group_pic']) && $_FILES['group_pic']['error'] === UPLOAD_ERR_OK) {
$old = query("SELECT profile_pic FROM groups WHERE id=?", [$group_id])->fetch();
if($old && $old['profile_pic'] && file_exists($old['profile_pic'])) @unlink($old['profile_pic']);
$ext = pathinfo($_FILES['group_pic']['name'], PATHINFO_EXTENSION);
$new_path = 'uploads/group_' . time() . '_' . uniqid() . '.' . $ext;
move_uploaded_file($_FILES['group_pic']['tmp_name'], $new_path);
$pic_sql = ", profile_pic = ?";
$pic_params[] = $new_path;
}
$sql = "UPDATE groups SET notify_channels=?, waha_endpoint=?, waha_chat_id=?, waha_template_task=?, waha_template_note=?, waha_template_password=?, waha_template_file=?, waha_session=?, waha_api_key=?, name=? $pic_sql WHERE id=?";
try {
$stmt = $pdo->prepare($sql);
$stmt->execute(array_merge([$ch_str, $waha_ep ?: null, $waha_cid ?: null, $tpl_task ?: null, $tpl_note ?: null, $tpl_pass ?: null, $tpl_file ?: null, $waha_ses, $waha_key ?: null, $name], $pic_params, [$group_id]));
$success_msg = "Group settings updated!";
} catch(Exception $e) {
$error_msg = "Error: Group name may already exist.";
}
}
if(isset($_POST['update_sys_config'])) {
$stmt = $pdo->prepare("UPDATE system_config SET v=? WHERE k=?");
$stmt->execute([$_POST['completed_days'] ?? 7, 'completed_days']);
$stmt->execute([$_POST['archived_days'] ?? 90, 'archived_days']);
$success_msg = "System configuration saved!";
}
}
// ── Fetch Data ────────────────────────────────────────────────────────────────
$users = query("SELECT id, username, is_admin, notify_channels, telegram_id, email, whatsapp_number, profile_pic, waha_endpoint, waha_chat_id, waha_template_task, waha_template_note, waha_template_password, waha_template_file, waha_session, waha_api_key FROM users ORDER BY is_admin DESC, username ASC")->fetchAll();
$all_groups = query("SELECT * FROM groups ORDER BY name")->fetchAll();
$conf_comp = query("SELECT v FROM system_config WHERE k='completed_days'")->fetchColumn() ?: 7;
$conf_arch = query("SELECT v FROM system_config WHERE k='archived_days'")->fetchColumn() ?: 90;
$waha_endpoint = query("SELECT v FROM system_config WHERE k='waha_endpoint'")->fetchColumn() ?: '';
$waha_chat_id = query("SELECT v FROM system_config WHERE k='waha_chat_id'")->fetchColumn() ?: '';
$waha_template = query("SELECT v FROM system_config WHERE k='waha_template'")->fetchColumn() ?: '';
// Activity stats for admin
$total_users = count($users);
$total_groups = count($all_groups);
$total_tasks = query("SELECT COUNT(*) FROM tasks")->fetchColumn();
$total_notes = 0; try { $total_notes = query("SELECT COUNT(*) FROM notes")->fetchColumn(); } catch(Exception $e) {}
$total_passwords = query("SELECT COUNT(*) FROM passwords")->fetchColumn();
$total_projects = query("SELECT COUNT(*) FROM projects")->fetchColumn();
// Activity log (recent, all users)
$recent_activity = [];
try {
$recent_activity = $pdo->query("SELECT al.*, u.username FROM activity_log al LEFT JOIN users u ON al.user_id=u.id ORDER BY al.created_at DESC LIMIT 20")->fetchAll();
} catch(Exception $e) {}
$active_tab = $_GET['tab'] ?? 'overview';
?>
<div class="header">
<h1>Admin Panel</h1>
<div class="header" style="margin-bottom:1rem;">
<h1 style="font-size:1.5rem; font-weight:700;"><i class="fa fa-shield-halved" style="color:var(--primary);"></i> Admin Panel</h1>
<span style="font-size:0.8rem; background:rgba(var(--primary-rgb),0.1); color:var(--primary); padding:4px 12px; border-radius:20px; font-weight:700;">ADMIN</span>
</div>
<div style="display:grid; grid-template-columns: 1fr 1fr; gap:1.5rem; margin-bottom: 2rem;">
<?php if($success_msg): ?>
<div class="alert" style="background:rgba(16,185,129,0.12); color:#10B981; border:1px solid rgba(16,185,129,0.3); margin-bottom:1rem;"><?= htmlspecialchars($success_msg) ?></div>
<?php endif; ?>
<?php if($error_msg): ?>
<div class="alert" style="margin-bottom:1rem;"><?= htmlspecialchars($error_msg) ?></div>
<?php endif; ?>
<!-- ── Tabs ──────────────────────────────────────────────────────────────── -->
<div class="admin-tabs">
<button class="admin-tab <?= $active_tab==='overview'?'active':'' ?>" onclick="switchTab('overview')"><i class="fa fa-chart-line"></i> Overview</button>
<button class="admin-tab <?= $active_tab==='users'?'active':'' ?>" onclick="switchTab('users')"><i class="fa fa-users"></i> Users</button>
<button class="admin-tab <?= $active_tab==='groups'?'active':'' ?>" onclick="switchTab('groups')"><i class="fa fa-people-group"></i> Groups</button>
<button class="admin-tab <?= $active_tab==='channels'?'active':'' ?>" onclick="switchTab('channels')"><i class="fa fa-bell"></i> Notifications</button>
<button class="admin-tab <?= $active_tab==='config'?'active':'' ?>" onclick="switchTab('config')"><i class="fa fa-gear"></i> System Config</button>
</div>
<!-- ── Overview Tab ──────────────────────────────────────────────────────── -->
<div class="admin-tab-pane <?= $active_tab==='overview'?'active':'' ?>" id="tab-overview">
<!-- Stats Grid -->
<div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(150px,1fr)); gap:1rem; margin-bottom:1.5rem;">
<?php
$stats = [
['👤','Users',$total_users,'var(--primary)'],
['👥','Groups',$total_groups,'#10B981'],
['✅','Tasks',$total_tasks,'#F59E0B'],
['📝','Notes',$total_notes,'#8B5CF6'],
['🔐','Passwords',$total_passwords,'#EF4444'],
['📁','Projects',$total_projects,'#06B6D4'],
];
foreach($stats as [$icon,$label,$val,$col]):
?>
<div class="db-stat-card" style="border-top:3px solid <?= $col ?>; gap:0.35rem; padding:1rem;">
<div style="font-size:0.75rem; color:var(--text-light); font-weight:600; text-transform:uppercase;"><?= $label ?></div>
<div style="font-size:1.8rem; font-weight:700; color:<?= $col ?>;"><?= $icon ?> <?= $val ?></div>
</div>
<?php endforeach; ?>
</div>
<!-- Recent Activity -->
<div class="card">
<h3>Create User</h3>
<form method="POST" style="margin-top:1rem;">
<div class="form-group"><input type="text" name="username" class="form-control" placeholder="Username" required></div>
<div class="form-group"><input type="password" name="password" class="form-control" placeholder="Password" required></div>
<div class="form-group">
<label><input type="checkbox" name="is_admin"> Admin Privileges</label>
<h3 style="font-size:1rem; font-weight:700; margin-bottom:1rem;">🕓 Recent Platform Activity</h3>
<?php if(empty($recent_activity)): ?>
<p style="color:var(--text-light); font-size:0.85rem;">No activity recorded yet.</p>
<?php else: ?>
<div style="display:flex; flex-direction:column; gap:0.5rem; max-height:320px; overflow-y:auto;">
<?php
$aic = ['#4F46E5','#10B981','#F59E0B','#EF4444','#8B5CF6'];
foreach($recent_activity as $log):
$t = strtotime($log['created_at']);
$diff = time()-$t;
$ago = $diff<60?'just now':($diff<3600?floor($diff/60).'m ago':($diff<86400?floor($diff/3600).'h ago':floor($diff/86400).'d ago'));
$col = $aic[crc32($log['username']??'')%count($aic)];
$init = strtoupper(mb_substr($log['username']??'S',0,1));
?>
<div class="log-item">
<div class="log-avatar" style="background:<?= $col ?>; flex-shrink:0;"><?= $init ?></div>
<div class="log-body">
<strong><?= htmlspecialchars($log['username']??'System') ?></strong>
<span class="log-detail"> · <?= htmlspecialchars($log['action']) ?><?= $log['detail']?' — '.htmlspecialchars(mb_substr($log['detail'],0,40)):'' ?></span>
</div>
<div class="log-time"><?= $ago ?></div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<button type="submit" name="create_user" class="btn">Create User</button>
</form>
</div>
<!-- ── Users Tab ─────────────────────────────────────────────────────────── -->
<div class="admin-tab-pane <?= $active_tab==='users'?'active':'' ?>" id="tab-users">
<div style="display:grid; grid-template-columns:340px 1fr; gap:1.5rem; align-items:start;">
<!-- Create User Form -->
<div class="card">
<h3>Create Group & Assign Role</h3>
<form method="POST" style="margin-top:1rem; margin-bottom:2rem;">
<div style="display:flex; gap:0.5rem;">
<input type="text" name="group_name" class="form-control" placeholder="Group Name" required>
<button type="submit" name="create_group" class="btn">Create Group</button>
</div>
</form>
<h3 style="font-size:1rem; font-weight:700; margin-bottom:1rem;"><i class="fa fa-user-plus"></i> Create New User</h3>
<form method="POST">
<div style="display:flex; gap:0.5rem; align-items:center;">
<select name="user_id" class="form-control" required style="width:130px;">
<option value="">User...</option>
<div class="form-group">
<label>Username</label>
<input type="text" name="username" class="form-control" placeholder="Enter username" required>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" placeholder="Set password" required>
</div>
<div class="form-group" style="display:flex; align-items:center; gap:0.5rem;">
<input type="checkbox" name="is_admin" id="new-user-admin" style="width:auto;">
<label for="new-user-admin" style="margin:0; font-weight:500;">Grant Admin Privileges</label>
</div>
<button type="submit" name="create_user" class="btn" style="width:100%;">
<i class="fa fa-plus"></i> Create User
</button>
</form>
</div>
<!-- User Cards -->
<div>
<h3 style="font-size:1rem; font-weight:700; margin-bottom:1rem;"><i class="fa fa-users"></i> All Users (<?= $total_users ?>)</h3>
<div class="admin-user-grid">
<?php foreach($users as $u):
$pic = $u['profile_pic'] ?? null;
$groups_of_u = query("SELECT g.name FROM groups g JOIN user_groups ug ON g.id=ug.group_id WHERE ug.user_id=?", [$u['id']])->fetchAll();
?>
<div class="admin-user-card">
<div class="admin-user-card-header">
<div class="admin-user-avatar">
<?php if($pic && file_exists($pic)): ?>
<img src="<?= htmlspecialchars($pic) ?>" style="width:100%;height:100%;object-fit:cover;border-radius:50%;" alt="">
<?php else: ?>
<?= strtoupper(mb_substr($u['username'],0,1)) ?>
<?php endif; ?>
</div>
<div style="flex:1; min-width:0;">
<div style="font-weight:700; font-size:0.9rem; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"><?= htmlspecialchars($u['username']) ?></div>
<div style="margin-top:2px;">
<span class="<?= $u['is_admin'] ? 'admin-badge-admin' : 'admin-badge-user' ?>">
<?= $u['is_admin'] ? 'Admin' : 'User' ?>
</span>
</div>
</div>
</div>
<div style="font-size:0.75rem; color:var(--text-light); margin-bottom:0.75rem;">
<?php if($groups_of_u): ?>
<i class="fa fa-users" style="margin-right:4px;"></i>
<?= implode(', ', array_map(fn($g)=>htmlspecialchars($g['name']), $groups_of_u)) ?>
<?php else: ?>
<span style="font-style:italic;">No groups</span>
<?php endif; ?>
</div>
<!-- Actions -->
<div style="display:flex; gap:0.4rem; flex-wrap:wrap;">
<?php if($u['id'] != $user_id): ?>
<!-- Toggle admin -->
<form method="POST" style="display:inline;">
<input type="hidden" name="toggle_user_id" value="<?= $u['id'] ?>">
<input type="hidden" name="new_admin_val" value="<?= $u['is_admin']?0:1 ?>">
<button type="submit" name="toggle_admin" class="btn btn-sm btn-secondary" title="<?= $u['is_admin']?'Revoke Admin':'Grant Admin' ?>">
<i class="fa fa-<?= $u['is_admin']?'user-minus':'user-shield' ?>"></i>
</button>
</form>
<!-- Delete -->
<form method="POST" style="display:inline;" onsubmit="event.preventDefault(); appConfirm('Delete user <?= htmlspecialchars(addslashes($u['username'])) ?>?').then(y => { if(y) { this.onsubmit=null; this.submit(); } })">
<input type="hidden" name="del_user_id" value="<?= $u['id'] ?>">
<button type="submit" name="delete_user" class="btn btn-sm btn-danger" title="Delete user">
<i class="fa fa-trash"></i>
</button>
</form>
<?php else: ?>
<span style="font-size:0.75rem; color:var(--primary); font-style:italic; padding:4px 0;">(You)</span>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
<!-- ── Groups Tab ────────────────────────────────────────────────────────── -->
<div class="admin-tab-pane <?= $active_tab==='groups'?'active':'' ?>" id="tab-groups">
<div style="display:grid; grid-template-columns:340px 1fr; gap:1.5rem; align-items:start;">
<!-- Create Group + Assign -->
<div>
<div class="card">
<h3 style="font-size:1rem; font-weight:700; margin-bottom:1.25rem;"><i class="fa fa-folder-plus"></i> Create Group</h3>
<form method="POST" enctype="multipart/form-data">
<div class="form-group">
<label>Group Name</label>
<input type="text" name="group_name" class="form-control" placeholder="Enter group name" required>
</div>
<div class="form-group">
<label>Profile Picture</label>
<input type="file" name="group_pic" class="form-control" accept="image/*">
</div>
<button type="submit" name="create_group" class="btn" style="width:100%"><i class="fa fa-plus"></i> Create Group</button>
</form>
</div>
<div class="card">
<h3 style="font-size:1rem; font-weight:700; margin-bottom:1rem;"><i class="fa fa-user-plus"></i> Assign User to Group</h3>
<form method="POST">
<div class="form-group">
<label>User</label>
<select name="user_id" class="form-control" required>
<option value="">Select user...</option>
<?php foreach($users as $u): ?><option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['username']) ?></option><?php endforeach; ?>
</select>
<select name="group_id" class="form-control" required style="width:130px;">
<option value="">Group...</option>
</div>
<div class="form-group">
<label>Group</label>
<select name="group_id" class="form-control" required>
<option value="">Select group...</option>
<?php foreach($all_groups as $g): ?><option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['name']) ?></option><?php endforeach; ?>
</select>
<button type="submit" name="assign_group" class="btn">Assign</button>
</div>
<button type="submit" name="assign_group" class="btn" style="width:100%;"><i class="fa fa-link"></i> Assign</button>
</form>
</div>
</div>
<!-- Groups Breakdown -->
<div>
<h3 style="font-size:1rem; font-weight:700; margin-bottom:1rem;"><i class="fa fa-people-group"></i> All Groups (<?= $total_groups ?>)</h3>
<?php if(!$all_groups): ?>
<p style="color:var(--text-light);">No groups created yet.</p>
<?php endif; ?>
<div style="display:flex; flex-direction:column; gap:1rem;">
<?php foreach($all_groups as $g):
$stmt = $pdo->prepare("SELECT u.id, u.username FROM users u JOIN user_groups ug ON u.id=ug.user_id WHERE ug.group_id=?");
$stmt->execute([$g['id']]);
$g_users = $stmt->fetchAll();
?>
<div class="card" style="margin-bottom:0;">
<form method="POST" enctype="multipart/form-data">
<input type="hidden" name="update_group_channels" value="1">
<input type="hidden" name="group_id" value="<?= $g['id'] ?>">
<input type="hidden" name="group_name" value="<?= htmlspecialchars($g['name']) ?>">
<div style="display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:0.75rem;">
<div style="display:flex; align-items:center; gap:0.75rem;">
<div class="admin-user-avatar" style="width:42px; height:42px; font-size:1rem;">
<?php if($g['profile_pic'] && file_exists($g['profile_pic'])): ?>
<img src="<?= htmlspecialchars($g['profile_pic']) ?>" style="width:100%;height:100%;object-fit:cover;border-radius:50%;">
<?php else: ?>
<?= strtoupper(mb_substr($g['name'],0,1)) ?>
<?php endif; ?>
</div>
<div>
<input type="text" name="group_name" value="<?= htmlspecialchars($g['name']) ?>" class="form-control" style="font-weight:700; font-size:1rem; color:var(--primary); background:transparent; border:none; padding:0; height:auto; width:100%;" onchange="this.form.submit()">
<div style="font-size:0.75rem; color:var(--text-light);"><?= count($g_users) ?> member<?= count($g_users)!=1?'s':'' ?></div>
</div>
</div>
<div style="display:flex; gap:0.4rem;">
<label class="btn btn-sm btn-secondary" style="cursor:pointer;" title="Change Picture">
<i class="fa fa-camera"></i>
<input type="file" name="group_pic" style="display:none;" onchange="this.form.submit()">
</label>
<?php if($g['profile_pic']): ?>
<button type="submit" name="remove_pic" value="1" class="btn btn-sm btn-secondary" title="Remove Picture" onclick="return confirm('Remove profile picture?')"><i class="fa fa-image-slash"></i></button>
<?php endif; ?>
<button type="button" class="btn btn-sm btn-danger" onclick="appConfirm('Delete group <?= htmlspecialchars(addslashes($g['name'])) ?>?').then(y => { if(y) { document.getElementById('del-group-<?= $g['id'] ?>').submit(); } })"><i class="fa fa-trash"></i></button>
</div>
</div>
<!-- Hidden inputs for templates to preserve them when updating from here -->
<div style="display:none;">
<input type="text" name="waha_endpoint" value="<?= htmlspecialchars($g['waha_endpoint']??'') ?>">
<input type="text" name="waha_chat_id" value="<?= htmlspecialchars($g['waha_chat_id']??'') ?>">
<input type="text" name="waha_session" value="<?= htmlspecialchars($g['waha_session']??'default') ?>">
<input type="text" name="waha_api_key" value="<?= htmlspecialchars($g['waha_api_key']??'') ?>">
<textarea name="waha_template_task"><?= htmlspecialchars($g['waha_template_task']??'') ?></textarea>
<textarea name="waha_template_note"><?= htmlspecialchars($g['waha_template_note']??'') ?></textarea>
<textarea name="waha_template_password"><?= htmlspecialchars($g['waha_template_password']??'') ?></textarea>
<textarea name="waha_template_file"><?= htmlspecialchars($g['waha_template_file']??'') ?></textarea>
<?php $channels = explode(',', $g['notify_channels']??''); foreach($channels as $c): if(!$c) continue; ?>
<input type="checkbox" name="channels[]" value="<?= $c ?>" checked>
<?php endforeach; ?>
</div>
</form>
<form method="POST" id="del-group-<?= $g['id'] ?>" style="display:none;"><input type="hidden" name="del_group_id" value="<?= $g['id'] ?>"><input type="hidden" name="delete_group" value="1"></form>
<?php if($g_users): ?>
<div style="display:flex; flex-wrap:wrap; gap:0.5rem;">
<?php foreach($g_users as $gu): ?>
<div style="display:flex; align-items:center; gap:0.35rem; background:rgba(var(--primary-rgb),0.07); border-radius:20px; padding:4px 10px;">
<span style="font-size:0.8rem; font-weight:600;"><?= htmlspecialchars($gu['username']) ?></span>
<form method="POST" style="display:inline;">
<input type="hidden" name="user_id" value="<?= $gu['id'] ?>">
<input type="hidden" name="group_id" value="<?= $g['id'] ?>">
<button type="submit" name="remove_from_group" class="btn btn-sm btn-danger" style="padding:1px 5px; font-size:0.7rem; border-radius:10px;" title="Remove from group">×</button>
</form>
</div>
<?php endforeach; ?>
</div>
<?php else: ?>
<p style="color:var(--text-light); font-size:0.8rem; font-style:italic;">No members yet.</p>
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
</div>
<!-- ── Notifications Tab ──────────────────────────────────────────────────── -->
<div class="admin-tab-pane <?= $active_tab==='channels'?'active':'' ?>" id="tab-channels">
<div class="card">
<h3 style="font-size:1rem; font-weight:700; margin-bottom:0.5rem;"><i class="fa fa-bell"></i> User Notification Channels</h3>
<p style="font-size:0.85rem; color:var(--text-light); margin-bottom:1.25rem;">Configure notification channels per user. WAHA settings appear when <strong>WhatsApp</strong> is enabled.</p>
<?php foreach($users as $u):
$chs = explode(',', $u['notify_channels'] ?? '');
$uid = $u['id'];
$hasWA = in_array('whatsapp', $chs);
?>
<div class="card" style="margin-bottom:1rem; padding:1rem; border:1px solid var(--border);">
<form method="POST">
<input type="hidden" name="user_id" value="<?= $uid ?>">
<!-- User header row -->
<div style="display:flex; align-items:center; gap:0.75rem; flex-wrap:wrap;">
<!-- Avatar -->
<div style="width:36px;height:36px;border-radius:50%;background:var(--primary);color:#fff;display:flex;align-items:center;justify-content:center;font-size:0.85rem;font-weight:700;flex-shrink:0;overflow:hidden;">
<?php if(($u['profile_pic']??null) && file_exists($u['profile_pic'])): ?>
<img src="<?= htmlspecialchars($u['profile_pic']) ?>" style="width:100%;height:100%;object-fit:cover;">
<?php else: ?>
<?= strtoupper(mb_substr($u['username'],0,1)) ?>
<?php endif; ?>
</div>
<!-- Name & role -->
<div style="flex:1;">
<div style="font-weight:700; font-size:0.95rem;"><?= htmlspecialchars($u['username']) ?></div>
<div><span class="<?= $u['is_admin']?'admin-badge-admin':'admin-badge-user' ?>" style="font-size:0.7rem;"><?= $u['is_admin']?'Admin':'User' ?></span></div>
</div>
<!-- Save button -->
<button type="submit" name="update_user_channels" class="btn btn-sm"><i class="fa fa-save"></i> Save</button>
</div>
<!-- Channel checkboxes -->
<div style="display:flex; gap:1rem; flex-wrap:wrap; margin-top:0.85rem; padding-top:0.75rem; border-top:1px dashed var(--border);">
<?php foreach(['native','email','telegram','whatsapp'] as $ch): ?>
<label style="display:flex; align-items:center; gap:5px; font-size:0.85rem; cursor:pointer; font-weight:500;">
<input type="checkbox" name="channels[]" value="<?= $ch ?>"
<?= in_array($ch,$chs)?'checked':'' ?>
<?= $ch==='whatsapp' ? "onchange=\"toggleWAHA({$uid}, this.checked)\"" : '' ?>>
<?php
$icons = ['native'=>'🔔','email'=>'📧','telegram'=>'✈️','whatsapp'=>'📱'];
echo $icons[$ch] . ' ' . ucfirst($ch);
?>
</label>
<?php endforeach; ?>
</div>
<!-- Extra fields row -->
<div style="display:flex; gap:1rem; flex-wrap:wrap; margin-top:0.75rem; align-items:flex-end;">
<div class="form-group" style="margin:0; min-width:130px;">
<label style="font-size:0.75rem;">Telegram ID</label>
<input type="text" name="telegram_id" value="<?= htmlspecialchars($u['telegram_id']??'') ?>" class="form-control" style="padding:0.35rem;" placeholder="@username or ID">
</div>
<div class="form-group" style="margin:0; min-width:180px;">
<label style="font-size:0.75rem;">Email</label>
<input type="email" name="email" value="<?= htmlspecialchars($u['email']??'') ?>" class="form-control" style="padding:0.35rem;" placeholder="user@example.com">
</div>
<div class="form-group" style="margin:0; min-width:140px;">
<label style="font-size:0.75rem;">WhatsApp Number</label>
<input type="text" name="whatsapp_number" value="<?= htmlspecialchars($u['whatsapp_number']??'') ?>" class="form-control" style="padding:0.35rem;" placeholder="6281234567890">
</div>
</div>
<!-- WAHA expandable section -->
<div id="waha-section-<?= $uid ?>" style="<?= $hasWA ? '' : 'display:none;' ?> margin-top:0.75rem; padding:0.85rem; background:rgba(37,211,102,0.06); border:1px solid rgba(37,211,102,0.25); border-radius:8px;">
<div style="font-size:0.78rem; font-weight:700; color:#25D366; margin-bottom:0.65rem;"><i class="fab fa-whatsapp"></i> WAHA WhatsApp API Settings</div>
<div style="display:flex; gap:1rem; flex-wrap:wrap; align-items:flex-end;">
<div class="form-group" style="margin:0; flex:2; min-width:200px;">
<label style="font-size:0.75rem;">WAHA Endpoint URL</label>
<input type="text" name="waha_endpoint" value="<?= htmlspecialchars($u['waha_endpoint']??'') ?>" class="form-control" style="padding:0.35rem;" placeholder="http://localhost:3000/api/sendText">
</div>
<div class="form-group" style="margin:0; flex:1; min-width:120px;">
<label style="font-size:0.75rem;">Session Name</label>
<input type="text" name="waha_session" value="<?= htmlspecialchars($u['waha_session'] ?? 'default') ?>" class="form-control" style="padding:0.35rem;" placeholder="default">
</div>
<div class="form-group" style="margin:0; flex:1; min-width:160px;">
<label style="font-size:0.75rem;">Chat ID</label>
<input type="text" name="waha_chat_id" value="<?= htmlspecialchars($u['waha_chat_id']??'') ?>" class="form-control" style="padding:0.35rem;" placeholder="6281234567890@c.us">
</div>
<div class="form-group" style="margin:0; flex:1; min-width:160px;">
<label style="font-size:0.75rem;">API Key <span style="font-weight:400; color:var(--text-light);">(X-Api-Key)</span></label>
<input type="password" name="waha_api_key" value="<?= htmlspecialchars($u['waha_api_key']??'') ?>" class="form-control" style="padding:0.35rem; font-family:monospace;" placeholder="Leave blank if not required">
</div>
</div>
<div style="margin-top:0.6rem;">
<label style="font-size:0.75rem;">Message Templates</label>
<div style="font-size:0.72rem; color:var(--text-light); margin-bottom:8px;">Variables: <code>{action}</code> <code>{module}</code> <code>{item}</code> <code>{user}</code> <code>{attachment_count}</code> <code>{due_date}</code> <code>{created_date}</code> <code>{updated_date}</code> <code>{assignor}</code> <code>{assignee}</code></div>
<div style="display:grid; grid-template-columns:1fr 1fr; gap:0.75rem;">
<div class="form-group" style="margin:0;">
<label style="font-size:0.7rem; color:var(--text-light);">Task</label>
<textarea name="waha_template_task" class="form-control" rows="2" style="padding:0.35rem; font-size:0.75rem;" placeholder="*Task Alert:* {action} on '{item}' by {user}"><?= htmlspecialchars($u['waha_template_task']??'') ?></textarea>
</div>
<div class="form-group" style="margin:0;">
<label style="font-size:0.7rem; color:var(--text-light);">Note</label>
<textarea name="waha_template_note" class="form-control" rows="2" style="padding:0.35rem; font-size:0.75rem;" placeholder="*Note Alert:* {action} on '{item}' by {user}"><?= htmlspecialchars($u['waha_template_note']??'') ?></textarea>
</div>
<div class="form-group" style="margin:0;">
<label style="font-size:0.7rem; color:var(--text-light);">Password</label>
<textarea name="waha_template_password" class="form-control" rows="2" style="padding:0.35rem; font-size:0.75rem;" placeholder="*Password Alert:* {action} on '{item}' by {user}"><?= htmlspecialchars($u['waha_template_password']??'') ?></textarea>
</div>
<div class="form-group" style="margin:0;">
<label style="font-size:0.7rem; color:var(--text-light);">File/Folder</label>
<textarea name="waha_template_file" class="form-control" rows="2" style="padding:0.35rem; font-size:0.75rem;" placeholder="*File Alert:* {action} on '{item}' by {user}"><?= htmlspecialchars($u['waha_template_file']??'') ?></textarea>
</div>
</div>
</div>
</div>
</form>
</div>
<?php endforeach; ?>
</div>
<!-- Group Notification Channels -->
<div class="card" style="margin-top:2rem;">
<h3 style="font-size:1rem; font-weight:700; margin-bottom:0.5rem;"><i class="fa fa-users"></i> Group Notification Channels</h3>
<p style="font-size:0.85rem; color:var(--text-light); margin-bottom:1.25rem;">Configure notification channels for an entire group. WAHA settings appear when <strong>WhatsApp</strong> is enabled.</p>
<?php foreach($all_groups as $g):
$chs = explode(',', $g['notify_channels'] ?? '');
$gid = $g['id'];
$hasWA = in_array('whatsapp', $chs);
?>
<div class="card" style="margin-bottom:1rem; padding:1rem; border:1px solid var(--border);">
<form method="POST">
<input type="hidden" name="update_group_channels" value="1">
<input type="hidden" name="group_id" value="<?= $gid ?>">
<input type="hidden" name="group_name" value="<?= htmlspecialchars($g['name']) ?>">
<!-- Group header row -->
<div style="display:flex; align-items:center; gap:0.75rem; flex-wrap:wrap;">
<div style="width:36px;height:36px;border-radius:50%;background:var(--primary);color:#fff;display:flex;align-items:center;justify-content:center;font-size:0.85rem;font-weight:700;flex-shrink:0;overflow:hidden;">
<?php if(!empty($g['profile_pic']) && file_exists($g['profile_pic'])): ?>
<img src="<?= htmlspecialchars($g['profile_pic']) ?>" style="width:100%;height:100%;object-fit:cover;">
<?php else: ?>
<?= strtoupper(mb_substr($g['name'],0,1)) ?>
<?php endif; ?>
</div>
<div style="flex:1;">
<div style="font-weight:700; font-size:0.95rem;"><?= htmlspecialchars($g['name']) ?></div>
<div><span style="font-size:0.7rem; color:var(--text-light);">Group</span></div>
</div>
<button type="submit" name="update_group_channels" class="btn btn-sm"><i class="fa fa-save"></i> Save</button>
</div>
<!-- Channel checkboxes -->
<div style="display:flex; gap:1rem; flex-wrap:wrap; margin-top:0.85rem; padding-top:0.75rem; border-top:1px dashed var(--border);">
<label style="display:flex; align-items:center; gap:5px; font-size:0.85rem; cursor:pointer; font-weight:500;">
<input type="checkbox" name="channels[]" value="whatsapp" <?= $hasWA?'checked':'' ?> onchange="toggleWAHAGroup(<?= $gid ?>, this.checked)">
📱 WhatsApp
</label>
</div>
<!-- WAHA expandable section -->
<div id="waha-group-section-<?= $gid ?>" style="<?= $hasWA ? '' : 'display:none;' ?> margin-top:0.75rem; padding:0.85rem; background:rgba(37,211,102,0.06); border:1px solid rgba(37,211,102,0.25); border-radius:8px;">
<div style="font-size:0.78rem; font-weight:700; color:#25D366; margin-bottom:0.65rem;"><i class="fab fa-whatsapp"></i> WAHA WhatsApp API Settings</div>
<div style="display:flex; gap:1rem; flex-wrap:wrap; align-items:flex-end;">
<div class="form-group" style="margin:0; flex:2; min-width:200px;">
<label style="font-size:0.75rem;">WAHA Endpoint URL</label>
<input type="text" name="waha_endpoint" value="<?= htmlspecialchars($g['waha_endpoint']??'') ?>" class="form-control" style="padding:0.35rem;" placeholder="http://localhost:3000/api/sendText">
</div>
<div class="form-group" style="margin:0; flex:1; min-width:120px;">
<label style="font-size:0.75rem;">Session Name</label>
<input type="text" name="waha_session" value="<?= htmlspecialchars($g['waha_session'] ?? 'default') ?>" class="form-control" style="padding:0.35rem;" placeholder="default">
</div>
<div class="form-group" style="margin:0; flex:1; min-width:160px;">
<label style="font-size:0.75rem;">Chat ID</label>
<input type="text" name="waha_chat_id" value="<?= htmlspecialchars($g['waha_chat_id']??'') ?>" class="form-control" style="padding:0.35rem;" placeholder="12345678@g.us">
</div>
<div class="form-group" style="margin:0; flex:1; min-width:160px;">
<label style="font-size:0.75rem;">API Key <span style="font-weight:400; color:var(--text-light);">(X-Api-Key)</span></label>
<input type="password" name="waha_api_key" value="<?= htmlspecialchars($g['waha_api_key']??'') ?>" class="form-control" style="padding:0.35rem; font-family:monospace;" placeholder="Leave blank if not required">
</div>
</div>
<div style="margin-top:0.6rem;">
<label style="font-size:0.75rem;">Message Templates</label>
<div style="font-size:0.72rem; color:var(--text-light); margin-bottom:8px;">Variables: <code>{action}</code> <code>{module}</code> <code>{item}</code> <code>{user}</code> <code>{attachment_count}</code> <code>{due_date}</code> <code>{created_date}</code> <code>{updated_date}</code> <code>{assignor}</code> <code>{assignee}</code></div>
<div style="display:grid; grid-template-columns:1fr 1fr; gap:0.75rem;">
<div class="form-group" style="margin:0;">
<label style="font-size:0.7rem; color:var(--text-light);">Task</label>
<textarea name="waha_template_task" class="form-control" rows="2" style="padding:0.35rem; font-size:0.75rem;" placeholder="*Task Alert:* {action} on '{item}' by {user}"><?= htmlspecialchars($g['waha_template_task']??'') ?></textarea>
</div>
<div class="form-group" style="margin:0;">
<label style="font-size:0.7rem; color:var(--text-light);">Note</label>
<textarea name="waha_template_note" class="form-control" rows="2" style="padding:0.35rem; font-size:0.75rem;" placeholder="*Note Alert:* {action} on '{item}' by {user}"><?= htmlspecialchars($g['waha_template_note']??'') ?></textarea>
</div>
<div class="form-group" style="margin:0;">
<label style="font-size:0.7rem; color:var(--text-light);">Password</label>
<textarea name="waha_template_password" class="form-control" rows="2" style="padding:0.35rem; font-size:0.75rem;" placeholder="*Password Alert:* {action} on '{item}' by {user}"><?= htmlspecialchars($g['waha_template_password']??'') ?></textarea>
</div>
<div class="form-group" style="margin:0;">
<label style="font-size:0.7rem; color:var(--text-light);">File/Folder</label>
<textarea name="waha_template_file" class="form-control" rows="2" style="padding:0.35rem; font-size:0.75rem;" placeholder="*File Alert:* {action} on '{item}' by {user}"><?= htmlspecialchars($g['waha_template_file']??'') ?></textarea>
</div>
</div>
</div>
</div>
</form>
</div>
<?php endforeach; ?>
</div>
</div>
<div class="card" style="grid-column: span 2;">
<h3>System Operations & Configurations</h3>
<p style="margin-top:0.5rem; color:var(--text-light);">Modify the global lifecycle durations for Kanban Auto-Archiving / Auto-Deleting processes.</p>
<form method="POST" style="margin-top:1.5rem; display:flex; gap:1.5rem; align-items:flex-end;">
<!-- ── System Config Tab ─────────────────────────────────────────────────── -->
<div class="admin-tab-pane <?= $active_tab==='config'?'active':'' ?>" id="tab-config">
<div class="card">
<h3 style="font-size:1rem; font-weight:700; margin-bottom:0.5rem;"><i class="fa fa-gear"></i> Kanban Auto-Archive Settings</h3>
<p style="font-size:0.85rem; color:var(--text-light); margin-bottom:1.5rem;">Control how long tasks stay in Completed or Archived states before being moved/deleted.</p>
<form method="POST">
<div style="display:grid; grid-template-columns:1fr 1fr; gap:1.5rem; max-width:600px;">
<div class="form-group" style="margin:0;">
<label>Completed tasks retain for (Days)</label>
<input type="number" name="completed_days" value="<?= htmlspecialchars($conf_comp) ?>" class="form-control" style="width:200px;">
<div style="font-size:0.75rem; color:var(--text-light); margin-top:4px;">Default: 7 Days (Before auto-moving to Archive)</div>
<input type="number" name="completed_days" value="<?= htmlspecialchars($conf_comp) ?>" class="form-control" min="1" max="365">
<div style="font-size:0.75rem; color:var(--text-light); margin-top:4px;">Default: 7 days (before auto-moving to Archive)</div>
</div>
<div class="form-group" style="margin:0;">
<label>Archived tasks retain for (Days)</label>
<input type="number" name="archived_days" value="<?= htmlspecialchars($conf_arch) ?>" class="form-control" style="width:200px;">
<div style="font-size:0.75rem; color:var(--text-light); margin-top:4px;">Default: 90 Days (Before permanent deletion)</div>
<input type="number" name="archived_days" value="<?= htmlspecialchars($conf_arch) ?>" class="form-control" min="1" max="3650">
<div style="font-size:0.75rem; color:var(--text-light); margin-top:4px;">Default: 90 days (before permanent deletion)</div>
</div>
<button type="submit" name="update_sys_config" class="btn">Save Database Config</button>
</div>
<button type="submit" name="update_sys_config" class="btn" style="margin-top:1.25rem;"><i class="fa fa-save"></i> Save Configuration</button>
</form>
</div>
<!-- Danger Zone -->
<div class="card" style="border:1px solid rgba(239,68,68,0.3);">
<h3 style="font-size:1rem; font-weight:700; margin-bottom:0.5rem; color:#EF4444;"><i class="fa fa-triangle-exclamation"></i> Danger Zone</h3>
<p style="font-size:0.85rem; color:var(--text-light); margin-bottom:1rem;">These actions are irreversible. Proceed with extreme caution.</p>
<div style="display:flex; gap:0.75rem; flex-wrap:wrap;">
<button class="btn btn-danger" onclick="appConfirm('Really purge all archive tasks?').then(y => { if(y) appAlert('Not implemented in this demo.'); })">
<i class="fa fa-trash"></i> Purge Archived Tasks
</button>
<button class="btn btn-danger" onclick="appConfirm('Really clear all activity logs?').then(y => { if(y) appAlert('Not implemented in this demo.'); })">
<i class="fa fa-eraser"></i> Clear Activity Logs
</button>
</div>
</div>
</div>
<div style="display:grid; grid-template-columns: 1fr; gap:1.5rem;">
<div class="card">
<h3>User Profile & Settings (Channels)</h3>
<p style="margin-bottom:1rem; color:var(--text-light);">Assign specific notification channels (Native, Telegram, Email, WhatsApp) to users. User must be created above first.</p>
<div style="overflow-x:auto;">
<table>
<thead><tr><th>Username</th><th>Active Channels</th><th>Telegram ID</th><th>Email</th><th>WhatsApp</th><th>Action</th></tr></thead>
<tbody>
<?php foreach($users as $u): ?>
<tr>
<form method="POST">
<input type="hidden" name="user_id" value="<?= $u['id'] ?>">
<td><strong><?= htmlspecialchars($u['username']) ?></strong></td>
<td style="display:flex; flex-direction:column; gap:0.25rem;">
<?php $chs = explode(',', $u['notify_channels'] ?? ''); ?>
<label><input type="checkbox" name="channels[]" value="native" <?= in_array('native', $chs)?'checked':'' ?>> Native</label>
<label><input type="checkbox" name="channels[]" value="email" <?= in_array('email', $chs)?'checked':'' ?>> Email</label>
<label><input type="checkbox" name="channels[]" value="telegram" <?= in_array('telegram', $chs)?'checked':'' ?>> TG</label>
<label><input type="checkbox" name="channels[]" value="whatsapp" <?= in_array('whatsapp', $chs)?'checked':'' ?>> WA</label>
</td>
<td><input type="text" name="telegram_id" value="<?= htmlspecialchars($u['telegram_id']??'') ?>" class="form-control" style="width:100px; padding:0.25rem;"></td>
<td><input type="email" name="email" value="<?= htmlspecialchars($u['email']??'') ?>" class="form-control" style="width:150px; padding:0.25rem;"></td>
<td><input type="text" name="whatsapp_number" value="<?= htmlspecialchars($u['whatsapp_number']??'') ?>" class="form-control" style="width:120px; padding:0.25rem;"></td>
<td><button type="submit" name="update_user_channels" class="btn btn-sm">Save</button></td>
</form>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<script>
function switchTab(name) {
document.querySelectorAll('.admin-tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.admin-tab-pane').forEach(p => p.classList.remove('active'));
document.querySelector(`[onclick="switchTab('${name}')"]`).classList.add('active');
document.getElementById('tab-'+name).classList.add('active');
const url = new URL(window.location);
url.searchParams.set('tab', name);
history.replaceState({}, '', url);
}
<div class="card">
<h3>Existing Groups Breakdown</h3>
<div style="display:flex; flex-wrap:wrap; gap:1.5rem; margin-top:1rem;">
<?php foreach($all_groups as $g): ?>
<div style="border:1px solid var(--border); border-radius:0.5rem; padding:1rem; width:250px;">
<h4 style="color:var(--primary); font-size:1.1rem; border-bottom:1px solid var(--border); padding-bottom:0.5rem; margin-bottom:0.5rem;"><?= htmlspecialchars($g['name']) ?></h4>
<ul style="padding-left:1.5rem;">
<?php
$stmt = $pdo->prepare("SELECT u.username FROM users u JOIN user_groups ug ON u.id = ug.user_id WHERE ug.group_id=?");
$stmt->execute([$g['id']]);
$g_users = $stmt->fetchAll();
foreach($g_users as $gu) echo "<li>".htmlspecialchars($gu['username'])."</li>";
if(!$g_users) echo "<li style='color:var(--text-light); list-style:none; margin-left:-1.5rem;'>No users in group</li>";
?>
</ul>
</div>
<?php endforeach; ?>
<?php if(!$all_groups): ?><p style="color:var(--text-light);">No groups registered.</p><?php endif; ?>
</div>
</div>
</div>
function toggleWAHA(uid, enabled) {
const section = document.getElementById('waha-section-' + uid);
if (!section) return;
if (enabled) {
section.style.display = 'block';
section.style.animation = 'fadeIn 0.25s ease';
} else {
section.style.display = 'none';
}
}
function toggleWAHAGroup(gid, enabled) {
const section = document.getElementById('waha-group-section-' + gid);
if (!section) return;
if (enabled) {
section.style.display = 'block';
section.style.animation = 'fadeIn 0.25s ease';
} else {
section.style.display = 'none';
}
}
</script>
<style>
@keyframes fadeIn { from { opacity:0; transform:translateY(-6px); } to { opacity:1; transform:none; } }
</style>

View File

@@ -17,7 +17,7 @@ try {
// ── Task Counts ───────────────────────────────────────────────────────────────
$user_groups = get_user_groups($user_id);
$my_group_ids = array_column($user_groups, 'id');
$group_in = implode(',', array_fill(0, max(count($my_group_ids), 1), '?')) ?: '0';
$group_in = $my_group_ids ? implode(',', array_fill(0, count($my_group_ids), '?')) : '0';
$params_tasks = array_merge([$user_id, $user_id], $my_group_ids, $my_group_ids, [$user_id]);
$sql_tasks = "SELECT status, COUNT(*) as cnt FROM tasks WHERE
(assignee_type='user' AND assignee_id=?)
@@ -52,15 +52,17 @@ try {
} catch(Exception $e) {}
// ── Current user mood ─────────────────────────────────────────────────────────
$my_mood = $current_user['mood'] ?? null;
$me = query("SELECT username, profile_pic, mood, mood_updated_at FROM users WHERE id=?", [$user_id])->fetch();
$my_mood = $me['mood'] ?? null;
// ── Team moods (all users + their mood) ──────────────────────────────────────
$team_moods = query("SELECT id, username, mood, mood_updated_at FROM users WHERE mood IS NOT NULL AND id != ? ORDER BY mood_updated_at DESC", [$user_id])->fetchAll();
$team_moods = query("SELECT id, username, mood, mood_updated_at, profile_pic FROM users WHERE mood IS NOT NULL AND id != ? ORDER BY mood_updated_at DESC", [$user_id])->fetchAll();
// ── Activity log ──────────────────────────────────────────────────────────────
// Admin: No longer sees all activity by default.
// Standard user/Admin: sees own activity + group members activity, BUT we hide admin activity from non-self.
$is_admin_user = !empty($_SESSION['is_admin']);
// ── Activity log (user + their groups, last 20) ───────────────────────────────
$recent_logs = [];
try {
// Collect relevant user IDs: current user + members of same groups
$peer_ids = [$user_id];
if ($my_group_ids) {
$gin = implode(',', array_fill(0, count($my_group_ids), '?'));
@@ -68,18 +70,40 @@ try {
$peers->execute($my_group_ids);
$peer_ids = array_unique(array_merge($peer_ids, array_column($peers->fetchAll(), 'user_id')));
}
// Ensure at least the user themselves is present
if(empty($peer_ids)) { $peer_ids = [$user_id]; }
// Get all admins except the current user
$other_admins = [];
try {
$other_admins = $pdo->prepare("SELECT id FROM users WHERE is_admin = 1 AND id != ?");
$other_admins->execute([$user_id]);
$other_admins = $other_admins->fetchAll(PDO::FETCH_COLUMN);
} catch(Exception $e) {}
// Filter out other admins from peer ids
$peer_ids = array_filter($peer_ids, function($id) use ($other_admins) {
return !in_array($id, $other_admins);
});
$uid_in = implode(',', array_fill(0, count($peer_ids), '?'));
$stmt = $pdo->prepare("SELECT al.*, u.username FROM activity_log al LEFT JOIN users u ON al.user_id=u.id WHERE al.user_id IN ($uid_in) ORDER BY al.created_at DESC LIMIT 20");
$stmt->execute($peer_ids);
$recent_logs = [];
try {
$stmt = $pdo->prepare("SELECT al.*, u.username FROM activity_log al LEFT JOIN users u ON al.user_id=u.id WHERE al.user_id IN ($uid_in) ORDER BY al.created_at DESC LIMIT 30");
$stmt->execute(array_values($peer_ids));
$recent_logs = $stmt->fetchAll();
} catch(Exception $e) {}
// ── Auto-log task changes for history (read recent task status changes) ───────
// ── Task logs ─────────────────────────────────────────────────────────────────
$task_logs = [];
try {
// Include group-assigned tasks too
$group_in_tl = $my_group_ids ? implode(',', array_fill(0, count($my_group_ids), '?')) : '0';
$tl_params = array_merge([$user_id, $user_id], $my_group_ids, $my_group_ids);
$admin_excl = $other_admins ? "AND t.assignor_id NOT IN (" . implode(',', array_fill(0, count($other_admins), '?')) . ")" : "";
if($other_admins) { $tl_params = array_merge($tl_params, $other_admins); }
$stmt = $pdo->prepare("SELECT t.title, t.status, t.status_updated_at, u.username as assignor
FROM tasks t LEFT JOIN users u ON t.assignor_id=u.id
WHERE t.status_updated_at IS NOT NULL
@@ -88,6 +112,7 @@ try {
OR (t.assignee_type='group' AND t.assignee_id IN ($group_in_tl))
OR (t.assignor_type='group' AND t.assignor_group_id IN ($group_in_tl))
)
$admin_excl
ORDER BY t.status_updated_at DESC LIMIT 30");
$stmt->execute($tl_params);
$task_logs = $stmt->fetchAll();
@@ -95,7 +120,7 @@ try {
?>
<style>
.db-grid { display:grid; grid-template-columns:repeat(auto-fit, minmax(220px,1fr)); gap:1.25rem; margin-bottom:1.5rem; }
.db-grid { display:grid; grid-template-columns:repeat(auto-fit, minmax(200px,1fr)); gap:1.25rem; margin-bottom:1.5rem; }
.db-stat-card {
background:var(--surface); border-radius:1rem; padding:1.25rem 1.5rem;
box-shadow:0 4px 6px -1px rgba(0,0,0,0.07); border:1px solid var(--border);
@@ -103,10 +128,10 @@ try {
text-decoration:none !important; color:var(--text) !important;
}
.db-stat-card:hover { transform:translateY(-3px); box-shadow:0 8px 15px -3px rgba(0,0,0,0.1); }
.db-stat-label { font-size:0.8rem; color:var(--text-light); font-weight:500; text-transform:uppercase; letter-spacing:0.04em; }
.db-stat-label { font-size:0.78rem; color:var(--text-light); font-weight:600; text-transform:uppercase; letter-spacing:0.05em; display:flex; align-items:center; gap:0.4rem; }
.db-stat-value { font-size:2.2rem; font-weight:700; line-height:1; }
.db-stat-sub { display:flex; gap:1rem; flex-wrap:wrap; margin-top:0.35rem; }
.db-stat-sub span { font-size:0.75rem; font-weight:600; padding:2px 8px; border-radius:20px; }
.db-stat-sub { display:flex; gap:0.5rem; flex-wrap:wrap; margin-top:0.35rem; }
.db-stat-sub span { font-size:0.72rem; font-weight:600; padding:2px 8px; border-radius:20px; }
.db-stat-link { font-size:0.78rem; color:var(--primary); margin-top:auto; font-weight:500; }
/* Welcome banner */
@@ -118,21 +143,6 @@ try {
.db-welcome h2 { font-size:1.4rem; font-weight:700; }
.db-welcome p { font-size:0.875rem; opacity:0.85; margin-top:0.25rem; }
/* Holiday strip */
.db-holiday {
background:var(--surface); border:1px solid var(--border); border-radius:0.75rem;
padding:0.75rem 1.25rem; display:flex; align-items:center; gap:0.75rem;
font-size:0.875rem; margin-bottom:1.5rem; overflow:hidden;
}
.db-holiday-list {
display:flex; gap:1.5rem; overflow-x:auto; flex:1; padding-bottom:2px;
scrollbar-width:thin;
}
.db-holiday-item { flex-shrink:0; display:flex; align-items:center; gap:0.4rem; white-space:nowrap; }
.db-holiday-date { font-size:0.7rem; background:rgba(var(--primary-rgb),0.1); color:var(--primary); padding:2px 6px; border-radius:6px; font-weight:600; }
.db-holiday-name { color:var(--text); font-weight:500; }
.db-holiday-country { font-size:0.7rem; color:var(--text-light); }
/* Mood picker */
.mood-row { display:flex; gap:0.4rem; flex-wrap:wrap; align-items:center; }
.mood-btn {
@@ -142,8 +152,8 @@ try {
transition:transform 0.15s, border-color 0.15s, background 0.15s;
line-height:1;
}
.mood-btn:hover { transform:scale(1.15); background:rgba(var(--primary-rgb),0.08); }
.mood-btn.active { border-color:var(--primary); background:rgba(var(--primary-rgb),0.12); transform:scale(1.1); }
.mood-btn:hover { transform:scale(1.15); background:rgba(255,255,255,0.15); }
.mood-btn.active { border-color:rgba(255,255,255,0.9); background:rgba(255,255,255,0.2); transform:scale(1.1); }
/* Team moods */
.team-mood-row { display:flex; flex-wrap:wrap; gap:0.6rem; }
@@ -155,8 +165,8 @@ try {
.team-mood-chip .em { font-size:1.2rem; }
/* Activity log */
.log-list { display:flex; flex-direction:column; gap:0.5rem; overflow-y:auto; flex:1; }
.log-item { display:flex; gap:0.75rem; align-items:flex-start; font-size:0.8rem; flex-shrink:0; }
.log-list { display:flex; flex-direction:column; gap:0.5rem; overflow-y:auto; flex:1; max-height:360px; }
.log-item { display:flex; gap:0.75rem; align-items:flex-start; font-size:0.8rem; flex-shrink:0; padding:0.35rem 0; }
.log-avatar { width:26px; height:26px; border-radius:50%; background:var(--primary); color:#fff; display:flex; align-items:center; justify-content:center; font-size:0.65rem; font-weight:700; flex-shrink:0; }
.log-body { flex:1; min-width:0; }
.log-body strong { color:var(--text); }
@@ -164,16 +174,18 @@ try {
.log-time { font-size:0.7rem; color:var(--text-light); white-space:nowrap; flex-shrink:0; }
/* Full-height bottom section */
.db-wrapper { display:flex; flex-direction:column; min-height:calc(100vh - 4rem); }
.db-wrapper { display:flex; flex-direction:column; }
.two-col {
display:grid; grid-template-columns:1fr 1fr; gap:1.25rem;
flex:1; min-height:0;
}
.two-col > .card {
margin-bottom:0; display:flex; flex-direction:column;
min-height:0; /* allow shrink inside grid */
min-height:0;
}
@media(max-width:720px){ .two-col { grid-template-columns:1fr; } }
.admin-activity-badge { display:inline-flex; align-items:center; gap:0.4rem; font-size:0.7rem; padding:2px 8px; border-radius:12px; background:rgba(239,68,68,0.1); color:#EF4444; font-weight:700; }
</style>
<?php
@@ -225,7 +237,7 @@ if (empty($_SESSION['dash_logged_today'])) {
</div>
</div>
<!-- ── Today's Holiday Badge (injected by JS into welcome banner) ──────────── -->
<!-- ── Today's Holiday Badge ──────────────────────────────────────────────── -->
<div id="today-holiday-banner" style="display:none; margin-bottom:1rem; padding:0.6rem 1.25rem; background:linear-gradient(90deg,rgba(245,158,11,0.12),rgba(16,185,129,0.08)); border:1px solid rgba(245,158,11,0.3); border-radius:0.75rem; align-items:center; gap:0.75rem; font-size:0.875rem;">
<span style="font-size:1.3rem;">🎉</span>
<div>
@@ -264,11 +276,11 @@ if (empty($_SESSION['dash_logged_today'])) {
<div class="db-stat-link">Open Vault →</div>
</a>
<!-- Projects -->
<!-- Files -->
<a href="?action=projects" class="db-stat-card" style="border-top:3px solid #F59E0B;">
<div class="db-stat-label">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"></path></svg>
Projects & Files
Files
</div>
<div class="db-stat-value" style="color:#F59E0B;"><?= $projects_count ?></div>
<div class="db-stat-sub">
@@ -289,41 +301,89 @@ if (empty($_SESSION['dash_logged_today'])) {
</div>
<div class="db-stat-link">Open Notes →</div>
</a>
<!-- Tools -->
<a href="?action=tools" class="db-stat-card" style="border-top:3px solid #EC4899;">
<div class="db-stat-label">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 9.36l-7.1 7.1a1 1 0 0 1-1.4 0l-2.8-2.8a1 1 0 0 1 0-1.4l7.1-7.1a6 6 0 0 1 9.36-7.94z"></path></svg>
Tools
</div>
<div class="db-stat-value" style="color:#EC4899;">3</div>
<div class="db-stat-sub">
<span style="background:rgba(236,72,153,0.12); color:#EC4899;">🛠 Utilities</span>
</div>
<div class="db-stat-link">Open Tools →</div>
</a>
</div>
<!-- ── Team Moods + Activity Log ───────────────────────────────────────────── -->
<div class="two-col">
<!-- Team Moods -->
<div class="card">
<!-- ── Team Moods ───────────────────────────────────────────── -->
<div class="card" style="margin-bottom:1.5rem;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem;">
<h3 style="font-size:1rem; font-weight:700;">👥 Team Mood</h3>
<span style="font-size:0.75rem; color:var(--text-light); font-style:italic;">Live from colleagues</span>
</div>
<?php if(empty($team_moods)): ?>
<p style="color:var(--text-light); font-size:0.85rem;">No one else has set a mood yet.</p>
<?php if(empty($team_moods) && empty($my_mood)): ?>
<p style="color:var(--text-light); font-size:0.85rem;">No team mood activity yet.</p>
<?php else: ?>
<div class="team-mood-row">
<?php foreach($team_moods as $tm): ?>
<div class="team-mood-chip" title="Updated: <?= date('M j, H:i', strtotime($tm['mood_updated_at'])) ?>">
<span class="em"><?= $tm['mood'] ?></span>
<span><?= htmlspecialchars($tm['username']) ?></span>
<div class="team-mood-row" style="display:flex; flex-wrap:nowrap; overflow-x:auto; gap:1rem; padding-bottom:0.5rem;">
<?php
$avatar_colors_tm = ['#4F46E5','#10B981','#F59E0B','#EF4444','#8B5CF6','#06B6D4','#EC4899','#84CC16'];
if(!empty($my_mood)):
$m_initial = strtoupper(mb_substr($me['username'], 0, 1));
$m_color = $avatar_colors_tm[crc32($me['username']) % count($avatar_colors_tm)];
?>
<div style="position:relative; flex-shrink:0; cursor:pointer;" title="You (Updated: <?= date('M j, H:i', strtotime($me['mood_updated_at'])) ?>)">
<div style="width:40px; height:40px; border-radius:50%; background:<?= $m_color ?>; color:#fff; display:flex; align-items:center; justify-content:center; font-weight:700; font-size:1rem; overflow:hidden;">
<?php if(!empty($me['profile_pic']) && file_exists($me['profile_pic'])): ?>
<img src="<?= htmlspecialchars($me['profile_pic']) ?>?v=<?= time() ?>" style="width:100%; height:100%; object-fit:cover;">
<?php else: ?>
<?= $m_initial ?>
<?php endif; ?>
</div>
<div style="position:absolute; top:-4px; right:-4px; background:var(--surface); border-radius:50%; width:20px; height:20px; display:flex; align-items:center; justify-content:center; font-size:0.8rem; box-shadow:0 2px 4px rgba(0,0,0,0.1);">
<?= $my_mood ?>
</div>
<div style="font-size:0.65rem; color:var(--text-light); text-align:center; margin-top:4px; max-width:40px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; font-style:italic;">
You
</div>
</div>
<?php endif; ?>
<?php
foreach($team_moods as $tm):
$initial = strtoupper(mb_substr($tm['username'], 0, 1));
$color = $avatar_colors_tm[crc32($tm['username']) % count($avatar_colors_tm)];
?>
<div style="position:relative; flex-shrink:0; cursor:pointer;" title="<?= htmlspecialchars($tm['username']) ?> (Updated: <?= date('M j, H:i', strtotime($tm['mood_updated_at'])) ?>)">
<div style="width:40px; height:40px; border-radius:50%; background:<?= $color ?>; color:#fff; display:flex; align-items:center; justify-content:center; font-weight:700; font-size:1rem; overflow:hidden;">
<?php if(!empty($tm['profile_pic']) && file_exists($tm['profile_pic'])): ?>
<img src="<?= htmlspecialchars($tm['profile_pic']) ?>?v=<?= time() ?>" style="width:100%; height:100%; object-fit:cover;">
<?php else: ?>
<?= $initial ?>
<?php endif; ?>
</div>
<div style="position:absolute; top:-4px; right:-4px; background:var(--surface); border-radius:50%; width:20px; height:20px; display:flex; align-items:center; justify-content:center; font-size:0.8rem; box-shadow:0 2px 4px rgba(0,0,0,0.1);">
<?= $tm['mood'] ?>
</div>
<div style="font-size:0.65rem; color:var(--text-light); text-align:center; margin-top:4px; max-width:40px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
<?= htmlspecialchars($tm['username']) ?>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if($my_mood): ?>
<div style="margin-top:1rem; padding-top:0.75rem; border-top:1px dashed var(--border); font-size:0.8rem; color:var(--text-light);">
Your mood is visible to your team: <strong style="color:var(--text);"><?= $my_mood ?></strong>
</div>
<?php endif; ?>
</div>
<!-- Activity Log -->
<div class="card">
<!-- ── Activity Log ───────────────────────────────────────────── -->
<div class="card" style="flex:1; display:flex; flex-direction:column; min-height:0;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem;">
<div style="display:flex; align-items:center; gap:0.65rem;">
<h3 style="font-size:1rem; font-weight:700;">🕓 Recent Activity</h3>
<span style="font-size:0.75rem; color:var(--text-light);">You & your groups</span>
</div>
<span style="font-size:0.75rem; color:var(--text-light);">
You & your groups
</span>
</div>
<?php
// Merge activity_log + task_logs into one unified feed sorted by time
@@ -346,13 +406,18 @@ if (empty($_SESSION['dash_logged_today'])) {
];
}
usort($feed, fn($a,$b) => strtotime($b['time']) - strtotime($a['time']));
$feed = array_slice($feed, 0, 30);
$feed = array_slice($feed, 0, $is_admin_user ? 50 : 30);
$action_icons = [
'visit' => '🌐',
'mood_set' => '😊',
'task_status' => '✅',
'note_create' => '📝',
'pw_add' => '🔐',
];
// Generate avatar color based on username hash
$avatar_colors = ['#4F46E5','#10B981','#F59E0B','#EF4444','#8B5CF6','#06B6D4','#EC4899','#84CC16'];
?>
<?php if(empty($feed)): ?>
<p style="color:var(--text-light); font-size:0.85rem;">No activity yet.</p>
@@ -362,9 +427,10 @@ if (empty($_SESSION['dash_logged_today'])) {
$initial = strtoupper(mb_substr($entry['user'], 0, 1));
$icon = $action_icons[$entry['action']] ?? '🔔';
$ago = human_time_diff(strtotime($entry['time']));
$color = $avatar_colors[crc32($entry['user']) % count($avatar_colors)];
?>
<div class="log-item">
<div class="log-avatar"><?= $initial ?></div>
<div class="log-avatar" style="background:<?= $color ?>;"><?= $initial ?></div>
<div class="log-body">
<strong><?= htmlspecialchars($entry['user']) ?></strong>
<span class="log-detail"> <?= $icon ?> <?= htmlspecialchars($entry['detail']) ?></span>
@@ -376,7 +442,6 @@ if (empty($_SESSION['dash_logged_today'])) {
<?php endif; ?>
</div>
</div>
</div><!-- .db-wrapper -->
<script>
@@ -384,7 +449,7 @@ if (empty($_SESSION['dash_logged_today'])) {
function updateTime() {
const now = new Date();
const el = document.getElementById('current-datetime');
if (el) el.textContent = now.toLocaleString('id-ID', {
if (el) el.textContent = now.toLocaleString('en-US', {
weekday:'long', year:'numeric', month:'long', day:'numeric',
hour:'2-digit', minute:'2-digit', second:'2-digit'
});
@@ -396,7 +461,6 @@ function selectMood(em) {
document.getElementById('mood-value').value = em;
document.querySelectorAll('.mood-btn').forEach(b => b.classList.remove('active'));
if (em) {
// Find the button whose text equals em
document.querySelectorAll('.mood-btn').forEach(b => {
if (b.textContent.trim() === em) b.classList.add('active');
});
@@ -404,10 +468,10 @@ function selectMood(em) {
document.getElementById('mood-form').submit();
}
// ── Holiday check: is TODAY a holiday in Indonesia (ID) or Internationally (UN)?
// ── Holiday check ─────────────────────────────────────────────────────────────
(function checkTodayHoliday() {
const year = new Date().getFullYear();
const today = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
const today = new Date().toISOString().slice(0, 10);
const urls = [
{ url: `https://date.nager.at/api/v3/PublicHolidays/${year}/ID`, flag: '🇮🇩', label: 'Indonesia' },
@@ -434,7 +498,6 @@ function selectMood(em) {
labelEl.textContent = '— Today is a holiday! 🎊';
banner.style.display = 'flex';
}
// If no holiday today, banner stays hidden (display:none)
});
})();
</script>

View File

@@ -2,7 +2,7 @@
</main>
</div>
<script>
// Dark Mode Toggle
// ── Dark Mode Toggle ──────────────────────────────────────────────────
const themeBtn = document.getElementById('theme-toggle');
const iconLight = document.getElementById('theme-icon-light');
const iconDark = document.getElementById('theme-icon-dark');
@@ -16,7 +16,6 @@
iconDark.style.display = 'block';
}
}
if(themeBtn) {
updateThemeIcon();
themeBtn.addEventListener('click', () => {
@@ -27,13 +26,135 @@
});
}
// Toast Notifier
// ── Toast ─────────────────────────────────────────────────────────────
function showToast(msg) {
const t = document.getElementById('toast');
t.textContent = msg;
t.classList.add('show');
setTimeout(() => t.classList.remove('show'), 3000);
}
// ── Custom Alert / Confirm ─────────────────────────────────────────────
function appAlert(msg) {
return new Promise(resolve => {
let modal = document.getElementById('app-alert-modal');
if(!modal) {
modal = document.createElement('div');
modal.id = 'app-alert-modal';
modal.className = 'modal-overlay';
modal.style.zIndex = '10005';
modal.innerHTML = `
<div class="modal-content" style="max-width:320px; text-align:center;">
<h3 style="margin-bottom:1rem; font-size:1.1rem;">Notice</h3>
<p style="margin-bottom:1.5rem; font-size:0.9rem; color:var(--text);" id="app-alert-msg"></p>
<button class="btn" style="width:100%;" id="app-alert-ok">OK</button>
</div>`;
document.body.appendChild(modal);
}
document.getElementById('app-alert-msg').textContent = msg;
modal.classList.add('active');
document.getElementById('app-alert-ok').onclick = () => { modal.classList.remove('active'); resolve(true); };
});
}
window.alert = function(msg) { appAlert(msg); };
function appConfirm(msg) {
return new Promise(resolve => {
let modal = document.getElementById('app-confirm-modal');
if(!modal) {
modal = document.createElement('div');
modal.id = 'app-confirm-modal';
modal.className = 'modal-overlay';
modal.style.zIndex = '10005';
modal.innerHTML = `
<div class="modal-content" style="max-width:350px;">
<h3 style="margin-bottom:0.75rem; font-size:1.1rem; text-align:center;">Confirmation</h3>
<p style="margin-bottom:1.5rem; font-size:0.95rem; color:var(--text); text-align:center; line-height:1.4;" id="app-confirm-msg"></p>
<div style="display:flex; gap:0.5rem;">
<button class="btn btn-secondary" style="flex:1;" id="app-confirm-no">Cancel</button>
<button class="btn btn-danger" style="flex:1;" id="app-confirm-yes">Confirm</button>
</div>
</div>`;
document.body.appendChild(modal);
}
document.getElementById('app-confirm-msg').textContent = msg;
modal.classList.add('active');
document.getElementById('app-confirm-no').onclick = () => { modal.classList.remove('active'); resolve(false); };
document.getElementById('app-confirm-yes').onclick = () => { modal.classList.remove('active'); resolve(true); };
});
}
function appConfirmUrl(event, url, msg) {
event.preventDefault();
appConfirm(msg).then(yes => { if(yes) window.location.href = url; });
}
// ── Sidebar Collapse ──────────────────────────────────────────────────
function toggleSidebar() {
const collapsed = document.body.classList.toggle('sidebar-collapsed');
localStorage.setItem('sidebar_collapsed', collapsed ? '1' : '0');
updateSidebarIcon();
}
function updateSidebarIcon() {
const icon = document.getElementById('sidebar-toggle-icon');
if(!icon) return;
if(document.body.classList.contains('sidebar-collapsed')) {
icon.className = 'fa fa-chevron-right';
} else {
icon.className = 'fa fa-chevron-left';
}
}
updateSidebarIcon();
// ── User Dropdown ─────────────────────────────────────────────────────
function toggleUserDropdown() {
const menu = document.getElementById('user-dropdown-menu');
menu.classList.toggle('open');
}
function closeUserDropdown() {
const menu = document.getElementById('user-dropdown-menu');
if(menu) menu.classList.remove('open');
}
document.addEventListener('click', (e) => {
const wrap = document.getElementById('user-dropdown-wrap');
if (wrap && !wrap.contains(e.target)) closeUserDropdown();
});
// ── Notifications ─────────────────────────────────────────────────────
function openNotifications() {
closeUserDropdown();
document.getElementById('notifications-modal').classList.add('active');
}
// ── Close modals on overlay click ─────────────────────────────────────
document.querySelectorAll('.modal-overlay').forEach(mo => {
mo.addEventListener('click', (e) => {
if (e.target === mo) mo.classList.remove('active');
});
});
// ── Auto open change-pw modal if error ────────────────────────────────
<?php
$pw_msg_bottom = $_SESSION['pw_change_msg_bottom'] ?? null;
if($pw_msg_bottom):
?>
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('change-pw-modal').classList.add('active');
});
<?php endif; ?>
// ── Tagify globally ───────────────────────────────────────────────────
document.addEventListener('DOMContentLoaded', () => {
if(typeof Tagify !== 'undefined' && window.APP_GLOBAL_TAGS) {
document.querySelectorAll('.tagify-input').forEach(el => {
new Tagify(el, {
whitelist: window.APP_GLOBAL_TAGS,
dropdown: { maxItems: 20, classname: "tags-look", enabled: 0, closeOnSelect: false },
originalInputValueFormat: valuesArr => valuesArr.map(item => item.value).join(',')
});
});
}
});
</script>
</body>
</html>

View File

@@ -7,41 +7,271 @@
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="public/css/style.css">
<script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify"></script>
<link href="https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/themes/dark.css">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<style>
.tags-look .tagify__dropdown__item{ display: inline-block; border-radius: 3px; padding: .3em .5em; border: 1px solid var(--border); background: var(--surface); margin: .2em; font-size: .85em; transition: 0s; color: var(--text); }
.tags-look .tagify__dropdown__item--active{ color: white; background: var(--primary); border-color: var(--primary); }
.tags-look .tagify__dropdown__item:hover{ background: var(--primary); color: white; border-color: var(--primary); }
/* Premium Dark Mode Tagify Sync */
.tagify { --tag-bg: rgba(var(--primary-rgb), 0.2); --tag-text-color: var(--text); --tag-hover: rgba(var(--primary-rgb), 0.3); --placeholder-color: var(--text-light); }
body.dark-mode .tagify { --tag-bg: #2d3748; --tag-text-color: #e2e8f0; --tag-hover: #4a5568; }
.tagify__tag > div { background: var(--tag-bg); color: var(--tag-text-color); border-radius: 6px; }
.tagify__tag:hover:not([readonly]) > div::before { background: var(--tag-hover); }
.tagify__dropdown { background: rgba(30, 41, 59, 0.95); backdrop-filter: blur(8px); border: 1px solid var(--border); border-radius: 8px; }
.tagify__dropdown__wrapper { background: transparent; border: none; }
</style>
<?php
date_default_timezone_set('Etc/GMT-7');
$all_app_tags = [];
try {
$rows = $pdo->query("SELECT label_name as tag FROM notes WHERE label_name IS NOT NULL AND label_name != ''")->fetchAll();
foreach($rows as $r) { foreach(explode(',', $r['tag']) as $p) { $all_app_tags[trim($p)] = 1; } }
$rows = $pdo->query("SELECT tags as tag FROM tasks WHERE tags IS NOT NULL AND tags != ''")->fetchAll();
foreach($rows as $r) { foreach(explode(',', $r['tag']) as $p) { $all_app_tags[trim($p)] = 1; } }
} catch(Exception $e) {}
$global_tags = array_keys($all_app_tags);
?>
<script>
window.APP_GLOBAL_TAGS = <?= json_encode(array_filter($global_tags)) ?>;
</script>
</head>
<body>
<script>if(localStorage.getItem('theme') === 'dark') document.body.classList.add('dark-mode');</script>
<script>
if(localStorage.getItem('theme') === 'dark') document.body.classList.add('dark-mode');
if(localStorage.getItem('sidebar_collapsed') === '1') document.body.classList.add('sidebar-collapsed');
</script>
<div id="toast"></div>
<div class="app-container">
<aside class="sidebar">
<h2 style="display:flex; align-items:center; gap:8px;">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
TaskManager
</h2>
<nav style="display:flex; flex-direction:column; gap:0.5rem;">
<a href="?action=dashboard" class="nav-link <?= $action=='dashboard'?'active':'' ?>"> Dashboard</a>
<a href="?action=tasks" class="nav-link <?= $action=='tasks'?'active':'' ?>"> Tasks</a>
<a href="?action=notes" class="nav-link <?= $action=='notes'?'active':'' ?>"> Notes</a>
<a href="?action=passwords" class="nav-link <?= $action=='passwords'?'active':'' ?>"> Passwords</a>
<a href="?action=projects" class="nav-link <?= $action=='projects'?'active':'' ?>"> Projects</a>
<a href="?action=notifications" class="nav-link <?= $action=='notifications'?'active':'' ?>">
Notifications
<?php if($unread_notifications > 0): ?>
<span class="badge"><?= $unread_notifications ?></span>
<!-- Profile Picture Modal -->
<div class="modal-overlay" id="profile-pic-modal">
<div class="modal-content" style="max-width:420px;">
<h3 style="margin-bottom:1rem; font-size:1.1rem;">Profile Picture</h3>
<div style="display:flex; flex-direction:column; align-items:center; gap:1rem; margin-bottom:1.5rem;">
<?php
try { $pdo->exec("ALTER TABLE users ADD COLUMN profile_pic TEXT DEFAULT NULL"); } catch(Exception $e) {}
$pic = $current_user['profile_pic'] ?? null;
?>
<?php if($pic && file_exists($pic)): ?>
<img src="<?= htmlspecialchars($pic) ?>" alt="Profile" style="width:100px; height:100px; border-radius:50%; object-fit:cover; border:3px solid var(--primary);">
<?php else: ?>
<div style="width:100px; height:100px; border-radius:50%; background:var(--primary); display:flex; align-items:center; justify-content:center; font-size:2.5rem; color:#fff; font-weight:700;">
<?= strtoupper(mb_substr($current_user['username'],0,1)) ?>
</div>
<?php endif; ?>
</div>
<form method="POST" enctype="multipart/form-data" style="margin-bottom:1rem;">
<input type="hidden" name="upload_profile_pic" value="1">
<input type="hidden" name="redirect_to" value="<?= htmlspecialchars($action) ?>">
<div class="form-group">
<label style="font-size:0.875rem; color:var(--text-light);">Upload New Picture (JPG, PNG, GIF, WebP)</label>
<input type="file" name="profile_pic" accept="image/*" class="form-control" style="margin-top:0.5rem;" required>
</div>
<button type="submit" class="btn" style="width:100%;">Upload Picture</button>
</form>
<?php if($pic && file_exists($pic)): ?>
<form method="POST">
<input type="hidden" name="delete_profile_pic" value="1">
<input type="hidden" name="redirect_to" value="<?= htmlspecialchars($action) ?>">
<button type="button" class="btn btn-danger" style="width:100%;" onclick="appConfirm('Delete profile picture?').then(y => { if(y) this.form.submit(); })">Delete Picture</button>
</form>
<?php endif; ?>
<button class="btn btn-secondary" style="width:100%; margin-top:0.5rem;" onclick="document.getElementById('profile-pic-modal').classList.remove('active')">Close</button>
</div>
</div>
<!-- Change Password Modal -->
<div class="modal-overlay" id="change-pw-modal">
<div class="modal-content" style="max-width:400px;">
<h3 style="margin-bottom:1rem; font-size:1.1rem;">Change Password</h3>
<?php
$pw_msg = $_SESSION['pw_change_msg'] ?? null;
unset($_SESSION['pw_change_msg']);
if ($pw_msg === 'success'): ?>
<div class="alert" style="background:rgba(16,185,129,0.12); color:#10B981; border:1px solid #10B981;">Password changed successfully!</div>
<?php elseif($pw_msg): ?>
<div class="alert"><?= htmlspecialchars($pw_msg) ?></div>
<?php endif; ?>
<form method="POST">
<input type="hidden" name="change_password" value="1">
<input type="hidden" name="redirect_to" value="<?= htmlspecialchars($action) ?>">
<div class="form-group">
<label>Current Password</label>
<input type="password" name="current_password" class="form-control" required>
</div>
<div class="form-group">
<label>New Password</label>
<input type="password" name="new_password" class="form-control" required minlength="6">
</div>
<div class="form-group">
<label>Confirm New Password</label>
<input type="password" name="confirm_password" class="form-control" required minlength="6">
</div>
<button type="submit" class="btn" style="width:100%;">Change Password</button>
</form>
<button class="btn btn-secondary" style="width:100%; margin-top:0.5rem;" onclick="document.getElementById('change-pw-modal').classList.remove('active')">Cancel</button>
</div>
</div>
<!-- Notifications Modal -->
<?php
// Fetch notifications for popup
$notif_list = [];
try {
$stmt_n = $pdo->prepare("SELECT * FROM notifications WHERE user_id=? ORDER BY created_at DESC LIMIT 30");
$stmt_n->execute([$user_id]);
$notif_list = $stmt_n->fetchAll();
} catch(Exception $e) {}
?>
<div class="modal-overlay" id="notifications-modal">
<div class="modal-content" style="max-width:460px; max-height:80vh; display:flex; flex-direction:column; padding:0; overflow:hidden;">
<div style="display:flex; justify-content:space-between; align-items:center; padding:1.25rem 1.5rem; border-bottom:1px solid var(--border);">
<h3 style="font-size:1.05rem; font-weight:700;"><i class="fa fa-bell" style="color:var(--primary);"></i> Notifications</h3>
<div style="display:flex; gap:0.5rem; align-items:center;">
<?php if($unread_notifications > 0): ?>
<form method="POST" id="mark-all-read-form" style="display:inline;">
<input type="hidden" name="mark_all_read" value="1">
<input type="hidden" name="redirect_to" value="<?= htmlspecialchars($action) ?>">
<button type="submit" class="btn btn-sm btn-secondary" style="font-size:0.75rem;">Mark all read</button>
</form>
<?php endif; ?>
<button onclick="document.getElementById('notifications-modal').classList.remove('active')" style="background:none;border:none;color:var(--text-light);cursor:pointer;font-size:1.2rem;padding:4px;">×</button>
</div>
</div>
<div style="overflow-y:auto; flex:1; padding:0.75rem 0;">
<?php if(empty($notif_list)): ?>
<div style="text-align:center; padding:2.5rem 1rem; color:var(--text-light);">
<i class="fa fa-bell-slash" style="font-size:2rem; display:block; margin-bottom:0.75rem;"></i>
No notifications yet.
</div>
<?php else: foreach($notif_list as $n):
$t = strtotime($n['created_at']);
$diff = time()-$t;
$ago = $diff<60?'just now':($diff<3600?floor($diff/60).'m ago':($diff<86400?floor($diff/3600).'h ago':floor($diff/86400).'d ago'));
?>
<div style="display:flex; align-items:flex-start; gap:0.75rem; padding:0.65rem 1.5rem; border-bottom:1px solid var(--border); transition:background 0.15s; <?= !$n['is_read']?'background:rgba(var(--primary-rgb),0.04);':'' ?>">
<div style="width:8px; height:8px; border-radius:50%; background:<?= !$n['is_read']?'var(--primary)':'transparent' ?>; margin-top:6px; flex-shrink:0;"></div>
<div style="flex:1; min-width:0;">
<div style="font-size:0.875rem; color:var(--text); <?= !$n['is_read']?'font-weight:500;':'' ?>"><?= htmlspecialchars($n['message']) ?></div>
<div style="font-size:0.72rem; color:var(--text-light); margin-top:3px;"><?= $ago ?></div>
</div>
</div>
<?php endforeach; endif; ?>
</div>
</div>
</div>
<div class="app-container">
<!-- Sidebar -->
<aside class="sidebar" id="sidebar">
<!-- Toggle button on the edge -->
<button class="sidebar-toggle-btn" id="sidebar-toggle-btn" onclick="toggleSidebar()" title="Collapse / Expand">
<i class="fa fa-chevron-left" id="sidebar-toggle-icon"></i>
</button>
<h2 class="sidebar-brand">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>
<span class="sidebar-label sidebar-brand-text">TaskManager</span>
</h2>
<nav style="display:flex; flex-direction:column; gap:0.25rem;">
<a href="?action=dashboard" class="nav-link <?= $action=='dashboard'?'active':'' ?>" title="Dashboard">
<i class="fa fa-gauge-high nav-icon"></i>
<span class="sidebar-label">Dashboard</span>
</a>
<a href="?action=tasks" class="nav-link <?= $action=='tasks'?'active':'' ?>" title="Tasks">
<i class="fa fa-list-check nav-icon"></i>
<span class="sidebar-label">Tasks</span>
</a>
<a href="?action=notes" class="nav-link <?= $action=='notes'?'active':'' ?>" title="Notes">
<i class="fa fa-note-sticky nav-icon"></i>
<span class="sidebar-label">Notes</span>
</a>
<a href="?action=passwords" class="nav-link <?= $action=='passwords'?'active':'' ?>" title="Passwords">
<i class="fa fa-lock nav-icon"></i>
<span class="sidebar-label">Passwords</span>
</a>
<a href="?action=projects" class="nav-link <?= $action=='projects'?'active':'' ?>" title="Files">
<i class="fa fa-folder-open nav-icon"></i>
<span class="sidebar-label">Files</span>
</a>
<a href="?action=tools" class="nav-link <?= $action=='tools'?'active':'' ?>" title="Tools">
<i class="fa fa-toolbox nav-icon"></i>
<span class="sidebar-label">Tools</span>
</a>
<?php if(!empty($_SESSION['is_admin'])): ?>
<a href="?action=admin" class="nav-link <?= $action=='admin'?'active':'' ?>"> Admin Panel</a>
<a href="?action=admin" class="nav-link <?= $action=='admin'?'active':'' ?>" title="Admin Panel">
<i class="fa fa-shield-halved nav-icon"></i>
<span class="sidebar-label">Admin Panel</span>
</a>
<?php endif; ?>
</nav>
<div style="margin-top:auto; padding-top:1rem; border-top:1px solid var(--border);">
<div style="margin-bottom:0.5rem; font-weight:600;"><?= htmlspecialchars($current_user['username']) ?></div>
<a href="?action=logout" class="nav-link" style="padding:0; color:var(--text-light);">Logout</a>
</div>
</aside>
<main class="main-content">
<div style="display:flex; justify-content:flex-end; margin-bottom:1rem;">
<button id="theme-toggle" class="btn btn-secondary" style="border-radius:50%; padding:0.5rem; width:40px; height:40px; display:flex; align-items:center; justify-content:center;">
<span id="theme-icon-light" style="display:none;"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg></span>
<span id="theme-icon-dark" style="display:none;"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg></span>
<!-- Top Bar -->
<div style="display:flex; justify-content:flex-end; align-items:center; gap:0.75rem; margin-bottom:1.5rem;">
<!-- Dark Mode Toggle -->
<button id="theme-toggle" class="btn btn-secondary" title="Toggle dark mode" style="border-radius:50%; padding:0; width:38px; height:38px; display:flex; align-items:center; justify-content:center; flex-shrink:0;">
<span id="theme-icon-light" style="display:none;"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg></span>
<span id="theme-icon-dark" style="display:none;"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg></span>
</button>
<!-- User Avatar Dropdown -->
<div class="user-dropdown-wrap" id="user-dropdown-wrap">
<!-- Avatar with notification badge -->
<div style="position:relative; display:inline-flex;">
<button class="user-avatar-btn" id="user-avatar-btn" onclick="toggleUserDropdown()" title="<?= htmlspecialchars($current_user['username']) ?>">
<?php
try { $pdo->exec("ALTER TABLE users ADD COLUMN profile_pic TEXT DEFAULT NULL"); } catch(Exception $e) {}
$pic_top = $current_user['profile_pic'] ?? null;
?>
<?php if($pic_top && file_exists($pic_top)): ?>
<img src="<?= htmlspecialchars($pic_top) ?>?v=<?= time() ?>" alt="avatar" style="width:100%; height:100%; object-fit:cover; border-radius:50%;">
<?php else: ?>
<?= strtoupper(mb_substr($current_user['username'],0,1)) ?>
<?php endif; ?>
</button>
<?php if($unread_notifications > 0): ?>
<span class="avatar-notif-badge" onclick="openNotifications()"><?= $unread_notifications > 9 ? '9+' : $unread_notifications ?></span>
<?php endif; ?>
</div>
<div class="user-dropdown-menu" id="user-dropdown-menu">
<div class="user-dropdown-header">
<div class="user-dropdown-name"><?= htmlspecialchars($current_user['username']) ?></div>
<?php if(!empty($_SESSION['is_admin'])): ?>
<div class="user-dropdown-role">Administrator</div>
<?php else: ?>
<div class="user-dropdown-role">Member</div>
<?php endif; ?>
</div>
<div class="user-dropdown-divider"></div>
<button class="user-dropdown-item" onclick="openNotifications()">
<i class="fa fa-bell"></i>
Notifications
<?php if($unread_notifications > 0): ?>
<span class="badge" style="margin-left:auto; font-size:0.65rem;"><?= $unread_notifications ?></span>
<?php endif; ?>
</button>
<div class="user-dropdown-divider"></div>
<button class="user-dropdown-item" onclick="document.getElementById('profile-pic-modal').classList.add('active'); closeUserDropdown();">
<i class="fa fa-image"></i> Set Profile Picture
</button>
<button class="user-dropdown-item" onclick="document.getElementById('change-pw-modal').classList.add('active'); closeUserDropdown();">
<i class="fa fa-key"></i> Change Password
</button>
<div class="user-dropdown-divider"></div>
<a href="?action=logout" class="user-dropdown-item user-dropdown-logout" onclick="appConfirmUrl(event, this.href, 'Logout?')">
<i class="fa fa-right-from-bracket"></i> Logout
</a>
</div>
</div>
</div>
<?php if (isset($pw_msg) && $pw_msg): ?>
<script>document.addEventListener('DOMContentLoaded',()=>{ document.getElementById('change-pw-modal').classList.add('active'); });</script>
<?php endif; ?>

View File

@@ -10,7 +10,7 @@
<body>
<div class="login-container">
<div class="login-card">
<h1>Welcome Back</h1>
<h1>Login</h1>
<?php if($error): ?><div class="alert"><?= htmlspecialchars($error) ?></div><?php endif; ?>
<form method="POST">
<div class="form-group">
@@ -23,7 +23,9 @@
</div>
<button type="submit" class="btn" style="width:100%;">Sign In</button>
</form>
<!--
<p style="text-align:center; margin-top:1rem; font-size:0.875rem; color:var(--text-light);">First time? Run <a href="?action=setup">setup</a> to install Database.</p>
-->
</div>
</div>
</body>

View File

@@ -1,35 +1,139 @@
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_note'])) {
$stmt = $pdo->prepare("INSERT INTO notes (title, content, owner_id) VALUES (?, ?, ?)");
$stmt->execute([$_POST['title'], $_POST['content'], $user_id]);
// ── DB migrations ─────────────────────────────────────────────────────────────
try { $pdo->exec("ALTER TABLE notes ADD COLUMN color TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE notes ADD COLUMN image_path TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE notes ADD COLUMN updated_at DATETIME DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE notes ADD COLUMN label_name TEXT DEFAULT NULL"); } catch(Exception $e) {}
try {
$pdo->exec("CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
content TEXT,
owner_id INTEGER,
color TEXT DEFAULT NULL,
image_path TEXT DEFAULT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT NULL,
FOREIGN KEY (owner_id) REFERENCES users(id) ON DELETE CASCADE
)");
} catch(Exception $e) {}
try {
$pdo->exec("CREATE TABLE IF NOT EXISTS note_shares (
id INTEGER PRIMARY KEY AUTOINCREMENT,
note_id INTEGER,
share_type TEXT,
share_id INTEGER,
FOREIGN KEY (note_id) REFERENCES notes(id) ON DELETE CASCADE
)");
} catch(Exception $e) {}
// ── Handle POST ───────────────────────────────────────────────────────────────
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_POST['create_note'])) {
$image_path = null;
if(isset($_FILES['note_image']) && $_FILES['note_image']['error'] === 0) {
$allowed = ['image/jpeg','image/png','image/gif','image/webp'];
if(in_array($_FILES['note_image']['type'], $allowed)) {
$ext = pathinfo($_FILES['note_image']['name'], PATHINFO_EXTENSION);
$fname = 'note_' . $user_id . '_' . time() . '.' . $ext;
$dest = 'uploads/' . $fname;
if(move_uploaded_file($_FILES['note_image']['tmp_name'], $dest)) $image_path = $dest;
}
}
$stmt = $pdo->prepare("INSERT INTO notes (title, content, owner_id, color, image_path, label_name) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->execute([$_POST['title'] ?? 'Untitled', $_POST['content'], $user_id, $_POST['color'] ?? null, $image_path, trim($_POST['label_name'] ?? '') ?: null]);
// Note creation only notifies owner in UI, but we can trigger a WAHA self-alert if they have it enabled
notify_user($user_id, "You created a new note: " . ($_POST['title'] ?? 'Untitled'), ['action'=>'Created', 'module'=>'Note', 'item'=>$_POST['title']??'Untitled']);
}
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['share_note'])) {
$n_id = $_POST['note_id'];
$share = $_POST['share_target']; // 'user_1'
$parts = explode('_', $share);
if(isset($_POST['update_note'])) {
$n = query("SELECT owner_id, image_path FROM notes WHERE id=?", [$_POST['note_id']])->fetch();
if($n && $n['owner_id'] == $user_id) {
$image_path = $n['image_path'];
if(isset($_FILES['note_image']) && $_FILES['note_image']['error'] === 0) {
$allowed = ['image/jpeg','image/png','image/gif','image/webp'];
if(in_array($_FILES['note_image']['type'], $allowed)) {
$ext = pathinfo($_FILES['note_image']['name'], PATHINFO_EXTENSION);
$fname = 'note_' . $user_id . '_' . time() . '.' . $ext;
$dest = 'uploads/' . $fname;
if(move_uploaded_file($_FILES['note_image']['tmp_name'], $dest)) {
if($image_path && file_exists($image_path)) @unlink($image_path);
$image_path = $dest;
}
}
}
if(isset($_POST['remove_image']) && $_POST['remove_image']) {
if($image_path && file_exists($image_path)) @unlink($image_path);
$image_path = null;
}
$stmt = $pdo->prepare("UPDATE notes SET title=?, content=?, color=?, image_path=?, label_name=?, updated_at=CURRENT_TIMESTAMP WHERE id=? AND owner_id=?");
$stmt->execute([$_POST['title'] ?? 'Untitled', $_POST['content'], $_POST['color'] ?? null, $image_path, trim($_POST['label_name'] ?? '') ?: null, $_POST['note_id'], $user_id]);
$ctx = ['action'=>'Updated', 'module'=>'Note', 'item'=>$_POST['title']??'Untitled'];
// Notify owner
notify_user($user_id, "Note '{$_POST['title']}' updated.", $ctx);
// Notify anyone this note is shared with
$shares = query("SELECT share_type, share_id FROM note_shares WHERE note_id=?", [$_POST['note_id']])->fetchAll();
foreach($shares as $sh) {
if($sh['share_type'] === 'user') notify_user($sh['share_id'], "Shared note '{$_POST['title']}' updated.", $ctx);
else notify_group($sh['share_id'], "Shared group note '{$_POST['title']}' updated.", $ctx);
}
}
}
if(isset($_POST['delete_note'])) {
$n = query("SELECT owner_id, image_path, title FROM notes WHERE id=?", [$_POST['note_id']])->fetch();
if($n && $n['owner_id'] == $user_id) {
if($n['image_path'] && file_exists($n['image_path'])) @unlink($n['image_path']);
$ctx = ['action'=>'Deleted', 'module'=>'Note', 'item'=>$n['title']??'Untitled'];
// Notify anyone it was shared with before deleting
$shares = query("SELECT share_type, share_id FROM note_shares WHERE note_id=?", [$_POST['note_id']])->fetchAll();
foreach($shares as $sh) {
if($sh['share_type'] === 'user') notify_user($sh['share_id'], "Shared note '{$n['title']}' has been deleted.", $ctx);
else notify_group($sh['share_id'], "Shared group note '{$n['title']}' has been deleted.", $ctx);
}
query("DELETE FROM notes WHERE id=? AND owner_id=?", [$_POST['note_id'], $user_id]);
notify_user($user_id, "Note '{$n['title']}' has been deleted.", $ctx);
}
}
if(isset($_POST['share_note'])) {
$n_id = $_POST['note_id'];
$share = $_POST['share_target'];
$parts = explode('_', $share, 2);
if(count($parts)===2) {
$stmt = $pdo->prepare("INSERT INTO note_shares (note_id, share_type, share_id) VALUES (?, ?, ?)");
$stmt->execute([$n_id, $parts[0], $parts[1]]);
$n = query("SELECT title FROM notes WHERE id=?", [$n_id])->fetch();
$msg = "A note '{$n['title']}' has been shared with you.";
if($parts[0] === 'user') notify_user($parts[1], $msg);
else notify_group($parts[1], $msg);
$ctx = ['action'=>'Shared', 'module'=>'Note', 'item'=>$n['title']??'Untitled', 'user'=>$_SESSION['username']??'System'];
if($parts[0] === 'user') notify_user($parts[1], $msg, $ctx);
else notify_group($parts[1], $msg, $ctx);
}
}
// Fetch Notes
if(isset($_POST['remove_note_share'])) {
$share_id = (int)$_POST['share_id'];
$chk = query("SELECT ns.id FROM note_shares ns JOIN notes n ON ns.note_id=n.id WHERE ns.id=? AND n.owner_id=?", [$share_id, $user_id])->fetch();
if($chk) {
$pdo->prepare("DELETE FROM note_shares WHERE id=?")->execute([$share_id]);
}
}
}
// ── Fetch Notes ───────────────────────────────────────────────────────────────
$user_groups = get_user_groups($user_id);
$my_group_ids = array_column($user_groups, 'id');
$group_in = implode(',', array_fill(0, count($my_group_ids), '?')) ?: '0';
$sql = "SELECT n.*, (n.owner_id = ?) as is_mine FROM notes n
$sql = "SELECT n.*, (n.owner_id = ?) as is_mine, u.username as owner_name FROM notes n
LEFT JOIN note_shares ns ON n.id = ns.note_id
LEFT JOIN users u ON n.owner_id = u.id
WHERE n.owner_id = ?
OR (ns.share_type='user' AND ns.share_id = ?)
OR (ns.share_type='group' AND ns.share_id IN ($group_in))
GROUP BY n.id ORDER BY n.created_at DESC";
GROUP BY n.id ORDER BY n.updated_at DESC, n.created_at DESC";
$params = array_merge([$user_id, $user_id, $user_id], $my_group_ids);
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
@@ -37,47 +141,575 @@ $notes = $stmt->fetchAll();
$all_users = query("SELECT id, username FROM users WHERE id != ?", [$user_id])->fetchAll();
$all_groups = query("SELECT * FROM groups")->fetchAll();
$label_names = [];
foreach($notes as $n) {
$lbls = explode(',', (string)($n['label_name'] ?? ''));
foreach($lbls as $lbl) {
$lbl = trim($lbl);
if($lbl !== '') $label_names[strtolower($lbl)] = $lbl;
}
}
natcasesort($label_names);
// Define note colors — Google Keep inspired
$note_colors = [
'' => ['bg'=>'var(--surface)', 'label'=>'Default', 'hex'=>'#ffffff'],
'#fff9c4' => ['bg'=>'#fff9c4', 'label'=>'Yellow', 'hex'=>'#fff9c4'],
'#ccff90' => ['bg'=>'#ccff90', 'label'=>'Lime', 'hex'=>'#ccff90'],
'#d4edda' => ['bg'=>'#d4edda', 'label'=>'Sage', 'hex'=>'#d4edda'],
'#80cbc4' => ['bg'=>'#80cbc4', 'label'=>'Teal', 'hex'=>'#80cbc4'],
'#b3e5fc' => ['bg'=>'#b3e5fc', 'label'=>'Sky', 'hex'=>'#b3e5fc'],
'#cce5ff' => ['bg'=>'#cce5ff', 'label'=>'Blue', 'hex'=>'#cce5ff'],
'#e2d9f3' => ['bg'=>'#e2d9f3', 'label'=>'Lavender', 'hex'=>'#e2d9f3'],
'#f3e5f5' => ['bg'=>'#f3e5f5', 'label'=>'Orchid', 'hex'=>'#f3e5f5'],
'#f8d7da' => ['bg'=>'#f8d7da', 'label'=>'Rose', 'hex'=>'#f8d7da'],
'#ef9a9a' => ['bg'=>'#ef9a9a', 'label'=>'Red', 'hex'=>'#ef9a9a'],
'#ffcc80' => ['bg'=>'#ffcc80', 'label'=>'Peach', 'hex'=>'#ffcc80'],
'#fde8d8' => ['bg'=>'#fde8d8', 'label'=>'Orange', 'hex'=>'#fde8d8'],
'#d7ccc8' => ['bg'=>'#d7ccc8', 'label'=>'Sand', 'hex'=>'#d7ccc8'],
'#f5f5f5' => ['bg'=>'#f5f5f5', 'label'=>'Stone', 'hex'=>'#f5f5f5'],
'#e8f5e9' => ['bg'=>'#e8f5e9', 'label'=>'Mint', 'hex'=>'#e8f5e9'],
'#fff3e0' => ['bg'=>'#fff3e0', 'label'=>'Apricot', 'hex'=>'#fff3e0'],
'#fce4ec' => ['bg'=>'#fce4ec', 'label'=>'Pink', 'hex'=>'#fce4ec'],
'#ede7f6' => ['bg'=>'#ede7f6', 'label'=>'Violet', 'hex'=>'#ede7f6'],
'#e0f7fa' => ['bg'=>'#e0f7fa', 'label'=>'Cyan', 'hex'=>'#e0f7fa'],
'#fffde7' => ['bg'=>'#fffde7', 'label'=>'Butter', 'hex'=>'#fffde7'],
];
?>
<div class="header">
<h1>Markdown Notes</h1>
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem; gap:0.75rem; flex-wrap:wrap;">
<button class="btn" onclick="document.getElementById('new-note-modal').classList.add('active')">
<i class="fa fa-plus"></i> New Note
</button>
<div style="display:flex; align-items:center; gap:0.5rem; flex-wrap:wrap;">
<input type="text" id="notes-search-input" class="form-control" placeholder="Search notes..." style="width:200px; padding:0.45rem 0.6rem; font-size:0.84rem;" oninput="filterNotes()">
<select id="notes-label-filter" class="form-control" style="width:180px; padding:0.45rem 0.6rem; font-size:0.84rem;" onchange="filterNotes()">
<option value="">All labels</option>
<?php foreach($label_names as $lbl): ?>
<option value="<?= htmlspecialchars(strtolower($lbl)) ?>"><?= htmlspecialchars($lbl) ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<!-- ── New Note Modal ─────────────────────────────────────────────────────── -->
<div class="modal-overlay" id="new-note-modal">
<div class="modal-content note-modal-compact" style="max-width:760px; max-height:92vh; overflow-y:auto;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem;">
<h3 style="font-size:1rem; font-weight:700;">New Note</h3>
<button type="button" style="background:none;border:none;color:var(--text-light);cursor:pointer;font-size:1.2rem;" onclick="document.getElementById('new-note-modal').classList.remove('active')">×</button>
</div>
<form method="POST" enctype="multipart/form-data" id="new-note-form">
<input type="hidden" name="create_note" value="1">
<div class="note-modal-top-fields" style="display:grid; grid-template-columns:2fr 1fr; gap:0.75rem;">
<div class="form-group">
<input type="text" name="title" class="form-control" placeholder="Title..." id="new-note-title" style="font-weight:600; font-size:1rem;">
</div>
<div class="form-group">
<label style="font-size:0.8rem; color:var(--text-light); margin-bottom:0.25rem; display:block;">Tags</label>
<input type="text" name="label_name" class="form-control tagify-input" id="new-note-label" placeholder="Add tags...">
</div>
</div>
<!-- WYSIWYG Toolbar -->
<div class="note-editor-toolbar" id="new-note-toolbar">
<button type="button" class="note-toolbar-btn" onclick="formatNote('new-note-content','bold')" title="Bold"><b>B</b></button>
<button type="button" class="note-toolbar-btn" onclick="formatNote('new-note-content','italic')" title="Italic"><i>I</i></button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('new-note-content','# ')" title="H1">H1</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('new-note-content','## ')" title="H2">H2</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('new-note-content','### ')" title="H3">H3</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('new-note-content','- ')" title="Bullet">• List</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('new-note-content','1. ')" title="Numbered">1. List</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('new-note-content','- [ ] ')" title="Todo">☑ Todo</button>
<button type="button" class="note-toolbar-btn" onclick="wrapMarkdown('new-note-content','`','`')" title="Code"><code>Code</code></button>
<button type="button" class="note-toolbar-btn" onclick="wrapMarkdown('new-note-content','```\n','\n```')" title="Code Block">{ } Block</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('new-note-content','> ')" title="Quote">❝ Quote</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('new-note-content','---\n')" title="Divider">─ Line</button>
<button type="button" class="note-toolbar-btn" id="new-preview-btn" onclick="togglePreview('new-note-content','new-note-preview','new-preview-btn')">👁 Preview</button>
</div>
<div class="form-group">
<textarea name="content" id="new-note-content" class="note-content-area" placeholder="Write your note... (Markdown supported)" rows="8"></textarea>
<div id="new-note-preview" class="markdown-body" style="display:none; min-height:160px; border:1px solid var(--border); border-radius:0.5rem; padding:0.75rem; background:var(--bg); font-size:0.9rem;"></div>
</div>
<!-- Color picker -->
<div class="form-group">
<label style="font-size:0.8rem; color:var(--text-light);">Note Color</label>
<div class="note-color-palette" id="new-note-colors">
<?php foreach($note_colors as $hex => $info): ?>
<div class="color-swatch <?= !$hex ? 'selected' : '' ?>"
style="background:<?= $hex ?: '#fff' ?>; border:2px solid var(--border);"
onclick="selectColor(this,'new-note-color-input','<?= $hex ?>')"
title="<?= $info['label'] ?>"></div>
<?php endforeach; ?>
</div>
<input type="hidden" name="color" id="new-note-color-input" value="">
</div>
<!-- Image upload -->
<div class="form-group">
<label style="font-size:0.8rem; color:var(--text-light);">Attach Image (optional)</label>
<input type="file" name="note_image" accept="image/*" class="form-control">
</div>
<div style="display:flex; gap:0.5rem; justify-content:flex-end; margin-top:1rem;">
<button type="button" class="btn btn-secondary" onclick="document.getElementById('new-note-modal').classList.remove('active')">Cancel</button>
<button type="submit" class="btn"><i class="fa fa-save"></i> Save Note</button>
</div>
</form>
</div>
</div>
<!-- ── View Note Modal ────────────────────────────────────────────────────── -->
<div class="modal-overlay" id="view-note-modal">
<div class="modal-content note-modal-compact" style="max-width:760px; max-height:92vh; overflow-y:auto; padding:0; background:var(--bg);">
<div id="view-note-header" style="padding:1.5rem; border-bottom:1px solid var(--border); background:var(--surface); position:sticky; top:0; z-index:10;">
<div style="display:flex; justify-content:space-between; align-items:flex-start; gap:1rem;">
<div style="flex:1; min-width:0;">
<h2 id="view-note-title" style="margin:0 0 0.5rem 0; font-size:1.4rem; font-weight:800; line-height:1.3; color:var(--text); word-wrap:break-word;"></h2>
<div style="display:flex; align-items:center; gap:0.5rem; flex-wrap:wrap;">
<span id="view-note-label-container" style="display:none; align-items:center; gap:0.35rem; padding:3px 8px; border-radius:999px; background:rgba(var(--primary-rgb),0.12); color:var(--primary); font-size:0.75rem; font-weight:600;">
<i class="fa fa-tag" style="font-size:0.7rem;"></i> <span id="view-note-label"></span>
</span>
<span id="view-note-date" style="font-size:0.8rem; color:var(--text-light);"></span>
<span id="view-note-shared-badge" class="note-card-shared-badge" style="display:none;">Shared</span>
</div>
</div>
<div style="display:flex; align-items:center; gap:0.5rem; flex-shrink:0;">
<button class="btn btn-sm btn-secondary" id="view-note-edit-btn" onclick="transToEditNote()"><i class="fa fa-pencil"></i> Edit</button>
<button type="button" style="background:none;border:none;color:var(--text-light);cursor:pointer;font-size:1.6rem; line-height:1; padding:0 4px;" onclick="document.getElementById('view-note-modal').classList.remove('active')">×</button>
</div>
</div>
<div id="view-note-image-container" style="display:none; margin-top:1.25rem; border-radius:0.75rem; overflow:hidden; border:1px solid var(--border);">
<img id="view-note-image" src="" style="width:100%; max-height:450px; object-fit:cover; display:block;">
</div>
</div>
<div style="padding:1.5rem;">
<div id="view-note-content" class="markdown-body" style="font-size:1rem; line-height:1.7; color:var(--text);"></div>
</div>
</div>
</div>
<!-- ── Edit Note Modal ────────────────────────────────────────────────────── -->
<div class="modal-overlay" id="edit-note-modal">
<div class="modal-content note-modal-compact" style="max-width:760px; max-height:90vh; overflow-y:auto;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:1rem;">
<h3 style="margin:0;">Edit Note</h3>
<button type="button" style="background:none;border:none;color:var(--text-light);cursor:pointer;font-size:1.2rem;" onclick="document.getElementById('edit-note-modal').classList.remove('active')">×</button>
</div>
<form method="POST" enctype="multipart/form-data" id="edit-note-form">
<input type="hidden" name="update_note" value="1">
<input type="hidden" name="note_id" id="edit-note-id">
<div class="note-modal-top-fields" style="display:grid; grid-template-columns:2fr 1fr; gap:0.75rem;">
<div class="form-group">
<input type="text" name="title" id="edit-note-title" class="form-control" placeholder="Title..." style="font-weight:600; font-size:1rem;">
</div>
<div class="form-group">
<label style="font-size:0.8rem; color:var(--text-light); margin-bottom:0.25rem; display:block;">Tags</label>
<input type="text" name="label_name" id="edit-note-label" class="form-control tagify-input" placeholder="Add tags...">
</div>
</div>
<div class="note-editor-toolbar">
<button type="button" class="note-toolbar-btn" onclick="formatNote('edit-note-content','bold')"><b>B</b></button>
<button type="button" class="note-toolbar-btn" onclick="formatNote('edit-note-content','italic')"><i>I</i></button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('edit-note-content','# ')">H1</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('edit-note-content','## ')">H2</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('edit-note-content','### ')">H3</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('edit-note-content','- ')">• List</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('edit-note-content','1. ')">1. List</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('edit-note-content','- [ ] ')">☑ Todo</button>
<button type="button" class="note-toolbar-btn" onclick="wrapMarkdown('edit-note-content','`','`')"><code>Code</code></button>
<button type="button" class="note-toolbar-btn" onclick="wrapMarkdown('edit-note-content','```\n','\n```')">{ } Block</button>
<button type="button" class="note-toolbar-btn" onclick="insertMarkdown('edit-note-content','> ')">❝ Quote</button>
<button type="button" class="note-toolbar-btn" id="edit-preview-btn" onclick="togglePreview('edit-note-content','edit-note-preview','edit-preview-btn')">👁 Preview</button>
</div>
<div class="form-group">
<textarea name="content" id="edit-note-content" class="note-content-area" rows="8"></textarea>
<div id="edit-note-preview" class="markdown-body" style="display:none; min-height:160px; border:1px solid var(--border); border-radius:0.5rem; padding:0.75rem; background:var(--bg); font-size:0.9rem;"></div>
</div>
<div class="form-group">
<label style="font-size:0.8rem; color:var(--text-light);">Note Color</label>
<div class="note-color-palette" id="edit-note-colors">
<?php foreach($note_colors as $hex => $info): ?>
<div class="color-swatch"
style="background:<?= $hex ?: '#fff' ?>; border:2px solid var(--border);"
onclick="selectColor(this,'edit-note-color-input','<?= $hex ?>')"
title="<?= $info['label'] ?>"></div>
<?php endforeach; ?>
</div>
<input type="hidden" name="color" id="edit-note-color-input" value="">
</div>
<div id="edit-current-image" style="display:none; margin-bottom:0.75rem;">
<label style="font-size:0.8rem; color:var(--text-light);">Current Image:</label>
<div style="display:flex; align-items:center; gap:0.5rem; margin-top:0.25rem;">
<img id="edit-current-img-preview" src="" alt="Current" style="height:60px; border-radius:0.5rem; object-fit:cover;">
<label style="display:flex; align-items:center; gap:0.25rem; font-size:0.8rem; cursor:pointer;">
<input type="checkbox" name="remove_image" value="1"> Remove image
</label>
</div>
</div>
<div class="form-group">
<label style="font-size:0.8rem; color:var(--text-light);">Replace Image (optional)</label>
<input type="file" name="note_image" accept="image/*" class="form-control">
</div>
<!-- Share section (only for owner) -->
<div id="edit-share-section" style="border-top:1px solid var(--border); padding-top:0.75rem; margin-top:0.5rem;">
<label style="font-size:0.8rem; color:var(--text-light); margin-bottom:0.4rem; display:block;">Shared with</label>
<div id="note-shares-list" style="display:flex; flex-wrap:wrap; gap:0.35rem; margin-bottom:0.75rem;"></div>
<div style="display:flex; gap:0.5rem; flex-wrap:wrap;">
<select name="share_target" id="edit-share-target" class="form-control" style="flex:1; min-width:150px; padding:0.4rem;">
<?php foreach($all_users as $u): ?>
<option value="user_<?= $u['id'] ?>">👤 <?= htmlspecialchars($u['username']) ?></option>
<?php endforeach; ?>
<?php foreach($all_groups as $g): ?>
<option value="group_<?= $g['id'] ?>">👥 <?= htmlspecialchars($g['name']) ?></option>
<?php endforeach; ?>
</select>
<button type="submit" name="share_note" value="1" class="btn btn-sm" onclick="this.form.action=''; document.querySelector('[name=update_note]').disabled=true; this.form.onsubmit=null;" formaction="">
<i class="fa fa-share-nodes"></i> Share
</button>
</div>
</div>
<div style="display:flex; gap:0.5rem; justify-content:space-between; margin-top:1rem; flex-wrap:wrap;">
<button type="button" class="btn btn-danger btn-sm" onclick="deleteNote(document.getElementById('edit-note-id').value)"><i class="fa fa-trash"></i> Delete</button>
<div style="display:flex; gap:0.5rem;">
<button type="button" class="btn btn-secondary" onclick="document.getElementById('edit-note-modal').classList.remove('active')">Cancel</button>
<button type="submit" class="btn"><i class="fa fa-save"></i> Save Changes</button>
</div>
</div>
</form>
</div>
</div>
<!-- Delete Note Form -->
<form method="POST" id="delete-note-form" style="display:none;">
<input type="hidden" name="delete_note" value="1">
<input type="hidden" name="note_id" id="delete-note-id">
</form>
<!-- Share Note Form (separate POST for share_note) -->
<form method="POST" id="share-note-standalone-form" style="display:none;">
<input type="hidden" name="share_note" value="1">
<input type="hidden" name="note_id" id="share-note-standalone-id">
<input type="hidden" name="share_target" id="share-note-standalone-target">
</form>
<form method="POST" id="remove-note-share-form" style="display:none;">
<input type="hidden" name="remove_note_share" value="1">
<input type="hidden" name="share_id" id="remove-note-share-id">
</form>
<!-- Markdown Libs -->
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<div style="display:grid; grid-template-columns: 1fr 2fr; gap:1.5rem;">
<div class="card">
<h3>Create Note</h3>
<form method="POST" style="margin-top:1rem;">
<div class="form-group"><input type="text" name="title" class="form-control" placeholder="Note Title" required></div>
<div class="form-group">
<textarea name="content" class="form-control" placeholder="Markdown supported..." style="min-height:200px;" required></textarea>
<!-- ── Notes Grid ─────────────────────────────────────────────────────────── -->
<?php if(empty($notes)): ?>
<div style="text-align:center; padding:4rem 2rem; color:var(--text-light);">
<div style="font-size:3rem; margin-bottom:1rem;">📝</div>
<h3 style="margin-bottom:0.5rem;">No notes yet</h3>
<p>Click <strong>New Note</strong> to start writing something.</p>
</div>
<button type="submit" name="create_note" class="btn">Save Note</button>
</form>
<?php else: ?>
<div class="notes-grid">
<?php foreach($notes as $n):
$bg = $n['color'] ?: 'var(--surface)';
$preview = strip_tags(isset($n['content']) ? (function_exists('marked') ? $n['content'] : $n['content']) : '');
$preview = mb_substr($preview, 0, 120) . (mb_strlen($preview) > 120 ? '...' : '');
$note_shares = [];
if($n['is_mine']) {
$note_shares = query("SELECT ns.id, ns.share_type, ns.share_id, u.username, u.profile_pic as upic, g.name as gname, g.profile_pic as gpic FROM note_shares ns LEFT JOIN users u ON (ns.share_type='user' AND ns.share_id=u.id) LEFT JOIN groups g ON (ns.share_type='group' AND ns.share_id=g.id) WHERE ns.note_id=?", [$n['id']])->fetchAll();
}
$shares_json = htmlspecialchars(json_encode($note_shares), ENT_QUOTES, 'UTF-8');
?>
<div class="note-card note-filter-item"
style="background:<?= htmlspecialchars($bg) ?>;"
data-id="<?= $n['id'] ?>"
data-title="<?= htmlspecialchars(addslashes((string)$n['title'])) ?>"
data-content="<?= htmlspecialchars(addslashes((string)$n['content'])) ?>"
data-label="<?= htmlspecialchars(strtolower(trim((string)($n['label_name'] ?? '')))) ?>"
data-label-raw="<?= htmlspecialchars(trim((string)($n['label_name'] ?? ''))) ?>"
data-color="<?= htmlspecialchars((string)$n['color']) ?>"
data-image="<?= htmlspecialchars((string)($n['image_path'] ?? '')) ?>"
data-shares="<?= $shares_json ?>"
data-mine="<?= $n['is_mine'] ?>"
data-updated="<?= date('M j, Y, H:i', strtotime($n['updated_at'] ?: $n['created_at'])) ?>"
onclick="viewNote(this)">
<?php if($n['image_path'] && file_exists($n['image_path'])): ?>
<img src="<?= htmlspecialchars($n['image_path']) ?>" alt="Note image" class="note-card-img">
<?php endif; ?>
<?php if($n['title']): ?>
<div class="note-card-title"><?= htmlspecialchars($n['title']) ?></div>
<?php endif; ?>
<?php if(!empty($n['label_name'])): ?>
<div style="display:flex; flex-wrap:wrap; gap:0.35rem; margin-bottom:0.5rem;">
<?php foreach(explode(',', $n['label_name']) as $lbl): $lbl=trim($lbl); if(!$lbl) continue; ?>
<div style="display:inline-flex; align-items:center; gap:0.35rem; padding:3px 8px; border-radius:999px; background:rgba(var(--primary-rgb),0.12); color:var(--primary); font-size:0.7rem; font-weight:600;">
<i class="fa fa-tag" style="font-size:0.65rem;"></i> <?= htmlspecialchars($lbl) ?>
</div>
<div class="card">
<h3>My Notes</h3>
<?php foreach($notes as $n): ?>
<div style="border:1px solid var(--border); border-radius:1rem; padding:1.5rem; margin-bottom:1.5rem;">
<div style="display:flex; justify-content:space-between; margin-bottom:1rem;">
<h4 style="font-size:1.2rem; color:var(--primary);"><?= htmlspecialchars($n['title']) ?> <?= !$n['is_mine'] ? '<span class="badge" style="background:#10B981; font-size:10px;">Shared</span>' : '' ?></h4>
<?php if($n['is_mine']): ?>
<form method="POST" style="display:inline; display:flex; gap:0.5rem;">
<input type="hidden" name="note_id" value="<?= $n['id'] ?>">
<select name="share_target" class="form-control" style="width:auto; padding:0.25rem;">
<?php foreach($all_users as $u): ?><option value="user_<?= $u['id'] ?>">User: <?= htmlspecialchars($u['username']) ?></option><?php endforeach; ?>
<?php foreach($all_groups as $g): ?><option value="group_<?= $g['id'] ?>">Group: <?= htmlspecialchars($g['name']) ?></option><?php endforeach; ?>
</select>
<button type="submit" name="share_note" class="btn btn-sm">Share</button>
</form>
<?php endforeach; ?>
</div>
<?php endif; ?>
<div class="note-card-preview"><?= htmlspecialchars($preview) ?></div>
<div class="note-card-footer">
<div style="display:flex; align-items:center; gap:0.4rem;">
<?php if($n['color']): ?><div class="note-color-dot" style="background:<?= htmlspecialchars($n['color']) ?>;"></div><?php endif; ?>
<span style="font-size:0.7rem; color:var(--text-light);"><?= date('M j', strtotime($n['updated_at'] ?: $n['created_at'])) ?></span>
<?php if(!$n['is_mine']): ?>
<span class="note-card-shared-badge">Shared</span>
<?php endif; ?>
</div>
<div class="note-card-actions" onclick="event.stopPropagation()">
<?php if($n['is_mine']): ?>
<button class="btn btn-sm btn-danger" style="padding:3px 7px;" onclick="deleteNote(<?= $n['id'] ?>)" title="Delete"><i class="fa fa-trash"></i></button>
<?php endif; ?>
</div>
<div class="markdown-body" style="background:var(--bg); padding:1rem; border-radius:0.5rem; font-size:0.95rem;">
<script>document.write(marked.parse(`<?= str_replace(array('\\', '`', '$'), array('\\\\', '\\`', '\\$'), (string)$n['content']) ?>`));</script>
</div>
</div>
<?php endforeach; ?>
<?php if(!$notes): ?><p>No notes written yet.</p><?php endif; ?>
</div>
</div>
<?php endif; ?>
<script>
// ── WYSIWYG Markdown Tools ────────────────────────────────────────────────────
function formatNote(textareaId, cmd) {
const ta = document.getElementById(textareaId);
const start = ta.selectionStart, end = ta.selectionEnd;
const sel = ta.value.substring(start, end);
let wrap = cmd === 'bold' ? '**' : '_';
const replacement = `${wrap}${sel || 'text'}${wrap}`;
ta.value = ta.value.substring(0, start) + replacement + ta.value.substring(end);
ta.focus();
ta.selectionStart = start + wrap.length;
ta.selectionEnd = start + wrap.length + (sel || 'text').length;
}
function insertMarkdown(textareaId, prefix) {
const ta = document.getElementById(textareaId);
const start = ta.selectionStart;
// Go to start of line
const before = ta.value.substring(0, start);
const lineStart = before.lastIndexOf('\n') + 1;
ta.value = ta.value.substring(0, lineStart) + prefix + ta.value.substring(lineStart);
ta.focus();
const newPos = lineStart + prefix.length + (start - lineStart);
ta.selectionStart = ta.selectionEnd = newPos;
}
function wrapMarkdown(textareaId, before, after) {
const ta = document.getElementById(textareaId);
const start = ta.selectionStart, end = ta.selectionEnd;
const sel = ta.value.substring(start, end);
ta.value = ta.value.substring(0, start) + before + (sel || 'code') + after + ta.value.substring(end);
ta.focus();
}
function togglePreview(contentId, previewId, btnId) {
const content = document.getElementById(contentId);
const preview = document.getElementById(previewId);
const btn = document.getElementById(btnId);
if(preview.style.display === 'none') {
preview.innerHTML = marked.parse(content.value || '');
preview.style.display = 'block';
content.style.display = 'none';
btn.textContent = '✏️ Edit';
} else {
preview.style.display = 'none';
content.style.display = 'block';
btn.textContent = '👁 Preview';
}
}
function selectColor(el, inputId, color) {
el.closest('.note-color-palette').querySelectorAll('.color-swatch').forEach(s => s.classList.remove('selected'));
el.classList.add('selected');
document.getElementById(inputId).value = color;
}
function openNote(card) {
const id = card.dataset.id;
const title = card.dataset.title;
const content = card.dataset.content;
const color = card.dataset.color;
const label = card.dataset.labelRaw || '';
const image = card.dataset.image;
const isMine = card.dataset.mine === '1';
document.getElementById('edit-note-id').value = id;
document.getElementById('edit-note-title').value = title;
document.getElementById('edit-note-content').value = content;
document.getElementById('edit-note-label').value = label;
document.getElementById('edit-note-color-input').value = color;
document.getElementById('edit-note-preview').style.display = 'none';
document.getElementById('edit-note-content').style.display = 'block';
document.getElementById('edit-preview-btn').innerHTML = '👁 Preview';
// Color swatches
document.querySelectorAll('#edit-note-colors .color-swatch').forEach(s => {
s.classList.remove('selected');
const swatchColor = s.getAttribute('onclick').match(/'([^']*)'/g);
if(swatchColor && swatchColor[1] && swatchColor[1].replace(/'/g,'') === color) s.classList.add('selected');
if(!color && s.title === 'Default') s.classList.add('selected');
});
// Image preview
const imgBlock = document.getElementById('edit-current-image');
if(image) {
imgBlock.style.display = 'block';
document.getElementById('edit-current-img-preview').src = image;
} else {
imgBlock.style.display = 'none';
}
// Share section
document.getElementById('edit-share-section').style.display = isMine ? 'block' : 'none';
if(isMine) {
renderNoteShares(card.dataset.shares || '[]');
}
// Wire up share button
const shareBtn = document.querySelector('#edit-note-form button[name="share_note"]');
if(shareBtn) {
shareBtn.onclick = (e) => {
e.preventDefault();
const target = document.getElementById('edit-share-target').value;
document.getElementById('share-note-standalone-id').value = id;
document.getElementById('share-note-standalone-target').value = target;
document.getElementById('share-note-standalone-form').submit();
};
}
document.getElementById('edit-note-modal').classList.add('active');
}
let currentViewedCard = null;
function viewNote(card) {
currentViewedCard = card;
const title = card.dataset.title || 'Untitled Note';
const content = card.dataset.content || '';
const label = card.dataset.labelRaw || '';
const image = card.dataset.image;
const updatedAt = card.dataset.updated;
const isMine = card.dataset.mine === '1';
document.getElementById('view-note-title').textContent = title;
// Clear old tags
document.getElementById('view-note-label-container').innerHTML = '';
if(label) {
document.getElementById('view-note-label-container').style.display = 'flex';
const lbls = label.split(',');
lbls.forEach(l => {
const span = document.createElement('span');
span.style.cssText = 'display:inline-flex; align-items:center; gap:0.35rem; padding:3px 8px; border-radius:999px; background:rgba(var(--primary-rgb),0.12); color:var(--primary); font-size:0.75rem; font-weight:600;';
span.innerHTML = `<i class="fa fa-tag" style="font-size:0.7rem;"></i> ${l.trim()}`;
document.getElementById('view-note-label-container').appendChild(span);
});
} else {
document.getElementById('view-note-label-container').style.display = 'none';
}
document.getElementById('view-note-date').textContent = 'Updated ' + updatedAt;
document.getElementById('view-note-shared-badge').style.display = !isMine ? 'inline-block' : 'none';
if(image) {
document.getElementById('view-note-image-container').style.display = 'block';
document.getElementById('view-note-image').src = image;
} else {
document.getElementById('view-note-image-container').style.display = 'none';
}
document.getElementById('view-note-content').innerHTML = marked.parse(content);
document.getElementById('view-note-edit-btn').style.display = isMine ? 'inline-flex' : 'none';
document.getElementById('view-note-modal').classList.add('active');
}
function transToEditNote() {
if(currentViewedCard) {
document.getElementById('view-note-modal').classList.remove('active');
openNote(currentViewedCard);
}
}
function renderNoteShares(jsonShares) {
const list = document.getElementById('note-shares-list');
list.innerHTML = '';
let shares = [];
try { shares = JSON.parse(jsonShares || '[]'); } catch(e) { shares = []; }
if(shares.length === 0) return;
shares.forEach(sh => {
const pic = sh.share_type === 'user' ? sh.upic : sh.gpic;
const name = sh.share_type === 'user' ? (sh.username || 'User') : (sh.gname || 'Group');
const icon = sh.share_type === 'user' ? '👤' : '👥';
const chip = document.createElement('div');
chip.className = 'share-chip';
chip.style.display = 'inline-flex';
chip.style.alignItems = 'center';
chip.style.gap = '0.4rem';
chip.style.fontSize = '0.72rem';
chip.style.padding = '2px 8px 2px 2px';
chip.style.borderRadius = '999px';
chip.style.background = 'rgba(var(--primary-rgb),0.1)';
chip.style.color = 'var(--primary)';
chip.style.border = '1px solid rgba(var(--primary-rgb),0.2)';
let avatarHtml = `<div style="width:20px; height:20px; border-radius:50%; background:var(--primary); color:white; display:flex; align-items:center; justify-content:center; font-size:0.6rem; font-weight:700; overflow:hidden;">${name.charAt(0).toUpperCase()}</div>`;
if(pic) {
avatarHtml = `<img src="${pic}" style="width:20px; height:20px; border-radius:50%; object-fit:cover;">`;
}
chip.innerHTML = `${avatarHtml}<span style="font-weight:600;">${name}</span><button type="button" style="border:none;background:transparent;color:inherit;cursor:pointer;line-height:1;margin-left:2px;font-size:0.9rem;" title="Unshare" onclick="removeNoteShare(${Number(sh.id)})">×</button>`;
list.appendChild(chip);
});
}
function removeNoteShare(shareId) {
if(!shareId) return;
appConfirm('Unshare this note access?').then(y => {
if(y) {
document.getElementById('remove-note-share-id').value = String(shareId);
document.getElementById('remove-note-share-form').submit();
}
});
}
function filterNotes() {
const q = (document.getElementById('notes-search-input')?.value || '').toLowerCase().trim();
const lbl = (document.getElementById('notes-label-filter')?.value || '').trim();
document.querySelectorAll('.note-filter-item').forEach(card => {
const t = (card.dataset.title || '').toLowerCase();
const c = (card.dataset.content || '').toLowerCase();
// data-label is now comma separated
const cardLabels = (card.dataset.label || '').split(',').map(s=>s.trim());
const okText = !q || t.includes(q) || c.includes(q) || cardLabels.join(' ').includes(q);
const okLabel = !lbl || cardLabels.includes(lbl);
card.style.display = (okText && okLabel) ? '' : 'none';
});
}
function deleteNote(id) {
appConfirm('Delete this note permanently?').then(y => {
if(y) {
document.getElementById('delete-note-id').value = id;
document.getElementById('delete-note-form').submit();
}
});
}
// Fix note card colors in dark mode
function applyDarkNoteColors() {
const isDark = document.body.classList.contains('dark-mode');
document.querySelectorAll('.note-card').forEach(card => {
const origColor = card.dataset.color;
if(!origColor && isDark) {
card.style.background = 'var(--surface)';
}
});
}
const observer = new MutationObserver(applyDarkNoteColors);
observer.observe(document.body, {attributes: true, attributeFilter: ['class']});
applyDarkNoteColors();
</script>

View File

@@ -1,165 +1,693 @@
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_password'])) {
$stmt = $pdo->prepare("INSERT INTO passwords (title, username, password, url, notes, owner_id) VALUES (?, ?, ?, ?, ?, ?)");
$stmt->execute([$_POST['title'], $_POST['username'], $_POST['password'], $_POST['url'], $_POST['notes'], $user_id]);
// ── DB migrations ─────────────────────────────────────────────────────────────
try { $pdo->exec("ALTER TABLE passwords ADD COLUMN folder_id INTEGER DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE passwords ADD COLUMN tags TEXT DEFAULT NULL"); } catch(Exception $e) {}
try {
$pdo->exec("CREATE TABLE IF NOT EXISTS password_folders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
owner_id INTEGER,
FOREIGN KEY (owner_id) REFERENCES users(id) ON DELETE CASCADE
)");
} catch(Exception $e) {}
// ── Handle POST ───────────────────────────────────────────────────────────────
if($_SERVER['REQUEST_METHOD'] === 'POST') {
if(isset($_POST['create_folder'])) {
$stmt = $pdo->prepare("INSERT INTO password_folders (name, owner_id) VALUES (?, ?)");
$stmt->execute([$_POST['folder_name'], $user_id]);
}
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['bulk_action'])) {
if(isset($_POST['selected_passwords'])) {
if(isset($_POST['delete_folder'])) {
// Move items to no folder
$pdo->prepare("UPDATE passwords SET folder_id=NULL WHERE folder_id=? AND owner_id=?")->execute([$_POST['folder_id'], $user_id]);
$pdo->prepare("DELETE FROM password_folders WHERE id=? AND owner_id=?")->execute([$_POST['folder_id'], $user_id]);
}
if(isset($_POST['create_password'])) {
$stmt = $pdo->prepare("INSERT INTO passwords (title, username, password, url, notes, owner_id, folder_id, tags) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->execute([$_POST['title'], $_POST['username'], $_POST['password'], $_POST['url'], $_POST['notes'], $user_id, $_POST['folder_id'] ?: null, trim($_POST['tags'] ?? '')]);
notify_user($user_id, "You added a new password: " . $_POST['title'], ['action'=>'Created', 'module'=>'Password', 'item'=>$_POST['title']]);
}
if(isset($_POST['update_password'])) {
$p = query("SELECT owner_id FROM passwords WHERE id=?", [$_POST['password_id']])->fetch();
if($p && $p['owner_id'] == $user_id) {
$stmt = $pdo->prepare("UPDATE passwords SET title=?, username=?, password=?, url=?, notes=?, folder_id=?, tags=? WHERE id=? AND owner_id=?");
$stmt->execute([$_POST['title'], $_POST['username'], $_POST['password'], $_POST['url'], $_POST['notes'], $_POST['folder_id'] ?: null, trim($_POST['tags'] ?? ''), $_POST['password_id'], $user_id]);
$ctx = ['action'=>'Updated', 'module'=>'Password', 'item'=>$_POST['title']];
notify_user($user_id, "Password '{$_POST['title']}' updated.", $ctx);
// Notify shared users/groups
$shares = query("SELECT share_type, share_id FROM password_shares WHERE password_id=?", [$_POST['password_id']])->fetchAll();
foreach($shares as $sh) {
if($sh['share_type'] === 'user') notify_user($sh['share_id'], "Shared password '{$_POST['title']}' updated.", $ctx);
else notify_group($sh['share_id'], "Shared group password '{$_POST['title']}' updated.", $ctx);
}
}
}
if(isset($_POST['delete_password'])) {
$p = query("SELECT owner_id, title FROM passwords WHERE id=?", [$_POST['password_id']])->fetch();
$ctx = ['action'=>'Deleted', 'module'=>'Password', 'item'=>$p['title']];
// Notify shared recipients before deletion
$shares = query("SELECT share_type, share_id FROM password_shares WHERE password_id=?", [$_POST['password_id']])->fetchAll();
foreach($shares as $sh) {
if($sh['share_type'] === 'user') notify_user($sh['share_id'], "Shared password '{$p['title']}' has been deleted.", $ctx);
else notify_group($sh['share_id'], "Shared group password '{$p['title']}' has been deleted.", $ctx);
}
query("DELETE FROM passwords WHERE id=? AND owner_id=?", [$_POST['password_id'], $user_id]);
notify_user($user_id, "Password '{$p['title']}' deleted.", $ctx);
}
// Unshare a specific share record
if(isset($_POST['remove_password_share'])) {
$share_id = (int)$_POST['share_id'];
$chk = query("SELECT ps.id FROM password_shares ps JOIN passwords p ON ps.password_id=p.id WHERE ps.id=? AND p.owner_id=?", [$share_id, $user_id])->fetch();
if($chk) query("DELETE FROM password_shares WHERE id=?", [$share_id]);
}
if(isset($_POST['bulk_action']) && isset($_POST['selected_passwords'])) {
$selected = $_POST['selected_passwords'];
$action = $_POST['bulk_action'];
if($action === 'delete') {
foreach($selected as $p_id) {
// Check if owner
$p = query("SELECT owner_id FROM passwords WHERE id=?", [$p_id])->fetch();
$p = query("SELECT owner_id, title FROM passwords WHERE id=?", [$p_id])->fetch();
if($p && $p['owner_id']==$user_id) {
query("DELETE FROM passwords WHERE id=?", [$p_id]);
notify_waha('Deleted', 'Password Entry', $p['title']);
}
}
} elseif($action === 'share') {
$share_target = $_POST['share_target']; // 'user_1'
$parts = explode('_', $share_target);
$share_target = $_POST['share_target'];
$parts = explode('_', $share_target, 2);
if(count($parts)===2) {
foreach($selected as $p_id) {
$p = query("SELECT owner_id, title FROM passwords WHERE id=?", [$p_id])->fetch();
if($p && $p['owner_id']==$user_id) {
$stmt = $pdo->prepare("INSERT INTO password_shares (password_id, share_type, share_id) VALUES (?, ?, ?)");
$stmt->execute([$p_id, $parts[0], $parts[1]]);
$msg = "A password '{$p['title']}' has been shared with you.";
if($parts[0] === 'user') notify_user($parts[1], $msg);
else notify_group($parts[1], $msg);
$ctx = ['action'=>'Shared', 'module'=>'Password', 'item'=>$p['title'], 'user'=>$_SESSION['username']??'System'];
if($parts[0] === 'user') notify_user($parts[1], $msg, $ctx);
else notify_group($parts[1], $msg, $ctx);
}
}
}
} elseif($action === 'move_folder' && isset($_POST['move_folder_target'])) {
$fid = $_POST['move_folder_target'] ?: null;
foreach($selected as $p_id) {
$p = query("SELECT owner_id FROM passwords WHERE id=?", [$p_id])->fetch();
if($p && $p['owner_id']==$user_id) {
$pdo->prepare("UPDATE passwords SET folder_id=? WHERE id=?")->execute([$fid, $p_id]);
}
}
}
}
}
// Fetch passwords (owned + shared)
// ── Fetch ─────────────────────────────────────────────────────────────────────
$user_groups = get_user_groups($user_id);
$my_group_ids = array_column($user_groups, 'id');
$group_in = implode(',', array_fill(0, count($my_group_ids), '?')) ?: '0';
$params = array_merge([$user_id, $user_id], $my_group_ids);
$params = array_merge([$user_id, $user_id, $user_id], $my_group_ids);
$sql = "SELECT p.*, (p.owner_id = ?) as is_mine FROM passwords p
$sql = "SELECT p.*, (p.owner_id = ?) as is_mine, pf.name as folder_name FROM passwords p
LEFT JOIN password_shares ps ON p.id = ps.password_id
LEFT JOIN password_folders pf ON p.folder_id = pf.id
WHERE p.owner_id = ?
OR (ps.share_type='user' AND ps.share_id = ?)
OR (ps.share_type='group' AND ps.share_id IN ($group_in))
GROUP BY p.id ORDER BY p.title";
$params = array_merge([$user_id, $user_id, $user_id], $my_group_ids);
GROUP BY p.id ORDER BY pf.name ASC, p.title ASC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$passwords = $stmt->fetchAll();
// Folder list (own folders only)
$folders = query("SELECT * FROM password_folders WHERE owner_id=? ORDER BY name", [$user_id])->fetchAll();
$all_users = query("SELECT id, username FROM users WHERE id != ?", [$user_id])->fetchAll();
$all_groups = query("SELECT * FROM groups")->fetchAll();
// Group passwords by folder
$grouped = ['__none__' => []];
foreach($folders as $f) $grouped[$f['id']] = [];
foreach($passwords as $p) {
$fk = $p['folder_id'] ?? '__none__';
if(!isset($grouped[$fk])) $grouped[$fk] = [];
$grouped[$fk][] = $p;
}
// Active folder filter
$active_folder = $_GET['vault_folder'] ?? 'all';
?>
<div class="header">
<h1>Passwords Vault</h1>
</div>
<div class="modal-overlay" id="password-modal">
<div class="modal-content">
<h3 style="margin-bottom:1rem;">Password View</h3>
<input type="text" id="modal-password" class="form-control" readonly style="margin-bottom:1rem; font-family:monospace; font-size:1.1rem;">
<div style="display:flex; gap:0.5rem; justify-content:flex-end;">
<button type="button" class="btn btn-secondary" onclick="document.getElementById('password-modal').classList.remove('active')">Close</button>
</div>
</div>
</div>
<div style="display:grid; grid-template-columns: 1fr 2fr; gap:1.5rem;">
<div class="card">
<h3>Add Password</h3>
<form method="POST" style="margin-top:1rem;">
<div class="form-group"><input type="text" name="title" class="form-control" placeholder="Title/Service" required></div>
<div class="form-group"><input type="text" name="username" class="form-control" placeholder="Username"></div>
<div class="form-group" style="display:flex; gap:0.5rem;">
<input type="password" name="password" id="new_pw" class="form-control" placeholder="Password" required>
<button type="button" class="btn btn-secondary" onclick="genPassword()">🎲</button>
</div>
<div class="form-group"><input type="text" name="url" class="form-control" placeholder="Website URL"></div>
<div class="form-group"><textarea name="notes" class="form-control" placeholder="Notes"></textarea></div>
<button type="submit" name="create_password" class="btn">Save Password</button>
</form>
</div>
<div class="card">
<h3>My Vault</h3>
<form method="POST" id="bulk-form">
<div style="display:flex; justify-content:space-between; margin-bottom:1rem;">
<!-- ── Password View Modal ─────────────────────────────────────────────────── -->
<div class="modal-overlay" id="password-view-modal">
<div class="modal-content" style="max-width:380px;">
<h3 style="margin-bottom:1rem; font-size:1.05rem;">Password Entry</h3>
<div id="pw-view-title" style="font-weight:700; font-size:1rem; margin-bottom:0.25rem;"></div>
<div id="pw-view-url" style="font-size:0.8rem; color:var(--primary); margin-bottom:1rem;"></div>
<div class="form-group" style="margin-bottom:0.5rem;">
<label style="font-size:0.78rem; color:var(--text-light);">Username</label>
<div style="display:flex; gap:0.5rem;">
<button type="submit" name="bulk_action" value="delete" class="btn btn-sm btn-danger" onclick="return confirm('Delete selected?')">Delete Selected</button>
<div style="display:flex; align-items:center;">
<select name="share_target" class="form-control" style="width:150px; padding:0.25rem;">
<?php foreach($all_users as $u): ?><option value="user_<?= $u['id'] ?>">User: <?= htmlspecialchars($u['username']) ?></option><?php endforeach; ?>
<?php foreach($all_groups as $g): ?><option value="group_<?= $g['id'] ?>">Group: <?= htmlspecialchars($g['name']) ?></option><?php endforeach; ?>
</select>
<button type="submit" name="bulk_action" value="share" class="btn btn-sm" style="margin-left:0.5rem;">Share Selected</button>
<input type="text" id="pw-view-user" class="form-control" readonly>
<button class="btn btn-secondary btn-sm" onclick="copyFieldValue('pw-view-user')"><i class="fa fa-copy"></i></button>
</div>
</div>
<div style="color:var(--text-light);font-size:0.875rem;">Shortcuts:<br>Ctrl+B (Copy User), Ctrl+C (Copy Password)<br>Hover row to activate</div>
<div class="form-group">
<label style="font-size:0.78rem; color:var(--text-light);">Password</label>
<div style="display:flex; gap:0.5rem;">
<input type="password" id="pw-view-pw" class="form-control" readonly style="font-family:monospace;">
<button class="btn btn-secondary btn-sm" onclick="togglePwView()" id="pw-view-toggle"><i class="fa fa-eye"></i></button>
<button class="btn btn-sm" onclick="copyFieldValue('pw-view-pw')"><i class="fa fa-copy"></i></button>
</div>
<table>
<thead><tr><th><input type="checkbox" onclick="toggleAll(this)"></th><th>Title</th><th>Username</th><th>Actions</th></tr></thead>
<tbody>
<?php foreach($passwords as $p): ?>
<tr class="pw-row" data-pw="<?= htmlspecialchars($p['password']) ?>" data-usr="<?= htmlspecialchars((string)$p['username']) ?>">
<td><?php if($p['is_mine']): ?><input type="checkbox" name="selected_passwords[]" value="<?= $p['id'] ?>" class="pw-checkbox"><?php endif; ?></td>
<td><?= htmlspecialchars($p['title']) ?> <?= !$p['is_mine'] ? '<span class="badge" style="background:var(--secondary);">Shared</span>' : '' ?></td>
<td><?= htmlspecialchars((string)$p['username']) ?></td>
<td>
<button type="button" onclick="showGw('<?= htmlspecialchars(addslashes($p['password'])) ?>')" class="btn btn-sm btn-secondary">👀 View</button>
<button type="button" onclick="copyText('<?= htmlspecialchars(addslashes($p['password'])) ?>')" class="btn btn-sm">📋 Copy Pw</button>
</td>
</tr>
</div>
<div id="pw-view-notes" style="font-size:0.8rem; color:var(--text-light); margin-top:0.5rem; white-space:pre-wrap;"></div>
<div id="pw-view-tags-container" style="display:none; flex-wrap:wrap; gap:0.25rem; margin-top:1rem; padding-top:0.5rem; border-top:1px dashed var(--border);"></div>
<div style="display:flex; justify-content:flex-end; gap:0.5rem; margin-top:1rem;">
<button class="btn btn-secondary" onclick="document.getElementById('password-view-modal').classList.remove('active')">Close</button>
</div>
</div>
</div>
<!-- ── Add/Edit Password Modal ────────────────────────────────────────────── -->
<div class="modal-overlay" id="password-edit-modal">
<div class="modal-content" style="max-width:480px;">
<h3 style="margin-bottom:1rem; font-size:1.05rem;" id="pw-edit-modal-title">Add Password</h3>
<form method="POST" id="pw-edit-form">
<input type="hidden" name="password_id" id="pw-edit-id">
<div class="form-group">
<label>Title / Service</label>
<input type="text" name="title" id="pw-edit-title" class="form-control" placeholder="e.g. Google Account" required>
</div>
<div class="form-group">
<label>Username / Email</label>
<input type="text" name="username" id="pw-edit-uname" class="form-control" placeholder="Username or email">
</div>
<div class="form-group">
<label>Password</label>
<div style="display:flex; gap:0.5rem;">
<input type="password" name="password" id="pw-edit-pw" class="form-control" placeholder="Password" required>
<button type="button" class="btn btn-secondary btn-sm" onclick="toggleEditPwView()" title="Show/hide"><i class="fa fa-eye" id="pw-edit-eye"></i></button>
<button type="button" class="btn btn-secondary btn-sm" onclick="genPassword()" title="Generate"><i class="fa fa-shuffle"></i></button>
</div>
<!-- Password strength bar -->
<div id="pw-strength-bar" style="height:4px; background:var(--border); border-radius:4px; margin-top:4px; overflow:hidden;">
<div id="pw-strength-fill" style="height:100%; width:0%; transition:width 0.3s, background 0.3s;"></div>
</div>
<div id="pw-strength-label" style="font-size:0.72rem; color:var(--text-light); margin-top:2px;"></div>
</div>
<div class="form-group">
<label>Website URL</label>
<input type="text" name="url" id="pw-edit-url" class="form-control" placeholder="https://...">
</div>
<div class="form-group">
<label>Folder</label>
<select name="folder_id" id="pw-edit-folder" class="form-control">
<option value="">— No Folder —</option>
<?php foreach($folders as $f): ?>
<option value="<?= $f['id'] ?>"><?= htmlspecialchars($f['name']) ?></option>
<?php endforeach; ?>
</tbody>
</table>
</select>
</div>
<div class="form-group">
<label>Notes</label>
<textarea name="notes" id="pw-edit-notes" class="form-control" rows="2" placeholder="Optional notes..."></textarea>
</div>
<div class="form-group">
<label>Tags</label>
<input type="text" name="tags" id="pw-edit-tags" class="form-control tagify-input" placeholder="Add tags...">
</div>
<!-- Shares management section (populated by JS) -->
<div id="pw-shares-section" style="display:none; border-top:1px solid var(--border); padding-top:0.75rem; margin-top:0.5rem;">
<label style="font-size:0.8rem; color:var(--text-light); display:block; margin-bottom:0.4rem;">Shared with</label>
<div id="pw-shares-list" style="display:flex; flex-wrap:wrap; gap:0.35rem;"></div>
</div>
<div style="display:flex; justify-content:space-between; gap:0.5rem; flex-wrap:wrap; margin-top:0.75rem;">
<div id="pw-edit-delete-wrap" style="display:none;">
<button type="button" class="btn btn-danger btn-sm" onclick="deletePassword()"><i class="fa fa-trash"></i> Delete</button>
</div>
<div style="display:flex; gap:0.5rem; margin-left:auto;">
<button type="button" class="btn btn-secondary" onclick="document.getElementById('password-edit-modal').classList.remove('active')">Cancel</button>
<button type="submit" class="btn" id="pw-save-btn"><i class="fa fa-save"></i> Save</button>
</div>
</div>
</form>
</div>
</div>
<!-- Delete Password form -->
<form method="POST" id="delete-pw-form" style="display:none;">
<input type="hidden" name="delete_password" value="1">
<input type="hidden" name="password_id" id="delete-pw-id">
</form>
<form method="POST" id="remove-share-form" style="display:none;">
<input type="hidden" name="remove_password_share" value="1">
<input type="hidden" name="share_id" id="remove-share-id">
</form>
<!-- Add folder form (hidden) -->
<form method="POST" id="add-folder-form" style="display:none;">
<input type="hidden" name="create_folder" value="1">
<input type="hidden" name="folder_name" id="add-folder-name">
</form>
<form method="POST" id="del-folder-form" style="display:none;">
<input type="hidden" name="delete_folder" value="1">
<input type="hidden" name="folder_id" id="del-folder-id">
</form>
<div style="background:var(--surface); border-radius:1rem; box-shadow:0 4px 6px -1px rgba(0,0,0,0.07); border:1px solid var(--border); overflow:hidden;">
<div class="vault-layout" style="min-height:calc(100vh - 130px);">
<!-- Vault Sidebar (Folders) -->
<div class="vault-sidebar">
<div style="font-size:0.7rem; text-transform:uppercase; letter-spacing:0.06em; color:var(--text-light); font-weight:700; padding:0.25rem 0.65rem; margin-bottom:0.25rem;">Folders</div>
<a href="?action=passwords&vault_folder=all" class="vault-folder-item <?= $active_folder==='all'?'active':'' ?>">
<i class="fa fa-vault"></i> All Entries
<span style="margin-left:auto; font-size:0.75rem; background:rgba(var(--primary-rgb),0.1); color:var(--primary); padding:1px 6px; border-radius:10px;"><?= count($passwords) ?></span>
</a>
<a href="?action=passwords&vault_folder=__none__" class="vault-folder-item <?= $active_folder==='__none__'?'active':'' ?>">
<i class="fa fa-inbox"></i> No Folder
<span style="margin-left:auto; font-size:0.75rem; background:rgba(var(--primary-rgb),0.1); color:var(--primary); padding:1px 6px; border-radius:10px;"><?= count($grouped['__none__'] ?? []) ?></span>
</a>
<?php foreach($folders as $f): ?>
<div style="display:flex; align-items:center; gap:0;">
<a href="?action=passwords&vault_folder=<?= $f['id'] ?>" class="vault-folder-item <?= $active_folder==$f['id']?'active':'' ?>" style="flex:1;">
<i class="fa fa-folder"></i> <?= htmlspecialchars($f['name']) ?>
<span style="margin-left:auto; font-size:0.75rem; background:rgba(var(--primary-rgb),0.1); color:var(--primary); padding:1px 6px; border-radius:10px;"><?= count($grouped[$f['id']] ?? []) ?></span>
</a>
<button class="vault-folder-item" style="width:28px; padding:0.3rem; flex-shrink:0; color:var(--text-light);" onclick="deleteFolder(<?= $f['id'] ?>, '<?= htmlspecialchars(addslashes($f['name'])) ?>')" title="Delete folder"><i class="fa fa-xmark" style="font-size:0.75rem;"></i></button>
</div>
<?php endforeach; ?>
<div style="margin-top:auto; padding-top:0.75rem; border-top:1px solid var(--border);">
<div style="font-size:0.7rem; color:var(--text-light); text-align:center;">
<i class="fa fa-lock"></i> <?= count($passwords) ?> entries
</div>
</div>
</div>
<!-- Vault Main -->
<div class="vault-main">
<div style="display:flex; justify-content:flex-end; gap:0.5rem; flex-wrap:wrap; margin-bottom:1rem;">
<button class="btn btn-secondary" onclick="showAddFolderPrompt()"><i class="fa fa-folder-plus"></i> New Folder</button>
<button class="btn" onclick="openAddPassword()"><i class="fa fa-plus"></i> Add Entry</button>
</div>
<!-- Search + Bulk Actions -->
<div class="vault-search">
<div style="position:relative; flex:1;">
<i class="fa fa-search" style="position:absolute; left:0.75rem; top:50%; transform:translateY(-50%); color:var(--text-light); font-size:0.875rem;"></i>
<input type="text" id="vault-search-input" class="form-control" placeholder="Search entries..." style="padding-left:2.2rem;" oninput="filterVault(this.value)">
</div>
</div>
<!-- Bulk Actions -->
<form method="POST" id="bulk-form" style="margin-bottom:1rem;">
<div style="display:flex; gap:0.5rem; flex-wrap:wrap; align-items:center; font-size:0.8rem; color:var(--text-light);">
<label style="display:flex; align-items:center; gap:0.35rem; cursor:pointer; font-weight:600;">
<input type="checkbox" id="select-all-chk" onclick="toggleAll(this)"> Select All
</label>
<select name="share_target" class="form-control" style="width:160px; padding:0.35rem; font-size:0.8rem;">
<?php foreach($all_users as $u): ?>
<option value="user_<?= $u['id'] ?>">👤 <?= htmlspecialchars($u['username']) ?></option>
<?php endforeach; ?>
<?php foreach($all_groups as $g): ?>
<option value="group_<?= $g['id'] ?>">👥 <?= htmlspecialchars($g['name']) ?></option>
<?php endforeach; ?>
</select>
<button type="submit" name="bulk_action" value="share" class="btn btn-sm btn-secondary"><i class="fa fa-share-nodes"></i> Share</button>
<select name="move_folder_target" class="form-control" style="width:130px; padding:0.35rem; font-size:0.8rem;">
<option value="">— No Folder —</option>
<?php foreach($folders as $f): ?>
<option value="<?= $f['id'] ?>"><?= htmlspecialchars($f['name']) ?></option>
<?php endforeach; ?>
</select>
<button type="submit" name="bulk_action" value="move_folder" class="btn btn-sm btn-secondary"><i class="fa fa-folder-arrow-down"></i> Move</button>
<button type="button" class="btn btn-sm btn-danger" onclick="appConfirm('Delete selected entries?').then(y => { if(y) { const el = document.createElement('input'); el.type='hidden'; el.name='bulk_action'; el.value='delete'; this.form.appendChild(el); this.form.submit(); } })"><i class="fa fa-trash"></i> Delete</button>
</div>
<!-- Entries List -->
<div style="margin-top:0.75rem;">
<?php
// Determine which passwords to show
$show_passwords = [];
if($active_folder === 'all') {
$show_passwords = $passwords;
} elseif(isset($grouped[$active_folder])) {
$show_passwords = $grouped[$active_folder];
}
if(empty($show_passwords)):
?>
<div style="text-align:center; padding:3rem 1rem; color:var(--text-light);">
<div style="font-size:2.5rem; margin-bottom:0.75rem;">🔐</div>
<p>No entries here yet.</p>
</div>
<?php else: ?>
<?php
// Group by folder when showing "all"
if($active_folder === 'all') {
$display_groups = ['__none__' => ['label'=>'No Folder','entries'=>[]]];
foreach($folders as $f) $display_groups[$f['id']] = ['label'=>$f['name'],'entries'=>[]];
foreach($show_passwords as $p) {
$key = $p['folder_id'] ?? '__none__';
if(!isset($display_groups[$key])) $display_groups[$key] = ['label'=>'No Folder','entries'=>[]];
$display_groups[$key]['entries'][] = $p;
}
} else {
$display_groups = ['current' => ['label'=> ($active_folder==='__none__' ? 'No Folder' : (array_column($folders,'name','id')[$active_folder] ?? 'Folder')), 'entries'=>$show_passwords]];
}
foreach($display_groups as $gkey => $gdata):
if(empty($gdata['entries'])) continue;
?>
<?php if($active_folder === 'all'): ?>
<div style="font-size:0.72rem; text-transform:uppercase; letter-spacing:0.06em; color:var(--text-light); font-weight:700; padding:0.75rem 0 0.35rem; display:flex; align-items:center; gap:0.5rem;">
<i class="fa <?= $gkey==='__none__' ? 'fa-inbox' : 'fa-folder' ?>"></i>
<?= htmlspecialchars($gdata['label']) ?>
<span style="background:rgba(var(--primary-rgb),0.1); color:var(--primary); padding:1px 6px; border-radius:10px;"><?= count($gdata['entries']) ?></span>
</div>
<?php endif; ?>
<?php foreach($gdata['entries'] as $p):
$domain = '';
if($p['url']) {
$parsed = parse_url($p['url']);
$domain = $parsed['host'] ?? '';
$domain = preg_replace('/^www\./', '', $domain);
}
$favicon = $domain ? "https://www.google.com/s2/favicons?domain={$domain}&sz=32" : '';
$pw_shares = [];
if($p['is_mine']) {
$pw_shares = query("SELECT ps.id, ps.share_type, ps.share_id, u.username, u.profile_pic as upic, g.name as gname, g.profile_pic as gpic FROM password_shares ps LEFT JOIN users u ON (ps.share_type='user' AND ps.share_id=u.id) LEFT JOIN groups g ON (ps.share_type='group' AND ps.share_id=g.id) WHERE ps.password_id=?", [$p['id']])->fetchAll();
}
$shares_json = htmlspecialchars(json_encode($pw_shares), ENT_QUOTES, 'UTF-8');
?>
<div class="vault-entry pw-row"
data-pw="<?= htmlspecialchars(addslashes($p['password'])) ?>"
data-usr="<?= htmlspecialchars((string)$p['username']) ?>"
data-id="<?= $p['id'] ?>"
data-url="<?= htmlspecialchars((string)($p['url'] ?? '')) ?>"
data-notes="<?= htmlspecialchars(addslashes((string)($p['notes'] ?? ''))) ?>"
data-folder-id="<?= htmlspecialchars((string)($p['folder_id'] ?? '')) ?>"
data-shares="<?= $shares_json ?>"
data-tags="<?= htmlspecialchars((string)($p['tags'] ?? '')) ?>"
onclick="openViewEntry(this)">
<!-- Checkbox (only for owned items) -->
<?php if($p['is_mine']): ?>
<div onclick="event.stopPropagation()">
<input type="checkbox" name="selected_passwords[]" value="<?= $p['id'] ?>" class="pw-checkbox">
</div>
<?php else: ?>
<div style="width:16px;"></div>
<?php endif; ?>
<!-- Icon -->
<div class="vault-entry-icon">
<?php if($favicon): ?>
<img src="<?= htmlspecialchars($favicon) ?>" alt="" onerror="this.style.display='none'; this.nextSibling.style.display='flex';">
<span style="display:none;"><i class="fa fa-globe"></i></span>
<?php else: ?>
<i class="fa fa-key"></i>
<?php endif; ?>
</div>
<!-- Info -->
<div class="vault-entry-info">
<div class="vault-entry-title">
<?= htmlspecialchars($p['title']) ?>
<?php if(!$p['is_mine']): ?><span class="badge" style="font-size:0.6rem; padding:1px 5px; vertical-align:middle; margin-left:4px;">Shared</span><?php endif; ?>
</div>
<div class="vault-entry-user"><?= htmlspecialchars((string)$p['username']) ?: ($domain ?: '—') ?></div>
</div>
<!-- Actions -->
<div class="vault-entry-actions" onclick="event.stopPropagation()">
<button type="button" class="btn btn-sm btn-secondary" onclick="copyPw(this.closest('.vault-entry').dataset.pw)" title="Copy Password"><i class="fa fa-copy"></i></button>
<?php if($p['is_mine']): ?>
<button type="button" class="btn btn-sm btn-secondary" onclick="openEditEntry(this.closest('.vault-entry'))" title="Edit"><i class="fa fa-pen"></i></button>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>
</div>
</form>
<!-- Status bar -->
<div class="explorer-status-bar">
<span><i class="fa fa-database" style="margin-right:4px;"></i><?= count($passwords) ?> total entries</span>
<span title="Keyboard Shortcuts">Hover + Ctrl+C = Copy PW &nbsp;|&nbsp; Ctrl+B = Copy Username</span>
</div>
</div>
</div>
</div>
<script>
// ── Password strength ─────────────────────────────────────────────────────────
document.getElementById('pw-edit-pw').addEventListener('input', function() {
const v = this.value;
let score = 0;
if(v.length >= 8) score++;
if(v.length >= 12) score++;
if(/[A-Z]/.test(v)) score++;
if(/[0-9]/.test(v)) score++;
if(/[^A-Za-z0-9]/.test(v)) score++;
const fills = ['0%','25%','50%','75%','100%'];
const colors = ['#EF4444','#F59E0B','#EAB308','#10B981','#10B981'];
const labels = ['','Weak','Fair','Good','Strong','Very Strong'];
document.getElementById('pw-strength-fill').style.width = fills[score];
document.getElementById('pw-strength-fill').style.background = colors[Math.max(0,score-1)];
document.getElementById('pw-strength-label').textContent = v.length > 0 ? labels[score] : '';
});
function genPassword() {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+";
let p = "";
for(let i=0; i<16; i++) p += chars[Math.floor(Math.random()*chars.length)];
document.getElementById('new_pw').value = p;
document.getElementById('new_pw').type = 'text'; // show it temporarily
for(let i=0; i<18; i++) p += chars[Math.floor(Math.random()*chars.length)];
const inp = document.getElementById('pw-edit-pw');
inp.value = p;
inp.type = 'text';
inp.dispatchEvent(new Event('input'));
setTimeout(() => inp.type = 'password', 2500);
}
function showGw(pw) {
document.getElementById('modal-password').value = pw;
document.getElementById('password-modal').classList.add('active');
function toggleEditPwView() {
const inp = document.getElementById('pw-edit-pw');
const eye = document.getElementById('pw-edit-eye');
inp.type = inp.type === 'password' ? 'text' : 'password';
eye.className = inp.type === 'password' ? 'fa fa-eye' : 'fa fa-eye-slash';
}
function togglePwView() {
const inp = document.getElementById('pw-view-pw');
const btn = document.getElementById('pw-view-toggle');
inp.type = inp.type === 'password' ? 'text' : 'password';
btn.innerHTML = inp.type === 'password' ? '<i class="fa fa-eye"></i>' : '<i class="fa fa-eye-slash"></i>';
}
function copyPw(pw) {
navigator.clipboard.writeText(pw);
showToast('Password copied!');
}
function copyFieldValue(id) {
const val = document.getElementById(id).value;
navigator.clipboard.writeText(val);
showToast('Copied!');
}
// ── Open view modal ───────────────────────────────────────────────────────────
function openViewEntry(row) {
document.getElementById('pw-view-title').textContent = row.querySelector('.vault-entry-title').textContent.trim();
document.getElementById('pw-view-user').value = row.dataset.usr;
document.getElementById('pw-view-pw').value = row.dataset.pw;
document.getElementById('pw-view-pw').type = 'password';
document.getElementById('pw-view-toggle').innerHTML = '<i class="fa fa-eye"></i>';
const urlEl = document.createElement('div');
document.getElementById('pw-view-url').innerHTML = ''; // Clear existing
if(row.dataset.url) {
urlEl.innerHTML = `<a href="${row.dataset.url}" target="_blank" style="color:var(--primary);">${row.dataset.url}</a>`;
document.getElementById('pw-view-url').appendChild(urlEl);
}
document.getElementById('pw-view-notes').textContent = row.dataset.notes || '';
// Tag rendering
const tagsContainer = document.getElementById('pw-view-tags-container');
tagsContainer.innerHTML = '';
const tagsStr = row.dataset.tags || '';
if(tagsStr) {
tagsContainer.style.display = 'flex';
tagsStr.split(',').forEach(t => {
t = t.trim();
if(!t) return;
const span = document.createElement('span');
span.style.cssText = 'font-size:0.65rem; padding:2px 8px; border-radius:12px; background:rgba(var(--primary-rgb),0.12); color:var(--primary); font-weight:600; display:inline-flex; align-items:center; gap:0.2rem;';
span.innerHTML = `<i class="fa fa-tag" style="font-size:0.6rem;"></i> ${t}`;
tagsContainer.appendChild(span);
});
} else {
tagsContainer.style.display = 'none';
}
document.getElementById('password-view-modal').classList.add('active');
}
// ── Open add/edit modal ───────────────────────────────────────────────────────
function openAddPassword() {
document.getElementById('pw-edit-modal-title').textContent = 'Add Entry';
document.getElementById('pw-edit-form').onsubmit = null;
document.getElementById('pw-edit-form').querySelector('[name="password_id"]').name = '_unused';
// Reset name for create
const form = document.getElementById('pw-edit-form');
// Remove any update_password and add create_password
let existing = form.querySelector('[name="update_password"]');
if(existing) existing.remove();
let cp = form.querySelector('[name="create_password"]');
if(!cp) {
cp = document.createElement('input');
cp.type = 'hidden'; cp.name = 'create_password'; cp.value = '1';
form.appendChild(cp);
}
document.getElementById('pw-edit-id').value = '';
document.getElementById('pw-edit-title').value = '';
document.getElementById('pw-edit-uname').value = '';
document.getElementById('pw-edit-pw').value = '';
document.getElementById('pw-edit-pw').type = 'password';
document.getElementById('pw-edit-url').value = '';
document.getElementById('pw-edit-notes').value = '';
document.getElementById('pw-edit-folder').value = '';
document.getElementById('pw-edit-tags').value = '';
document.getElementById('pw-shares-section').style.display = 'none';
document.getElementById('pw-shares-list').innerHTML = '';
document.getElementById('pw-edit-delete-wrap').style.display = 'none';
document.getElementById('pw-edit-pw').dispatchEvent(new Event('input'));
document.getElementById('password-edit-modal').classList.add('active');
}
function openEditEntry(row) {
// We need full data – fetch from server or use data attributes
// For now we do a quick fetch via a hidden AJAX or just open with available data
const id = row.dataset.id;
document.getElementById('pw-edit-modal-title').textContent = 'Edit Entry';
const form = document.getElementById('pw-edit-form');
let cp = form.querySelector('[name="create_password"]');
if(cp) cp.remove();
let up = form.querySelector('[name="update_password"]');
if(!up) {
up = document.createElement('input');
up.type = 'hidden'; up.name = 'update_password'; up.value = '1';
form.appendChild(up);
}
form.querySelector('[name="password_id"]').name = 'password_id';
document.getElementById('pw-edit-id').value = id;
document.getElementById('pw-edit-title').value = row.querySelector('.vault-entry-title').textContent.trim();
document.getElementById('pw-edit-uname').value = row.dataset.usr;
document.getElementById('pw-edit-pw').value = row.dataset.pw;
document.getElementById('pw-edit-pw').type = 'password';
document.getElementById('pw-edit-url').value = row.dataset.url || '';
document.getElementById('pw-edit-notes').value = row.dataset.notes || '';
document.getElementById('pw-edit-folder').value = row.dataset.folderId || '';
document.getElementById('pw-edit-tags').value = row.dataset.tags || '';
document.getElementById('pw-edit-delete-wrap').style.display = 'block';
renderPasswordShares(row.dataset.shares || '[]');
document.getElementById('password-edit-modal').classList.add('active');
}
function renderPasswordShares(jsonShares) {
const sec = document.getElementById('pw-shares-section');
const list = document.getElementById('pw-shares-list');
list.innerHTML = '';
let shares = [];
try { shares = JSON.parse(jsonShares || '[]'); } catch(e) { shares = []; }
if(!shares || shares.length === 0) {
sec.style.display = 'none';
return;
}
shares.forEach(sh => {
const pic = sh.share_type === 'user' ? sh.upic : sh.gpic;
const name = sh.share_type === 'user' ? (sh.username || 'User') : (sh.gname || 'Group');
const chip = document.createElement('div');
chip.style.display = 'inline-flex';
chip.style.alignItems = 'center';
chip.style.gap = '0.4rem';
chip.style.fontSize = '0.72rem';
chip.style.padding = '2px 8px 2px 2px';
chip.style.borderRadius = '999px';
chip.style.background = 'rgba(var(--primary-rgb),0.1)';
chip.style.color = 'var(--primary)';
chip.style.border = '1px solid rgba(var(--primary-rgb),0.2)';
let avatarHtml = `<div style="width:20px; height:20px; border-radius:50%; background:var(--primary); color:white; display:flex; align-items:center; justify-content:center; font-size:0.6rem; font-weight:700; overflow:hidden;">${name.charAt(0).toUpperCase()}</div>`;
if(pic) {
avatarHtml = `<img src="${pic}" style="width:20px; height:20px; border-radius:50%; object-fit:cover;">`;
}
chip.innerHTML = `${avatarHtml}<span style="font-weight:600;">${name}</span><button type="button" style="border:none;background:transparent;color:inherit;cursor:pointer;line-height:1;margin-left:2px;font-size:0.9rem;" title="Unshare" onclick="removePasswordShare(${Number(sh.id)})">×</button>`;
list.appendChild(chip);
});
sec.style.display = 'block';
}
function removePasswordShare(shareId) {
if(!shareId) return;
appConfirm('Unshare this password access?').then(y => {
if(y) {
document.getElementById('remove-share-id').value = String(shareId);
document.getElementById('remove-share-form').submit();
}
});
}
function deletePassword() {
appConfirm('Delete this entry permanently?').then(y => {
if(y) {
document.getElementById('delete-pw-id').value = document.getElementById('pw-edit-id').value;
document.getElementById('delete-pw-form').submit();
}
});
}
// ── Toggles ───────────────────────────────────────────────────────────────────
function toggleAll(chk) {
document.querySelectorAll('.pw-checkbox').forEach(c => c.checked = chk.checked);
}
function copyText(txt) {
navigator.clipboard.writeText(txt);
showToast('Copied to clipboard!');
function filterVault(q) {
q = q.toLowerCase();
document.querySelectorAll('.vault-entry').forEach(row => {
const text = row.textContent.toLowerCase();
const tags = (row.dataset.tags || '').toLowerCase();
row.style.display = (text.includes(q) || tags.includes(q)) ? '' : 'none';
});
}
// Hotkeys Ctrl+C and Ctrl+B on hovered row
// ── Folder actions ────────────────────────────────────────────────────────────
function showAddFolderPrompt() {
const name = prompt('New folder name:');
if(name && name.trim()) {
document.getElementById('add-folder-name').value = name.trim();
document.getElementById('add-folder-form').submit();
}
}
function deleteFolder(id, name) {
appConfirm(`Delete folder "${name}"? Entries will not be deleted.`).then(y => {
if(y) {
document.getElementById('del-folder-id').value = id;
document.getElementById('del-folder-form').submit();
}
});
}
// ── Hotkeys on hovered row ────────────────────────────────────────────────────
let hoveredRow = null;
document.querySelectorAll('.pw-row').forEach(row => {
row.addEventListener('mouseenter', () => hoveredRow = row);
row.addEventListener('mouseleave', () => hoveredRow = null);
});
document.addEventListener('keydown', (e) => {
if(hoveredRow && e.ctrlKey) {
if(e.key.toLowerCase() === 'c') {
copyText(hoveredRow.getAttribute('data-pw'));
e.preventDefault();
} else if(e.key.toLowerCase() === 'b') {
copyText(hoveredRow.getAttribute('data-usr'));
e.preventDefault();
}
if(e.key.toLowerCase() === 'c') { copyPw(hoveredRow.dataset.pw); e.preventDefault(); }
else if(e.key.toLowerCase() === 'b') { navigator.clipboard.writeText(hoveredRow.dataset.usr); showToast('Username copied!'); e.preventDefault(); }
}
});
</script>

View File

@@ -1,48 +1,76 @@
<?php
$parent_id = $_GET['folder'] ?? null;
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_folder'])) {
$stmt = $pdo->prepare("INSERT INTO projects (name, is_folder, parent_id, owner_id) VALUES (?, 1, ?, ?)");
$stmt->execute([$_POST['name'], $parent_id, $user_id]);
notify_user($user_id, "New folder created: {$_POST['name']}", ['action'=>'Created', 'module'=>'Folder', 'item'=>$_POST['name']]);
}
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_item'])) {
$item = query("SELECT name FROM projects WHERE id=?", [$_POST['item_id']])->fetch();
$ctx = ['action'=>'Deleted', 'module'=>'File/Folder', 'item'=>$item['name']??'Item'];
// Notify shared recipients before deletion
$shares = query("SELECT share_type, share_id FROM project_shares WHERE project_id=?", [$_POST['item_id']])->fetchAll();
foreach($shares as $sh) {
if($sh['share_type'] === 'user') notify_user($sh['share_id'], "Shared item '{$item['name']}' deleted.", $ctx);
else notify_group($sh['share_id'], "Shared group item '{$item['name']}' deleted.", $ctx);
}
$stmt = $pdo->prepare("DELETE FROM projects WHERE id=? AND owner_id=?");
$stmt->execute([$_POST['item_id'], $user_id]);
notify_user($user_id, "Item deleted: " . ($item['name']??'Item'), $ctx);
}
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_item'])) {
$stmt = $pdo->prepare("UPDATE projects SET name=? WHERE id=? AND owner_id=?");
$stmt->execute([$_POST['new_name'], $_POST['item_id'], $user_id]);
$ctx = ['action'=>'Renamed', 'module'=>'File/Folder', 'item'=>$_POST['new_name']];
notify_user($user_id, "Item renamed to '{$_POST['new_name']}'", $ctx);
// Notify shared
$shares = query("SELECT share_type, share_id FROM project_shares WHERE project_id=?", [$_POST['item_id']])->fetchAll();
foreach($shares as $sh) {
if($sh['share_type'] === 'user') notify_user($sh['share_id'], "Shared item renamed to '{$_POST['new_name']}'", $ctx);
else notify_group($sh['share_id'], "Shared group item renamed to '{$_POST['new_name']}'", $ctx);
}
}
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_file']) && isset($_FILES['file'])) {
$name = $_FILES['file']['name'];
$tmp_name = $_FILES['file']['tmp_name'];
$size = $_FILES['file']['size'];
$path = 'uploads/' . time() . '_' . $name;
move_uploaded_file($tmp_name, $path);
$stmt = $pdo->prepare("INSERT INTO projects (name, is_folder, parent_id, file_path, owner_id) VALUES (?, 0, ?, ?, ?)");
$stmt->execute([$name, $parent_id, $path, $user_id]);
echo "OK"; exit; // For AJAX
notify_user($user_id, "File uploaded: $name", ['action'=>'Uploaded', 'module'=>'File', 'item'=>$name]);
echo "OK"; exit;
}
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['share_project'])) {
$pr_id = $_POST['project_id'];
$share = $_POST['share_target']; // 'user_1'
$parts = explode('_', $share);
$share = $_POST['share_target'];
$parts = explode('_', $share, 2);
if(count($parts)===2) {
$stmt = $pdo->prepare("INSERT INTO project_shares (project_id, share_type, share_id) VALUES (?, ?, ?)");
$stmt->execute([$pr_id, $parts[0], $parts[1]]);
$pr = query("SELECT name FROM projects WHERE id=?", [$pr_id])->fetch();
$msg = "A project/file '{$pr['name']}' has been shared with you.";
if($parts[0] === 'user') notify_user($parts[1], $msg);
else notify_group($parts[1], $msg);
$ctx = ['action'=>'Shared', 'module'=>'File/Folder', 'item'=>$pr['name'], 'user'=>$_SESSION['username']??'System'];
if($parts[0] === 'user') notify_user($parts[1], $msg, $ctx);
else notify_group($parts[1], $msg, $ctx);
}
}
// Fetch items in current folder
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['remove_project_share'])) {
$share_id = (int)$_POST['share_id'];
$chk = query("SELECT ps.id FROM project_shares ps JOIN projects p ON ps.project_id=p.id WHERE ps.id=? AND p.owner_id=?", [$share_id, $user_id])->fetch();
if($chk) {
$pdo->prepare("DELETE FROM project_shares WHERE id=?")->execute([$share_id]);
}
}
// ── Fetch current folder content ──────────────────────────────────────────────
$user_groups = get_user_groups($user_id);
$my_group_ids = array_column($user_groups, 'id');
$group_in = implode(',', array_fill(0, count($my_group_ids), '?')) ?: '0';
@@ -67,80 +95,219 @@ $items = $stmt->fetchAll();
$all_users = query("SELECT id, username FROM users WHERE id != ?", [$user_id])->fetchAll();
$all_groups = query("SELECT * FROM groups")->fetchAll();
// ── Build breadcrumb path ─────────────────────────────────────────────────────
$breadcrumbs = [];
$cur_id = $parent_id;
while($cur_id) {
$node = query("SELECT id, name, parent_id FROM projects WHERE id=?", [$cur_id])->fetch();
if(!$node) break;
array_unshift($breadcrumbs, $node);
$cur_id = $node['parent_id'];
}
// ── Helper: file size ─────────────────────────────────────────────────────────
function fmt_size($bytes) {
if(!$bytes) return '—';
if($bytes < 1024) return $bytes . ' B';
if($bytes < 1048576) return round($bytes/1024,1) . ' KB';
return round($bytes/1048576,1) . ' MB';
}
function get_file_icon($name, $is_folder) {
if($is_folder) return '📁';
$ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
$map = [
'pdf'=>'📄','doc'=>'📝','docx'=>'📝','xls'=>'📊','xlsx'=>'📊','ppt'=>'📑','pptx'=>'📑',
'jpg'=>'🖼','jpeg'=>'🖼','png'=>'🖼','gif'=>'🖼','webp'=>'🖼','svg'=>'🖼',
'mp4'=>'🎬','avi'=>'🎬','mov'=>'🎬','mp3'=>'🎵','wav'=>'🎵',
'zip'=>'🗜','rar'=>'🗜','7z'=>'🗜','tar'=>'🗜',
'php'=>'⚙','js'=>'⚙','css'=>'🎨','html'=>'🌐','txt'=>'📃','md'=>'📃',
'sh'=>'💻','py'=>'🐍',
];
return $map[$ext] ?? '📄';
}
?>
<div class="header">
<h1>Project Files Explorer</h1>
</div>
<div class="flex-between">
<?php if($parent_id):
$parent = query("SELECT parent_id FROM projects WHERE id=?", [$parent_id])->fetch();
?>
<a href="?action=projects&folder=<?= $parent['parent_id'] ?>" class="btn btn-secondary">← Back</a>
<?php else: ?>
<div>Root Directory</div>
<?php endif; ?>
<div style="display:flex; gap:1rem;">
<form method="POST" style="display:flex; gap:0.5rem;">
<input type="text" name="name" class="form-control" placeholder="New Folder Name" required>
<button type="submit" name="create_folder" class="btn">New Folder</button>
</form>
</div>
</div>
<div class="card" style="margin-top:1.5rem;">
<!-- Drag Drop Zone -->
<div id="dropzone" class="dropzone" ondragover="this.classList.add('dragover'); return false;" ondragleave="this.classList.remove('dragover');" ondrop="handleDrop(event)">
SVG Drop files here to upload instantly
<br><br><span style="color:var(--text-light); font-size:0.875rem;">(HTML5 Drag & Drop)</span>
</div>
<div style="margin-top:2rem;">
<?php foreach($items as $item): ?>
<div class="project-item">
<div style="display:flex; align-items:center; gap:0.5rem; flex:1;">
<span style="font-size:1.5rem;"><?= $item['is_folder'] ? '📁' : '📄' ?></span>
<?php if($item['is_folder']): ?>
<a href="?action=projects&folder=<?= $item['id'] ?>" style="font-weight:600;"><?= htmlspecialchars($item['name']) ?></a>
<?php else: ?>
<a href="<?= htmlspecialchars($item['file_path']) ?>" target="_blank"><?= htmlspecialchars($item['name']) ?></a>
<?php endif; ?>
</div>
<div style="width:200px; color:var(--text-light); font-size:0.875rem;">
Owner: <?= htmlspecialchars($item['owner_name']) ?>
<?= !$item['is_mine'] ? '<span class="badge" style="background:#10B981; font-size:10px;">Shared</span>' : '' ?>
</div>
<div style="display:flex; gap:0.5rem;">
<?php if($item['is_mine']): ?>
<form method="POST" style="display:inline; display:flex; gap:0.5rem;">
<input type="hidden" name="project_id" value="<?= $item['id'] ?>">
<select name="share_target" class="form-control" style="width:auto; padding:0.25rem;">
<?php foreach($all_users as $u): ?><option value="user_<?= $u['id'] ?>">User: <?= htmlspecialchars($u['username']) ?></option><?php endforeach; ?>
<?php foreach($all_groups as $g): ?><option value="group_<?= $g['id'] ?>">Group: <?= htmlspecialchars($g['name']) ?></option><?php endforeach; ?>
</select>
<button type="submit" name="share_project" class="btn btn-sm" title="Share">🔗</button>
</form>
<form method="POST" style="display:inline; display:flex; gap:0.5rem;" onsubmit="return confirm('Delete this item?')">
<input type="hidden" name="item_id" value="<?= $item['id'] ?>">
<button type="button" class="btn btn-sm btn-secondary" title="Rename" onclick="renameItem(<?= $item['id'] ?>, '<?= htmlspecialchars(addslashes($item['name'])) ?>')">✏️</button>
<button type="submit" name="delete_item" class="btn btn-sm btn-danger" title="Delete">🗑️</button>
</form>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
<?php if(!$items): ?><p style="margin-top:1rem;">Empty folder.</p><?php endif; ?>
</div>
</div>
<!-- Rename form hidden -->
<!-- Rename form -->
<form method="POST" id="rename-form" style="display:none;">
<input type="hidden" name="edit_item" value="1">
<input type="hidden" name="item_id" id="rn-item_id">
<input type="hidden" name="new_name" id="rn-new_name">
</form>
<!-- Share Modal -->
<div class="modal-overlay" id="share-modal">
<div class="modal-content" style="max-width:400px;">
<h3 style="margin-bottom:1rem; font-size:1.05rem;"><i class="fa fa-share-nodes"></i> Share Item</h3>
<form method="POST" id="share-form">
<input type="hidden" name="share_project" value="1">
<input type="hidden" name="project_id" id="share-project-id">
<div class="form-group">
<label>Share with</label>
<select name="share_target" class="form-control">
<?php foreach($all_users as $u): ?>
<option value="user_<?= $u['id'] ?>">👤 <?= htmlspecialchars($u['username']) ?></option>
<?php endforeach; ?>
<?php foreach($all_groups as $g): ?>
<option value="group_<?= $g['id'] ?>">👥 <?= htmlspecialchars($g['name']) ?></option>
<?php endforeach; ?>
</select>
</div>
<div style="display:flex; gap:0.5rem; justify-content:flex-end; margin-top:1rem;">
<button type="button" class="btn btn-secondary" onclick="document.getElementById('share-modal').classList.remove('active')">Cancel</button>
<button type="submit" class="btn"><i class="fa fa-share-nodes"></i> Share</button>
</div>
</form>
</div>
</div>
<!-- Delete form -->
<form method="POST" id="delete-item-form" style="display:none;">
<input type="hidden" name="delete_item" value="1">
<input type="hidden" name="item_id" id="delete-item-id">
</form>
<form method="POST" id="remove-share-form" style="display:none;">
<input type="hidden" name="remove_project_share" value="1">
<input type="hidden" name="share_id" id="remove-share-id">
</form>
<!-- Hidden folder create form -->
<form method="POST" id="new-folder-form" style="display:none;">
<input type="hidden" name="create_folder" value="1">
<input type="hidden" name="name" id="new-folder-name">
</form>
<!-- Explorer Toolbar / Breadcrumb -->
<div class="explorer-toolbar" style="margin-bottom:0.75rem;">
<a href="?action=projects" class="btn btn-secondary btn-sm" title="Home">
<i class="fa fa-house"></i>
</a>
<a href="javascript:history.back()" class="btn btn-secondary btn-sm" title="Back">
<i class="fa fa-arrow-left"></i>
</a>
<div class="explorer-path">
<a class="explorer-path-part <?= !$parent_id?'current':'' ?>" href="?action=projects">Root</a>
<?php foreach($breadcrumbs as $bc): ?>
<span class="explorer-path-sep">›</span>
<a class="explorer-path-part <?= $bc['id']==$parent_id?'current':'' ?>" href="?action=projects&folder=<?= $bc['id'] ?>">
<?= htmlspecialchars($bc['name']) ?>
</a>
<?php endforeach; ?>
</div>
<input type="text" id="explorer-search" placeholder="Search..." class="form-control" style="width:180px; padding:0.4rem 0.6rem; font-size:0.85rem;" oninput="filterExplorer(this.value)">
<label class="btn btn-secondary btn-sm" style="cursor:pointer;">
<i class="fa fa-arrow-up-from-bracket"></i> Upload File
<input type="file" id="file-upload-input" style="display:none;" onchange="handleFileSelect(this)">
</label>
<button class="btn btn-sm" onclick="showNewFolderDialog()"><i class="fa fa-folder-plus"></i> New Folder</button>
</div>
<div id="drag-upload-overlay" style="position:fixed; inset:0; z-index:1200; display:none; align-items:center; justify-content:center; pointer-events:none; background:rgba(15,23,42,0.45); backdrop-filter:blur(2px);">
<div style="background:var(--surface); border:2px dashed var(--primary); border-radius:1rem; padding:2rem 2.5rem; color:var(--text); text-align:center; box-shadow:0 12px 30px rgba(0,0,0,0.2);">
<i class="fa fa-cloud-arrow-up" style="font-size:2rem; margin-bottom:0.6rem; display:block; color:var(--primary);"></i>
<div style="font-weight:700; margin-bottom:0.2rem;">Drop files to upload</div>
<div style="font-size:0.84rem; color:var(--text-light);">Release your file anywhere on this page</div>
</div>
</div>
<!-- Detail Table -->
<div class="card" style="padding:0; overflow:hidden; min-height:calc(100vh - 190px);">
<table class="explorer-table" id="explorer-table">
<thead>
<tr>
<th style="width:30px;"><input type="checkbox" id="explorer-select-all" onclick="explorerSelectAll(this)"></th>
<th onclick="sortExplorer('name')" style="min-width:200px;">
<i class="fa fa-sort" style="font-size:0.7rem; margin-right:4px;"></i>Name
</th>
<th onclick="sortExplorer('type')" style="width:80px;">Type</th>
<th onclick="sortExplorer('owner')" style="width:120px;">Owner</th>
<th onclick="sortExplorer('size')" style="width:80px;">Size</th>
<th style="width:140px;">Shared</th>
<th style="width:160px; text-align:right;">Actions</th>
</tr>
</thead>
<tbody id="explorer-tbody">
<?php if(empty($items)): ?>
<tr><td colspan="7" style="text-align:center; padding:3rem; color:var(--text-light);">
<i class="fa fa-folder-open" style="font-size:2rem; display:block; margin-bottom:0.5rem;"></i>
This folder is empty.
</td></tr>
<?php endif; ?>
<?php foreach($items as $item):
$ext = $item['is_folder'] ? 'folder' : strtoupper(pathinfo($item['name'], PATHINFO_EXTENSION) ?: 'File');
$size = (!$item['is_folder'] && $item['file_path'] && file_exists($item['file_path'])) ? filesize($item['file_path']) : null;
$icon = get_file_icon($item['name'], $item['is_folder']);
?>
<tr class="explorer-row" data-name="<?= htmlspecialchars($item['name']) ?>" data-type="<?= $item['is_folder']?'folder':'file' ?>">
<td><input type="checkbox" class="explorer-check" value="<?= $item['id'] ?>"></td>
<td>
<div class="explorer-name">
<span class="explorer-icon"><?= $icon ?></span>
<?php if($item['is_folder']): ?>
<a href="?action=projects&folder=<?= $item['id'] ?>"><?= htmlspecialchars($item['name']) ?></a>
<?php else: ?>
<a href="<?= htmlspecialchars($item['file_path']) ?>" target="_blank"><?= htmlspecialchars($item['name']) ?></a>
<?php endif; ?>
</div>
</td>
<td style="color:var(--text-light); font-size:0.8rem;"><?= htmlspecialchars($ext) ?></td>
<td style="font-size:0.8rem;">
<?= htmlspecialchars($item['owner_name']) ?>
<?php if(!$item['is_mine']): ?><span class="badge" style="font-size:0.6rem; padding:1px 5px; margin-left:2px;">Shared</span><?php endif; ?>
</td>
<td style="color:var(--text-light); font-size:0.8rem;"><?= $size !== null ? fmt_size($size) : '—' ?></td>
<td style="font-size:0.8rem; color:var(--text-light);">
<?php
// Show shares
$shares = query("SELECT ps.id, ps.share_type, ps.share_id, u.username, u.profile_pic as upic, g.name as gname, g.profile_pic as gpic FROM project_shares ps LEFT JOIN users u ON (ps.share_type='user' AND ps.share_id=u.id) LEFT JOIN groups g ON (ps.share_type='group' AND ps.share_id=g.id) WHERE ps.project_id=?", [$item['id']])->fetchAll();
foreach($shares as $sh) {
$pic = ($sh['share_type'] === 'user' ? ($sh['upic']??'') : ($sh['gpic']??''));
$name = ($sh['share_type'] === 'user' ? ($sh['username']??'User') : ($sh['gname']??'Group'));
$init = strtoupper(mb_substr($name, 0, 1));
echo '<span style="font-size:0.72rem; background:rgba(var(--primary-rgb),0.1); color:var(--primary); padding:1px 5px 1px 1px; border-radius:12px; margin:1px; display:inline-flex; align-items:center; gap:3px; border:1px solid rgba(var(--primary-rgb),0.15);">';
if($pic && file_exists($pic)) {
echo '<img src="'.htmlspecialchars($pic).'" style="width:16px; height:16px; border-radius:50%; object-fit:cover;">';
} else {
echo '<div style="width:16px; height:16px; border-radius:50%; background:var(--primary); color:white; display:flex; align-items:center; justify-content:center; font-size:0.55rem; font-weight:700;">'.$init.'</div>';
}
echo '<span>'.htmlspecialchars($name).'</span>';
if($item['is_mine']) {
echo '<button type="button" style="border:none;background:transparent;color:inherit;cursor:pointer;line-height:1;margin-left:2px;font-size:0.8rem;" title="Unshare" onclick="removeProjectShare('.$sh['id'].')">×</button>';
}
echo '</span>';
}
if(!$shares) echo '<span style="color:var(--text-light); font-size:0.8rem;">—</span>';
?>
</td>
<td>
<div class="explorer-actions" style="justify-content:flex-end;">
<?php if($item['is_mine']): ?>
<button class="btn btn-sm btn-secondary" onclick="openShare(<?= $item['id'] ?>)" title="Share"><i class="fa fa-share-nodes"></i></button>
<button class="btn btn-sm btn-secondary" onclick="renameItem(<?= $item['id'] ?>, '<?= htmlspecialchars(addslashes($item['name'])) ?>')" title="Rename"><i class="fa fa-pen"></i></button>
<button class="btn btn-sm btn-danger" onclick="deleteItem(<?= $item['id'] ?>, '<?= htmlspecialchars(addslashes($item['name'])) ?>')" title="Delete"><i class="fa fa-trash"></i></button>
<?php else: ?>
<span style="font-size:0.75rem; color:var(--text-light); padding:0 0.5rem;">View only</span>
<?php endif; ?>
</div>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<!-- Status Bar -->
<div class="explorer-status-bar">
<span id="explorer-count"><?= count($items) ?> item<?= count($items)!=1?'s':'' ?></span>
<span id="explorer-selected-count" style="display:none; color:var(--primary); font-weight:600;"></span>
<span style="margin-left:auto;">
<?= $parent_id ? 'Folder: '.htmlspecialchars(end($breadcrumbs)['name'] ?? '') : 'Root directory' ?>
</span>
</div>
<script>
function renameItem(id, currName) {
let nn = prompt("Enter new name:", currName);
@@ -151,24 +318,132 @@ function renameItem(id, currName) {
}
}
function handleDrop(e) {
e.preventDefault();
e.currentTarget.classList.remove('dragover');
let dt = e.dataTransfer;
let files = dt.files;
if(files.length > 0) {
let formData = new FormData();
formData.append('upload_file', '1');
formData.append('file', files[0]);
fetch('?action=projects&folder=<?= $parent_id ?>', {
method: 'POST',
body: formData
}).then(res => {
window.location.reload();
function deleteItem(id, name) {
appConfirm(`Delete "${name}"? This cannot be undone.`).then(y => {
if(y) {
document.getElementById('delete-item-id').value = id;
document.getElementById('delete-item-form').submit();
}
});
}
function openShare(id) {
document.getElementById('share-project-id').value = id;
document.getElementById('share-modal').classList.add('active');
}
function removeProjectShare(shareId) {
appConfirm('Unshare this item?').then(y => {
if(y) {
document.getElementById('remove-share-id').value = shareId;
document.getElementById('remove-share-form').submit();
}
});
}
function showNewFolderDialog() {
const name = prompt('New folder name:');
if(name && name.trim()) {
document.getElementById('new-folder-name').value = name.trim();
document.getElementById('new-folder-form').submit();
}
}
function handleFileSelect(input) {
if(input.files.length > 0) uploadFile(input.files[0]);
}
function handleDrop(e) {
e.preventDefault();
hideDragOverlay();
if(e.dataTransfer.files.length > 0) uploadFile(e.dataTransfer.files[0]);
}
function uploadFile(file) {
showToast('Uploading ' + file.name + '...');
let formData = new FormData();
formData.append('upload_file', '1');
formData.append('file', file);
fetch('?action=projects&folder=<?= $parent_id ?>', { method: 'POST', body: formData })
.then(() => window.location.reload());
}
let dragCounter = 0;
const dragOverlay = document.getElementById('drag-upload-overlay');
function showDragOverlay() {
if(dragOverlay) dragOverlay.style.display = 'flex';
}
function hideDragOverlay() {
if(dragOverlay) dragOverlay.style.display = 'none';
}
document.addEventListener('dragenter', (e) => {
if(!e.dataTransfer || !Array.from(e.dataTransfer.types || []).includes('Files')) return;
dragCounter++;
showDragOverlay();
});
document.addEventListener('dragover', (e) => {
if(!e.dataTransfer || !Array.from(e.dataTransfer.types || []).includes('Files')) return;
e.preventDefault();
});
document.addEventListener('dragleave', (e) => {
if(!e.dataTransfer || !Array.from(e.dataTransfer.types || []).includes('Files')) return;
dragCounter = Math.max(0, dragCounter - 1);
if(dragCounter === 0) hideDragOverlay();
});
document.addEventListener('drop', (e) => {
if(!e.dataTransfer || !Array.from(e.dataTransfer.types || []).includes('Files')) return;
e.preventDefault();
dragCounter = 0;
handleDrop(e);
});
// ── Select all ────────────────────────────────────────────────────────────────
function explorerSelectAll(chk) {
document.querySelectorAll('.explorer-check').forEach(c => c.checked = chk.checked);
updateSelectedCount();
}
document.querySelectorAll('.explorer-check').forEach(c => c.addEventListener('change', updateSelectedCount));
function updateSelectedCount() {
const n = document.querySelectorAll('.explorer-check:checked').length;
const el = document.getElementById('explorer-selected-count');
if(n > 0) {
el.textContent = n + ' selected';
el.style.display = 'inline';
} else {
el.style.display = 'none';
}
}
// ── Search filter ─────────────────────────────────────────────────────────────
function filterExplorer(q) {
q = q.toLowerCase();
let visible = 0;
document.querySelectorAll('#explorer-tbody tr.explorer-row').forEach(row => {
const name = row.dataset.name || '';
if(name.toLowerCase().includes(q)) { row.style.display = ''; visible++; }
else row.style.display = 'none';
});
document.getElementById('explorer-count').textContent = visible + ' item' + (visible!==1?'s':'');
}
// ── Sort ──────────────────────────────────────────────────────────────────────
let sortDir = {};
function sortExplorer(col) {
sortDir[col] = !sortDir[col];
const tbody = document.getElementById('explorer-tbody');
const rows = Array.from(tbody.querySelectorAll('tr.explorer-row'));
rows.sort((a, b) => {
let av = '', bv = '';
if(col==='name') { av=a.dataset.name||''; bv=b.dataset.name||''; }
if(col==='type') { av=a.dataset.type||''; bv=b.dataset.type||''; }
// folders first for type sort
if(col==='type' && av===bv) return 0;
const cmp = av.localeCompare(bv);
return sortDir[col] ? cmp : -cmp;
});
// Folders always first
const folders = rows.filter(r => r.dataset.type==='folder');
const files = rows.filter(r => r.dataset.type!=='folder');
[...folders,...files].forEach(r => tbody.appendChild(r));
}
</script>

View File

@@ -3,7 +3,8 @@
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN assignor_type TEXT DEFAULT 'user'"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN assignor_group_id INTEGER"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN status_updated_at DATETIME"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN due_date DATE"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN due_date DATETIME"); } catch(Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN tags TEXT DEFAULT NULL"); } catch(Exception $e) {}
try { $pdo->exec("CREATE TABLE IF NOT EXISTS task_attachments (id INTEGER PRIMARY KEY AUTOINCREMENT, task_id INTEGER, file_name TEXT, file_path TEXT, owner_id INTEGER, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)"); } catch(Exception $e) {}
try {
$pdo->exec("CREATE TABLE IF NOT EXISTS system_config (k TEXT PRIMARY KEY, v TEXT)");
@@ -37,7 +38,16 @@ if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_task'])) {
}
if($can_delete) {
$task_to_del = query("SELECT title, assignee_type, assignee_id FROM tasks WHERE id=?", [$del_id])->fetch();
query("DELETE FROM tasks WHERE id=?", [$del_id]);
if($task_to_del) {
$ctx = ['action' => 'Deleted', 'module' => 'Task', 'item' => $task_to_del['title']];
if($task_to_del['assignee_type'] === 'user' && $task_to_del['assignee_id']) {
notify_user($task_to_del['assignee_id'], "Task '{$task_to_del['title']}' has been deleted.", $ctx);
} elseif($task_to_del['assignee_type'] === 'group' && $task_to_del['assignee_id']) {
notify_group($task_to_del['assignee_id'], "Group task '{$task_to_del['title']}' has been deleted.", $ctx);
}
}
}
}
@@ -117,8 +127,9 @@ if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_task'])) {
}
}
$stmt = $pdo->prepare("INSERT INTO tasks (title, description, assignor_id, assignor_type, assignor_group_id, assignee_type, assignee_id, custom_assignee_name, status_updated_at, due_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?)");
if(!$stmt->execute([$title, $desc, $user_id, $assignor_type, $assignor_group_id, $a_type, $a_id, $custom_name, $due_date])) {
$tags = trim($_POST['tags'] ?? '');
$stmt = $pdo->prepare("INSERT INTO tasks (title, description, assignor_id, assignor_type, assignor_group_id, assignee_type, assignee_id, custom_assignee_name, status_updated_at, due_date, tags) VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, ?, ?)");
if(!$stmt->execute([$title, $desc, $user_id, $assignor_type, $assignor_group_id, $a_type, $a_id, $custom_name, $due_date, $tags])) {
if(isset($_POST['ajax_submit'])) { echo json_encode(['success'=>false, 'error'=>'Task insert failed']); exit; }
}
$new_task_id = $pdo->lastInsertId();
@@ -144,12 +155,13 @@ if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_task'])) {
}
// Handle notifications
$ctx = ['action' => 'Created', 'module' => 'Task', 'item' => $title, 'assignor' => $current_user['username'] ?? 'System', 'due_date' => $due_date ?: 'None'];
foreach($to_list as $rec) {
$u = query("SELECT id FROM users WHERE username=?", [$rec])->fetch();
if($u) notify_user($u['id'], "You have been assigned a new task: $title");
if($u) notify_user($u['id'], "You have been assigned a new task: $title", $ctx);
else {
$g = query("SELECT id FROM groups WHERE name=?", [$rec])->fetch();
if($g) notify_group($g['id'], "Your group has been assigned a new task: $title");
if($g) notify_group($g['id'], "Your group has been assigned a new task: $title", $ctx);
}
}
@@ -176,18 +188,43 @@ $all_g = query("SELECT id, name FROM groups")->fetchAll();
$group_in = implode(',', array_fill(0, count($my_group_ids), '?')) ?: '0';
$params = array_merge([$user_id], $my_group_ids, $my_group_ids, [$user_id]);
$custom_tokens = [];
if(!empty($current_user['username'])) $custom_tokens[] = (string)$current_user['username'];
foreach($user_groups as $g) {
if(!empty($g['name'])) $custom_tokens[] = (string)$g['name'];
}
$custom_tokens = array_values(array_unique(array_filter(array_map('trim', $custom_tokens), fn($v) => $v !== '')));
$sql = "SELECT t.*, u.username as assignor_user_name, g.name as assignor_group_name, au.username as assignee_user_name, ag.name as assignee_group_name
$custom_in = implode(',', array_fill(0, count($custom_tokens), '?')) ?: '0';
$custom_like = $custom_tokens ? implode(' OR ', array_fill(0, count($custom_tokens), "(','||lower(replace(t.custom_assignee_name,' ',''))||',') LIKE ('%,'||lower(replace(?,' ',''))||',%')")) : '0';
$params = array_merge([$user_id], $my_group_ids, $my_group_ids, [$user_id], $custom_tokens, $custom_tokens);
$sql = "SELECT t.*,
u.username as assignor_user_name, u.profile_pic as assignor_user_pic,
g.name as assignor_group_name, g.profile_pic as assignor_group_pic,
au.username as assignee_user_name, au.profile_pic as assignee_user_pic,
ag.name as assignee_group_name, ag.profile_pic as assignee_group_pic,
cu.username as completed_by_username, aru.username as archived_by_username
FROM tasks t
LEFT JOIN users u ON t.assignor_id = u.id
LEFT JOIN groups g ON t.assignor_group_id = g.id
LEFT JOIN users au ON (t.assignee_type='user' AND t.assignee_id = au.id)
LEFT JOIN groups ag ON (t.assignee_type='group' AND t.assignee_id = ag.id)
LEFT JOIN users cu ON t.completed_by = cu.id
LEFT JOIN users aru ON t.archived_by = aru.id
WHERE (t.assignee_type='user' AND t.assignee_id = ?)
OR (t.assignee_type='group' AND t.assignee_id IN ($group_in))
OR (t.assignor_type='group' AND t.assignor_group_id IN ($group_in))
OR (t.assignor_type='user' AND t.assignor_id = ?)
OR (
COALESCE(t.assignee_type,'custom')='custom'
AND t.custom_assignee_name IS NOT NULL
AND (
t.custom_assignee_name IN ($custom_in)
OR ($custom_like)
)
)
ORDER BY t.created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
@@ -195,6 +232,7 @@ $tasks = $stmt->fetchAll();
$t_ids = array_column($tasks, 'id');
$attachments = [];
$comments = [];
if($t_ids) {
$in = str_repeat('?,', count($t_ids) - 1) . '?';
$stmt = $pdo->prepare("SELECT ta.*, u.username as owner_name FROM task_attachments ta LEFT JOIN users u ON ta.owner_id = u.id WHERE ta.task_id IN ($in) ORDER BY ta.created_at ASC");
@@ -202,6 +240,47 @@ if($t_ids) {
foreach($stmt->fetchAll() as $row) {
$attachments[$row['task_id']][] = $row;
}
$stmt2 = $pdo->prepare("SELECT tc.*, cu.username as created_by_username FROM task_comments tc LEFT JOIN users cu ON tc.created_by = cu.id WHERE tc.task_id IN ($in) ORDER BY tc.created_at ASC");
$stmt2->execute($t_ids);
foreach($stmt2->fetchAll() as $row) {
$comments[$row['task_id']][] = $row;
}
}
// Pre-fetch profile pics for users
$all_usernames = [];
foreach($tasks as $t) {
if($t['assignee_type'] == 'user' || $t['assignee_type'] == 'custom') {
$names = array_filter(array_map('trim', explode(',', $t['assignee_user_name'] ?? $t['custom_assignee_name'] ?? '')));
foreach($names as $n) $all_usernames[] = $n;
}
if($t['assignor_type'] == 'user') $all_usernames[] = $t['assignor_user_name'];
}
$user_pics = [];
if($all_usernames) {
$all_usernames = array_unique($all_usernames);
$in_u = str_repeat('?,', count($all_usernames) - 1) . '?';
$stmt_u = $pdo->prepare("SELECT username, profile_pic FROM users WHERE username IN ($in_u)");
$stmt_u->execute(array_values($all_usernames));
foreach($stmt_u->fetchAll() as $row) {
$user_pics[$row['username']] = $row['profile_pic'];
}
}
// Pre-fetch group pics
$all_groupnames = [];
foreach($tasks as $t) {
if($t['assignee_type'] == 'group') $all_groupnames[] = $t['assignee_group_name'];
if($t['assignor_type'] == 'group') $all_groupnames[] = $t['assignor_group_name'];
}
if($all_groupnames) {
$all_groupnames = array_unique($all_groupnames);
$in_g = str_repeat('?,', count($all_groupnames) - 1) . '?';
$stmt_g = $pdo->prepare("SELECT name, profile_pic FROM groups WHERE name IN ($in_g)");
$stmt_g->execute(array_values($all_groupnames));
foreach($stmt_g->fetchAll() as $row) {
$user_pics[$row['name']] = $row['profile_pic'];
}
}
$kanban = ['pending' => [], 'in_progress' => [], 'completed' => [], 'archived' => []];
@@ -213,7 +292,7 @@ foreach($tasks as $t) {
usort($kanban['pending'], function($a, $b) {
$da = $a['due_date'] ? strtotime($a['due_date']) : PHP_INT_MAX;
$db = $b['due_date'] ? strtotime($b['due_date']) : PHP_INT_MAX;
if($da == $db) return strtotime($b['created_at']) - strtotime($a['created_at']);
if($da == $db) return strtotime($b['created_at'] . ' UTC') - strtotime($a['created_at'] . ' UTC');
return $da - $db;
});
?>
@@ -242,7 +321,7 @@ usort($kanban['pending'], function($a, $b) {
.kanban-task {
background: var(--surface); padding: 1rem; border-radius: 10px;
box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05), 0 2px 4px -1px rgba(0,0,0,0.03);
border: 1px solid rgba(0,0,0,0.05); cursor: grab; transition: transform 0.2s, box-shadow 0.2s;
border: 1px solid rgba(0,0,0,0.05); transition: transform 0.2s, box-shadow 0.2s, opacity 0.2s;
border-left: 4px solid var(--border);
}
body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-left: 4px solid var(--primary); }
@@ -253,8 +332,9 @@ body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-l
.kanban-task.expanded { box-shadow: 0 10px 15px -3px rgba(0,0,0,0.05); }
.kanban-task:hover:not(.expanded) { transform: translateY(-2px); box-shadow: 0 10px 15px -3px rgba(0,0,0,0.05); }
.kanban-task.dragging { opacity: 0.4; transform: scale(1.02); box-shadow: 0 20px 25px -5px rgba(0,0,0,0.1), 0 10px 10px -5px rgba(0,0,0,0.04); cursor: grabbing; z-index: 100; }
.kanban-task-header { cursor: pointer; display: flex; flex-direction: column; gap: 0.5rem; }
.kanban-task-header { cursor: grab; display: flex; flex-direction: column; gap: 0.5rem; }
.kanban-task-title {
font-weight: 700; font-size: 1.05rem; color: var(--text);
/* Clamp to 2 lines when collapsed */
@@ -272,7 +352,7 @@ body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-l
-webkit-line-clamp: unset;
}
.kanban-task-body {
display: none; padding-top: 0.75rem; margin-top: 0.5rem; border-top: 1px dashed var(--border);
display: none; padding-top: 0.75rem; margin-top: 0.5rem; border-top: 1px dashed var(--border); position: relative; padding-bottom: 2.5rem;
}
.kanban-task.expanded .kanban-task-body { display: block; }
.chevron { transition: transform 0.2s; font-size: 0.8rem; color: var(--text-light); }
@@ -288,6 +368,12 @@ body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-l
.role-from { background: rgba(var(--primary-rgb), 0.1); color: var(--primary); }
.role-to { background: rgba(16, 185, 129, 0.1); color: #10B981; }
.kanban-task:not(.expanded) .expanded-only { display: none !important; }
.kanban-task.expanded .avatar-collapsed-only { display: none !important; }
.kanban-task.expanded .expanded-only { display: inline-flex !important; }
/* Hide header metadata row when expanded to avoid duplication */
.kanban-task.expanded .kanban-task-header > div:last-child { display: none !important; }
/* Custom Autocomplete Dropdown */
.autocomplete-dropdown {
position: absolute; top: 100%; left: 0; right: 0; background: var(--surface);
@@ -377,7 +463,7 @@ body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-l
<span id="att-lightbox-title">Preview</span>
<button id="att-lightbox-close" onclick="closeAttachmentPreview()" title="Close">✕</button>
</div>
<div id="att-lightbox-body" id="att-lightbox-body"></div>
<div id="att-lightbox-body"></div>
</div>
</div>
@@ -405,11 +491,11 @@ body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-l
</div>
</div>
<div style="position:relative; width:30px; height:30px;" title="Due Date">
<div style="cursor:pointer; display:flex; align-items:center; justify-content:center; width:100%; height:100%; border-radius:50%; background:var(--surface); border:1px solid var(--border); color:var(--text-light); transition:background 0.2s; position:absolute; top:0; left:0; z-index:1; pointer-events:none;">
<div style="position:relative;" title="Due Date & Time">
<div id="due-icon-btn" style="cursor:pointer; display:flex; align-items:center; justify-content:center; width:30px; height:30px; border-radius:50%; background:var(--surface); border:1px solid var(--border); color:var(--text-light); transition:all 0.2s;" onclick="duePicker.open();">
<i class="fas fa-calendar-alt" style="font-size:0.85rem;"></i>
</div>
<input type="date" name="due_date" style="position:absolute; top:0; left:0; width:100%; height:100%; opacity:0; cursor:pointer; z-index:2;" title="Set Due Date" onchange="handleDueDateChange(this.value)">
<input type="text" name="due_date" id="due-picker-input" style="visibility:hidden; position:absolute; width:1px; height:1px;">
</div>
<label title="Attach Files" id="attach-icon-btn" style="cursor:pointer; display:flex; align-items:center; justify-content:center; width:30px; height:30px; border-radius:50%; background:var(--surface); border:1px solid var(--border); color:var(--text-light); transition:background 0.2s;">
@@ -417,6 +503,16 @@ body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-l
<input type="file" multiple style="display:none;" onchange="handleTaskFilesSelect(this)">
</label>
<div style="position:relative;" title="Tags">
<div id="tag-icon-btn" style="cursor:pointer; display:flex; align-items:center; justify-content:center; width:30px; height:30px; border-radius:50%; background:var(--surface); border:1px solid var(--border); color:var(--text-light); transition:background 0.2s;" onclick="document.getElementById('tags-dropdown-container').style.display='block';">
<i class="fas fa-tag" style="font-size:0.85rem;"></i>
</div>
<div id="tags-dropdown-container" style="display:none; position:absolute; top:35px; right:-20px; background:var(--surface); border:1px solid var(--border); border-radius:8px; padding:0.75rem; z-index:100; box-shadow:0 10px 15px -3px rgba(0,0,0,0.1); width:280px; align-items:stretch;">
<label style="font-size:0.75rem; font-weight:600; color:var(--text); margin-bottom:0.4rem; display:block; text-align:left;">Tags</label>
<input type="text" name="tags" class="form-control tagify-input" style="font-size:0.8rem; border:1px solid var(--border); border-radius:4px; padding:4px; max-width:100%;" placeholder="Add tags...">
</div>
</div>
<button type="button" class="btn" style="padding:0.3rem 1rem; border-radius:20px; font-weight:600; font-size:0.8rem;" onclick="submitCreateTaskForm()">Create</button>
<button type="submit" id="hidden-create-btn" name="create_task" style="display:none;"></button>
</div>
@@ -451,9 +547,9 @@ body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-l
</div>
<div class="kanban-tasks" id="col-<?= $col_id ?>">
<?php foreach($kanban[$col_id] as $t): ?>
<div class="kanban-task status-<?= $col_id ?>" draggable="true" ondragstart="drag(event, <?= $t['id'] ?>)" id="task-<?= $t['id'] ?>" data-due="<?= $t['due_date'] ? strtotime($t['due_date']) : PHP_INT_MAX ?>" data-created="<?= strtotime($t['created_at']) ?>">
<div class="kanban-task status-<?= $col_id ?>" id="task-<?= $t['id'] ?>" data-due="<?= $t['due_date'] ? strtotime($t['due_date']) : PHP_INT_MAX ?>" data-created="<?= strtotime($t['created_at'] . ' UTC') ?>">
<div class="kanban-task-header" onclick="toggleTaskExpand(this)">
<div class="kanban-task-header" draggable="true" ondragstart="drag(event, <?= $t['id'] ?>)" ondragend="dragEnd(event)" onclick="toggleTaskExpand(this)">
<div style="display:flex; justify-content:space-between; align-items:flex-start; width:100%; min-width:0; gap:0.5rem;">
<span class="kanban-task-title"><?= htmlspecialchars($t['title']) ?></span>
<div style="display:flex; align-items:center; gap:0.5rem; flex-shrink:0;">
@@ -476,25 +572,99 @@ body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-l
</div>
</div>
<div style="display:flex; justify-content:space-between; align-items:center; width:100%; font-size:0.75rem;">
<div style="display:flex; justify-content:space-between; align-items:center; width:100%; font-size:0.75rem; margin-top:0.5rem;">
<?php
echo '<span class="badge-role role-to" style="padding:2px 8px;">';
if($t['assignee_type'] == 'custom') echo '👤 '.htmlspecialchars((string)$t['custom_assignee_name']);
elseif($t['assignee_type'] == 'group') echo '👥 '.htmlspecialchars($t['assignee_group_name']);
else echo '👤 '.htmlspecialchars($t['assignee_user_name'] ?? '');
echo '</span>';
// Determine assignor info
$from_name = '';
if($t['assignor_type'] == 'group') $from_name = $t['assignor_group_name'];
else $from_name = $t['assignor_user_name'] ?? 'System';
$from_pic = ($t['assignor_type'] == 'user') ? ($user_pics[$from_name] ?? '') : '';
$from_initial = strtoupper(mb_substr($from_name, 0, 1));
$bg_colors = ['#4F46E5','#10B981','#F59E0B','#EF4444','#8B5CF6','#06B6D4','#EC4899','#84CC16'];
$from_bg = $bg_colors[crc32($from_name) % 8];
echo '<div style="display:flex; align-items:center; gap:0.5rem;">';
$to_names_raw = '';
if($t['assignee_type'] == 'custom') $to_names_raw = (string)$t['custom_assignee_name'];
elseif($t['assignee_type'] == 'group') $to_names_raw = htmlspecialchars($t['assignee_group_name']);
else $to_names_raw = htmlspecialchars($t['assignee_user_name'] ?? '');
$to_names = array_filter(array_map('trim', explode(',', $to_names_raw)));
$to_names_str = implode(', ', $to_names);
$assignment_title = "Task Assigned from {$from_name} to {$to_names_str}";
// Collapsed View: {assignor} => {assignee}
echo '<div class="avatar-collapsed-only" style="display:flex; align-items:center; gap:0.4rem;" title="'.htmlspecialchars($assignment_title).'">';
// From Avatar
if ($from_pic && file_exists($from_pic)) {
echo '<img src="'.htmlspecialchars($from_pic).'" style="width:24px; height:24px; border-radius:50%; object-fit:cover; border:2px solid var(--surface);">';
} else {
echo '<div style="width:24px; height:24px; border-radius:50%; background:'.$from_bg.'; color:white; display:flex; align-items:center; justify-content:center; font-weight:700; font-size:0.75rem; border:2px solid var(--surface);">'.$from_initial.'</div>';
}
// Arrow style separator
echo '<i class="fas fa-chevron-right" style="font-size:0.6rem; color:var(--text-light); opacity:0.6;"></i>';
// To Avatar(s) stack
echo '<div style="display:flex; align-items:center;">';
foreach($to_names as $idx => $name) {
$initial = strtoupper(mb_substr($name, 0, 1));
$col_idx = crc32($name) % 8;
$av_bg = $bg_colors[$col_idx];
$pic = $user_pics[$name] ?? '';
$margin = ($idx === 0) ? '0' : '-8px';
if ($pic && file_exists($pic)) {
echo '<img src="'.htmlspecialchars($pic).'" style="width:24px; height:24px; border-radius:50%; object-fit:cover; border:2px solid var(--surface); margin-left:'.$margin.'; z-index:'.(10 - $idx).';">';
} else {
echo '<div style="width:24px; height:24px; border-radius:50%; background:'.$av_bg.'; color:white; display:flex; align-items:center; justify-content:center; font-weight:700; font-size:0.75rem; border:2px solid var(--surface); margin-left:'.$margin.'; z-index:'.(10 - $idx).';">'.$initial.'</div>';
}
}
echo '</div>';
echo '</div>';
// Expanded View Badges
echo '<div class="expanded-only" style="display:flex; flex-wrap:wrap; gap:0.4rem;">';
foreach($to_names as $name) {
$initial = strtoupper(mb_substr($name, 0, 1));
$col_idx = crc32($name) % 8;
$av_bg = $bg_colors[$col_idx];
$pic = $user_pics[$name] ?? '';
echo '<span class="badge-role role-to" style="padding:2px 8px; align-items:center; gap:0.4rem; display:inline-flex;">';
if ($pic && file_exists($pic)) {
echo '<img src="'.htmlspecialchars($pic).'" style="width:18px; height:18px; border-radius:50%; object-fit:cover;">';
} else {
echo '<div style="width:18px; height:18px; border-radius:50%; background:'.$av_bg.'; color:white; display:flex; align-items:center; justify-content:center; font-weight:700; font-size:0.6rem;">'.$initial.'</div>';
}
echo '<span>'.htmlspecialchars($name).'</span>';
echo '</span>';
}
echo '</div>';
echo '<div style="display:flex; align-items:center; gap:0.5rem; margin-left:auto;">';
$tag_count = !empty($t['tags']) ? count(array_filter(array_map('trim', explode(',', $t['tags'])))) : 0;
if($tag_count > 0) {
echo '<span style="color:var(--text-light); font-weight:600; display:flex; align-items:center; gap:0.15rem;" title="'.$tag_count.' tag(s)"><i class="fas fa-tag" style="font-size:0.75rem;"></i> '.$tag_count.'</span>';
}
$att_count = empty($attachments[$t['id']]) ? 0 : count($attachments[$t['id']]);
if($att_count > 0) {
echo '<span style="color:var(--text-light); font-weight:600; display:flex; align-items:center; gap:0.15rem;" title="'.$att_count.' attachment(s)"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path></svg> '.$att_count.'</span>';
}
// We could show comments count too on collapsed state
$comment_count = empty($comments[$t['id']]) ? 0 : count($comments[$t['id']]);
if($comment_count > 0) {
echo '<span style="color:var(--text-light); font-weight:600; display:flex; align-items:center; gap:0.15rem;" title="'.$comment_count.' comment(s)"><i class="fas fa-comment-dots" style="font-size:0.75rem;"></i> '.$comment_count.'</span>';
}
if($t['due_date']) {
$days_diff = (int)round((strtotime($t['due_date']) - strtotime(date('Y-m-d'))) / 86400);
if($days_diff < 0) {
echo '<span class="badge" style="background:#EF4444; color:white; padding:2px 8px; border-radius:12px; font-weight:600;">Overdue by '.abs($days_diff).'d</span>';
echo '<span class="badge" style="background:#EF4444; color:white; padding:2px 8px; border-radius:12px; font-weight:600;">Overdue '.abs($days_diff).'d ago</span>';
} elseif($days_diff == 0) {
echo '<span class="badge" style="background:#F59E0B; color:white; padding:2px 8px; border-radius:12px; font-weight:600;">Due Today</span>';
} else {
@@ -511,38 +681,118 @@ body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-l
<div class="kanban-task-desc"><?= nl2br(htmlspecialchars((string)$t['description'])) ?></div>
<?php endif; ?>
<div style="font-size:0.75rem; color:var(--text-light); margin-bottom:0.75rem;">
<div>📅 Created: <?= date('M j, Y', strtotime($t['created_at'])) ?></div>
<div style="font-size:0.72rem; color:var(--text-light); margin-bottom:0.75rem; display:flex; justify-content:space-between; align-items:center;">
<div title="Created At"><i class="fas fa-calendar-plus" style="opacity:0.7; margin-right:4px;"></i> <?= date('M j, Y H:i', strtotime($t['created_at'] . ' UTC')) ?></div>
<?php if($t['due_date']): ?>
<div style="margin-top:2px;">⏰ Due Date: <strong style="color:#EF4444;"><?= date('M j, Y', strtotime($t['due_date'])) ?></strong></div>
<div title="Due Date"><i class="fas fa-clock" style="color:#EF4444; margin-right:4px;"></i> <strong style="color:#EF4444;"><?= date('M j, Y H:i', strtotime($t['due_date'])) ?></strong></div>
<?php endif; ?>
</div>
<div style="display:flex; flex-direction:column; gap:0.5rem;">
<div style="font-size:0.8rem; display:flex; justify-content:space-between; align-items:center;">
<span style="color:var(--text-light);">From:</span>
<span class="badge-role role-from">
<?php
if($t['assignor_type'] == 'group') echo '👥 '.htmlspecialchars($t['assignor_group_name']);
else echo '👤 '.htmlspecialchars($t['assignor_user_name'] ?? '');
// Calculate FROM and TO names
$from_name = '';
if($t['assignor_type'] == 'group') $from_name = $t['assignor_group_name'];
else $from_name = $t['assignor_user_name'] ?? 'System';
if (!function_exists('get_avatar_html_local')) {
function get_avatar_html_local($name, $profile_pic = '') {
if (!$name) return '';
if($profile_pic && file_exists($profile_pic)) {
return '<img src="'.htmlspecialchars($profile_pic).'" style="width:24px; height:24px; border-radius:50%; object-fit:cover; border:2px solid var(--surface); cursor:help;" title="'.htmlspecialchars($name).'">';
}
$initial = strtoupper(mb_substr($name, 0, 1));
$col_idx = crc32($name) % 8;
$bg_colors = ['#4F46E5','#10B981','#F59E0B','#EF4444','#8B5CF6','#06B6D4','#EC4899','#84CC16'];
$av_bg = $bg_colors[$col_idx];
return '<div style="width:24px; height:24px; border-radius:50%; background:'.$av_bg.'; color:white; display:flex; align-items:center; justify-content:center; font-weight:700; font-size:0.75rem; border:2px solid var(--surface); cursor:help;" title="'.htmlspecialchars($name).'">'.$initial.'</div>';
}
}
$from_profile_pic = $user_pics[$from_name] ?? '';
?>
<div style="font-size:0.8rem; display:flex; justify-content:space-between; align-items:center;">
<span style="color:var(--text-light);">Assignments:</span>
<div style="display:flex; align-items:center; gap:0.5rem;">
<div style="display:flex; align-items:center; gap:0.4rem;">
<span style="font-size:0.65rem; color:var(--text-light);">From</span>
<?= get_avatar_html_local($from_name, $from_profile_pic) ?>
</div>
<div style="color:var(--border);">|</div>
<div style="display:flex; align-items:center; gap:0.4rem; flex-wrap:wrap; justify-content:flex-end; max-width:200px;">
<span style="font-size:0.65rem; color:var(--text-light);">To</span>
<?php
foreach($to_names as $name) {
$p = $user_pics[$name] ?? '';
echo get_avatar_html_local($name, $p);
}
?>
</div>
</div>
</div>
<?php if($t['status'] === 'completed'): ?>
<div style="font-size:0.8rem; display:flex; justify-content:space-between; align-items:center;">
<span style="color:var(--text-light);">Completed by:</span>
<span style="color:#10B981; font-weight:600;">
<?= htmlspecialchars($t['completed_by_username'] ?? 'System') ?>
</span>
</div>
<?php endif; ?>
<?php if($t['status'] === 'archived'): ?>
<div style="font-size:0.8rem; display:flex; justify-content:space-between; align-items:center;">
<span style="color:var(--text-light);">To:</span>
<span class="badge-role role-to">
<?php
if($t['assignee_type'] == 'custom') echo '👤 '.htmlspecialchars((string)$t['custom_assignee_name']);
elseif($t['assignee_type'] == 'group') echo '👥 '.htmlspecialchars($t['assignee_group_name']);
else echo '👤 '.htmlspecialchars($t['assignee_user_name'] ?? '');
?>
<span style="color:var(--text-light);">Archived by:</span>
<span style="color:#6B7280; font-weight:600;">
<?= htmlspecialchars($t['archived_by_username'] ?? 'System (Auto)') ?>
</span>
</div>
<?php endif; ?>
</div>
<div style="margin-top:0.75rem; border-top:1px dashed var(--border); padding-top:0.75rem;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:0.5rem;">
<div style="font-size:0.75rem; font-weight:600; color:var(--text-light);">Attachments</div>
<div style="font-size:0.75rem; font-weight:600; color:var(--text-light); margin-bottom:0.5rem;">Comments</div>
<div style="display:flex; flex-direction:column; gap:0.5rem; margin-bottom:0.5rem;" id="comments-container-<?= $t['id'] ?>">
<?php if(!empty($comments[$t['id']])): ?>
<?php foreach($comments[$t['id']] as $cm):
$commenter_name = $cm['created_by_username'] ?? 'User';
$commenter_pic = $user_pics[$commenter_name] ?? '';
?>
<div style="display:flex; gap:0.4rem; align-items:flex-start;">
<?= get_avatar_html_local($commenter_name, $commenter_pic) ?>
<div style="background:var(--bg); border:1px solid var(--border); border-radius:12px; border-top-left-radius:0; padding:0.4rem 0.6rem; font-size:0.75rem; color:var(--text); flex:1;">
<div style="display:flex; justify-content:space-between; margin-bottom:0.2rem;">
<strong style="font-size:0.65rem; color:var(--primary);"><?= htmlspecialchars($cm['created_by_username'] ?? 'User') ?></strong>
<span style="font-size:0.6rem; color:var(--text-light);"><?= date('M j, Y H:i', strtotime($cm['created_at'] . ' UTC')) ?>
<?php if($cm['created_by'] == $user_id || !empty($_SESSION['is_admin'])): ?>
&nbsp;<i class="fas fa-trash" style="cursor:pointer; color:#EF4444;" onclick="deleteComment(<?= $cm['id'] ?>)"></i>
<?php endif; ?>
</span>
</div>
<?= nl2br(htmlspecialchars($cm['comment'])) ?>
</div>
</div>
<?php endforeach; ?>
<?php else: ?>
<div style="font-size:0.75rem; color:var(--text-light); font-style:italic;">No comments yet.</div>
<?php endif; ?>
</div>
<form method="POST" onsubmit="event.preventDefault(); addComment(<?= $t['id'] ?>, this);" style="display:flex; gap:0.4rem;">
<input type="text" name="comment" placeholder="Write a comment..." required style="flex:1; border:1px solid var(--border); background:var(--bg); color:var(--text); border-radius:20px; padding:0.4rem 0.75rem; font-size:0.75rem; min-width:0;">
<button type="submit" style="background:var(--primary); color:white; border:none; border-radius:20px; padding:0.4rem 0.8rem; font-size:0.75rem; cursor:pointer;" title="Send"><i class="fas fa-paper-plane"></i></button>
</form>
</div>
<div style="margin-top:0.75rem; border-top:1px dashed var(--border); padding-top:0.75rem;">
<div style="position:absolute; bottom:-0.25rem; right:-0.25rem; display:flex; align-items:center; gap:0.5rem; padding:0.5rem;">
<!-- Tag icon styled like attachment icon -->
<?php $task_tags = !empty($t['tags']) ? array_filter(array_map('trim', explode(',', $t['tags']))) : []; ?>
<button type="button" onclick="showAddTagPopup(<?= $t['id'] ?>, '<?= htmlspecialchars(implode(',', $task_tags), ENT_QUOTES) ?>')" style="cursor:pointer; display:flex; align-items:center; justify-content:center; width:22px; height:22px; border-radius:4px; background:var(--border); color:var(--text); border:none; transition:background 0.2s; position:relative;" title="Manage Tags">
<i class="fas fa-tag" style="font-size:0.6rem;"></i>
<?php if(!empty($task_tags)): ?>
<span style="position:absolute; top:-4px; right:-4px; background:#EF4444; color:white; border-radius:50%; width:12px; height:12px; font-size:0.5rem; display:flex; align-items:center; justify-content:center; font-weight:700; border:1px solid var(--surface);"><?= count($task_tags) ?></span>
<?php endif; ?>
</button>
<!-- Attachment icon -->
<label title="Attach files" style="cursor:pointer; display:flex; align-items:center; justify-content:center; width:22px; height:22px; border-radius:4px; background:var(--border); color:var(--text); transition:background 0.2s;">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path></svg>
<input type="file" multiple style="display:none;" onchange="uploadFilesAjax(<?= $t['id'] ?>, this.files)">
@@ -590,7 +840,13 @@ body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-l
</form>
<?php endif; ?>
<div title="Uploaded by <?= htmlspecialchars((string)$att['owner_name']) ?>" style="position:absolute; top:2px; left:2px; width:16px; height:16px; border-radius:50%; background:var(--primary); color:white; display:flex; align-items:center; justify-content:center; font-size:0.5rem; font-weight:700; z-index:10; box-shadow:0 1px 2px rgba(0,0,0,0.3);"><?= $initial ?></div>
<?php
$att_owner_pic = $user_pics[$att['owner_name']] ?? '';
if($att_owner_pic && file_exists($att_owner_pic)): ?>
<img src="<?= htmlspecialchars($att_owner_pic) ?>" title="Uploaded by <?= htmlspecialchars((string)$att['owner_name']) ?>" style="position:absolute; top:2px; left:2px; width:16px; height:16px; border-radius:50%; object-fit:cover; z-index:10; box-shadow:0 1px 2px rgba(0,0,0,0.3); border:1px solid rgba(255,255,255,0.2);">
<?php else: ?>
<div title="Uploaded by <?= htmlspecialchars((string)$att['owner_name']) ?>" style="position:absolute; top:2px; left:2px; width:16px; height:16px; border-radius:50%; background:var(--primary); color:white; display:flex; align-items:center; justify-content:center; font-size:0.5rem; font-weight:700; z-index:10; box-shadow:0 1px 2px rgba(0,0,0,0.3); border:1px solid rgba(255,255,255,0.2);"><?= $initial ?></div>
<?php endif; ?>
<a href="<?= htmlspecialchars((string)$att['file_path']) ?>" target="_blank" style="background:rgba(0,0,0,0.6); color:white; font-size:0.5rem; padding:2px 3px; text-decoration:none; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; position:absolute; bottom:0; left:0; right:0; text-align:center;" title="<?= htmlspecialchars((string)$att['file_name']) ?>"><?= htmlspecialchars((string)$att['file_name']) ?></a>
</div>
@@ -599,6 +855,8 @@ body.dark-mode .kanban-task { border: 1px solid rgba(255,255,255,0.05); border-l
<?php endif; ?>
</div>
</div>
</div>
<?php endforeach; ?>
@@ -669,6 +927,13 @@ function allowDrop(ev) {
function drag(ev, taskId) {
ev.dataTransfer.setData("text", taskId);
// Get the task element from the header
let taskEl = ev.target.closest('.kanban-task');
setTimeout(() => taskEl.classList.add('dragging'), 0);
}
function dragEnd(ev) {
let taskEl = ev.target.closest('.kanban-task');
if(taskEl) taskEl.classList.remove('dragging');
}
function sortPendingTasks() {
@@ -723,7 +988,33 @@ function drop(ev, newStatus) {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: `task_id=${taskId}&status=${newStatus}`
}).then(() => showToast('Task updated.'));
}).then(() => {
showToast('Task updated.');
// Soft reload to show updated completions/archives visually
setTimeout(() => window.location.reload(), 300);
});
}
function addComment(taskId, form) {
let comment = form.comment.value;
if(!comment) return;
fetch('?action=api&api_action=add_comment', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: `task_id=${taskId}&comment=${encodeURIComponent(comment)}`
}).then(() => {
form.reset();
window.location.reload();
});
}
function deleteComment(commentId) {
if(!confirm('Delete this comment?')) return;
fetch('?action=api&api_action=delete_comment', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: `comment_id=${commentId}`
}).then(() => {
window.location.reload();
});
}
function toggleTaskExpand(header) {
@@ -755,9 +1046,14 @@ document.addEventListener("DOMContentLoaded", () => {
document.addEventListener('mousedown', function(e) {
let container = document.getElementById('to-dropdown-container');
if(container && !container.contains(e.target) && e.target.id !== 'to-input' && !e.target.closest('label')) {
if(container && !container.contains(e.target) && e.target.id !== 'to-input' && !e.target.closest('#to-icon-btn')) {
container.style.display = 'none';
}
let tagContainer = document.getElementById('tags-dropdown-container');
if(tagContainer && !tagContainer.contains(e.target) && !e.target.closest('#tag-icon-btn') && !e.target.closest('.tagify')) {
tagContainer.style.display = 'none';
}
});
let pendingTaskFiles = [];
@@ -904,11 +1200,22 @@ function handleDueDateChange(val) {
}
function clearDueDate() {
let input = document.querySelector('input[name="due_date"]');
input.value = '';
handleDueDateChange('');
duePicker.clear();
}
let duePicker;
document.addEventListener('DOMContentLoaded', () => {
duePicker = flatpickr("#due-picker-input", {
enableTime: true,
dateFormat: "Y-m-d H:i",
altInput: false,
disableMobile: "true",
onChange: function(selectedDates, dateStr) {
handleDueDateChange(dateStr);
}
});
});
let selectedAssignees = [];
function handleToSelection(val) {
@@ -1062,8 +1369,124 @@ function confirmCustomDelete(form, msg) {
return false;
}
function showAddTagPopup(taskId, existingTags) {
let tags = existingTags ? existingTags.split(',').filter(t => t.trim()) : [];
let overlay = document.createElement('div');
overlay.style.cssText = 'position:fixed; top:0; left:0; width:100vw; height:100vh; background:rgba(0,0,0,0.5); display:flex; align-items:center; justify-content:center; z-index:9999; opacity:0; transition:opacity 0.2s;';
let modal = document.createElement('div');
modal.style.cssText = 'background:var(--surface); padding:1.5rem; border-radius:1rem; min-width:300px; max-width:90vw; box-shadow:0 10px 25px rgba(0,0,0,0.2); transform:scale(0.9); transition:transform 0.2s;';
let tagsHtml = tags.map(tag => {
let escaped = tag.replace(/'/g, "\\'");
return `<span style="font-size:0.7rem; padding:3px 10px; border-radius:12px; background:rgba(var(--primary-rgb),0.15); color:var(--primary); font-weight:600; display:inline-flex; align-items:center; gap:0.3rem; margin:0.2rem;">
<i class="fas fa-tag" style="font-size:0.6rem;"></i> ${tag}
<i class="fas fa-times" style="cursor:pointer; opacity:0.6; font-size:0.65rem;" onclick="removeTagFromPopup('${escaped}', ${taskId})" title="Remove tag"></i>
</span>`;
}).join('');
modal.innerHTML = `
<h3 style="margin-bottom:1rem; font-size:1rem; text-align:center;"><i class="fas fa-tags" style="color:var(--primary);"></i> Manage Tags</h3>
<div id="popup-tags-list" style="margin-bottom:1rem; min-height:30px; ${tags.length ? '' : 'display:none;'}">${tagsHtml}</div>
<div style="display:flex; gap:0.5rem; margin-bottom:1rem;">
<input type="text" id="popup-tag-input" placeholder="Add tags (comma separated)..." style="flex:1; border:1px solid var(--border); background:var(--bg); color:var(--text); border-radius:8px; padding:0.5rem; font-size:0.875rem; box-sizing:border-box;" onkeypress="if(event.key==='Enter'){event.preventDefault();addTagsFromPopup(${taskId});">
<button type="button" onclick="addTagsFromPopup(${taskId})" style="background:var(--primary); color:white; border:none; border-radius:8px; padding:0.5rem 1rem; font-size:0.8rem; cursor:pointer;"><i class="fas fa-plus"></i></button>
</div>
<div style="text-align:center;">
<button onclick="closeTagPopup()" style="background:var(--border); color:var(--text); border:none; border-radius:8px; padding:0.4rem 1.5rem; font-size:0.8rem; cursor:pointer;">Close</button>
</div>
`;
overlay.appendChild(modal);
document.body.appendChild(overlay);
window.currentTagPopup = overlay;
window.currentTaskId = taskId;
setTimeout(() => {
overlay.style.opacity = '1';
modal.style.transform = 'scale(1)';
document.getElementById('popup-tag-input').focus();
}, 10);
overlay.onclick = function(e) {
if(e.target === overlay) closeTagPopup();
};
}
function closeTagPopup() {
if(window.currentTagPopup) {
window.currentTagPopup.style.opacity = '0';
window.currentTagPopup.querySelector('div').style.transform = 'scale(0.9)';
setTimeout(() => {
if(window.currentTagPopup) document.body.removeChild(window.currentTagPopup);
window.currentTagPopup = null;
window.location.reload();
}, 200);
}
}
function removeTagFromPopup(tag, taskId) {
fetch('?action=api&api_action=remove_task_tag', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: `task_id=${taskId}&tag=${encodeURIComponent(tag)}`
}).then(r => r.json()).then(res => {
if(res.success) {
// Refresh popup
closeTagPopup();
fetch('?action=api&api_action=get_tasks_status&task_id=' + taskId)
.then(r => r.json())
.then(data => {
if(data && !data.status) {
showAddTagPopup(taskId, data.tags || '');
}
});
}
});
}
function addTagsFromPopup(taskId) {
let input = document.getElementById('popup-tag-input');
let tags = input.value.split(',').map(t => t.trim()).filter(t => t);
if(!tags.length) return;
let promises = tags.map(tag =>
fetch('?action=api&api_action=add_task_tag', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: `task_id=${taskId}&tag=${encodeURIComponent(tag)}`
}).then(r => r.json())
);
Promise.all(promises).then(() => {
input.value = '';
// Refresh popup
closeTagPopup();
setTimeout(() => showAddTagPopup(taskId, ''), 250);
});
}
function addTaskTag(taskId) {
showAddTagPopup(taskId, '');
}
function removeTaskTag(taskId, tag) {
fetch('?action=api&api_action=remove_task_tag', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: `task_id=${taskId}&tag=${encodeURIComponent(tag)}`
}).then(r => r.json()).then(res => {
if(res.success) {
window.location.reload();
} else {
showToast('Error: ' + (res.error || 'Failed to remove tag'));
}
});
}
function uploadFilesAjax(taskId, files) {
if(files.length === 0) return;
let container = document.getElementById('progress-container-' + taskId);
let fill = document.getElementById('progress-fill-' + taskId);

74
views/tools.php Normal file
View File

@@ -0,0 +1,74 @@
<?php
// Tools page
?>
<div class="header">
<h1 style="font-size:1.5rem; font-weight:700;"><i class="fa fa-toolbox" style="color:var(--primary);"></i> Tools</h1>
</div>
<div class="db-grid">
<!-- Base64 encode/decode -->
<a href="#" class="db-stat-card" style="border-top:3px solid #6366F1;" onclick="openTool('base64'); return false;">
<div class="db-stat-label"><i class="fa fa-code"></i> Base64 En/Decode</div>
<div class="db-stat-sub" style="margin-top:auto;"><span style="background:rgba(99,102,241,0.12); color:#6366F1;">Text utility</span></div>
</a>
<!-- UUID Generator -->
<a href="#" class="db-stat-card" style="border-top:3px solid #10B981;" onclick="openTool('uuid'); return false;">
<div class="db-stat-label"><i class="fa fa-fingerprint"></i> UUID Generator</div>
<div class="db-stat-sub" style="margin-top:auto;"><span style="background:rgba(16,185,129,0.12); color:#10B981;">ID utility</span></div>
</a>
<!-- JSON Formatter -->
<a href="#" class="db-stat-card" style="border-top:3px solid #F59E0B;" onclick="openTool('json'); return false;">
<div class="db-stat-label"><i class="fa fa-code"></i> JSON Formatter</div>
<div class="db-stat-sub" style="margin-top:auto;"><span style="background:rgba(245,158,11,0.12); color:#F59E0B;">Dev utility</span></div>
</a>
</div>
<!-- Modal for tools -->
<div class="modal-overlay" id="tool-modal">
<div class="modal-content" style="max-width:600px; display:flex; flex-direction:column;">
<h3 id="tool-title" style="margin-bottom:1rem; font-size:1.1rem;"></h3>
<div id="tool-body" style="flex:1;"></div>
<button class="btn btn-secondary" style="margin-top:1rem; width:100%;" onclick="document.getElementById('tool-modal').classList.remove('active')">Close</button>
</div>
</div>
<script>
function openTool(tool) {
const title = document.getElementById('tool-title');
const body = document.getElementById('tool-body');
if (tool === 'base64') {
title.innerHTML = '<i class="fa fa-code"></i> Base64 Encoder/Decoder';
body.innerHTML = `
<textarea id="b64-input" class="form-control" rows="4" placeholder="Enter text here..."></textarea>
<div style="display:flex; gap:0.5rem; margin:1rem 0;">
<button class="btn" onclick="document.getElementById('b64-output').value = btoa(unescape(encodeURIComponent(document.getElementById('b64-input').value)))">Encode</button>
<button class="btn" onclick="try{document.getElementById('b64-output').value = decodeURIComponent(escape(atob(document.getElementById('b64-input').value)))}catch(e){alert('Invalid base64')}">Decode</button>
</div>
<textarea id="b64-output" class="form-control" rows="4" placeholder="Result..." readonly></textarea>
`;
} else if (tool === 'uuid') {
title.innerHTML = '<i class="fa fa-fingerprint"></i> UUID Generator';
body.innerHTML = `
<div style="display:flex; gap:0.5rem; margin-bottom:1rem;">
<input type="text" id="uuid-output" class="form-control" readonly style="font-family:monospace; font-size:1.1rem; text-align:center;">
<button class="btn" onclick="navigator.clipboard.writeText(document.getElementById('uuid-output').value); showToast('Copied!')"><i class="fa fa-copy"></i></button>
</div>
<button class="btn" style="width:100%;" onclick="document.getElementById('uuid-output').value = crypto.randomUUID()">Generate New UUID</button>
`;
setTimeout(() => document.getElementById('uuid-output').value = crypto.randomUUID(), 10);
} else if (tool === 'json') {
title.innerHTML = '<i class="fa fa-code"></i> JSON Formatter';
body.innerHTML = `
<textarea id="json-input" class="form-control" rows="8" placeholder="Paste JSON here..." style="font-family:monospace;"></textarea>
<div style="margin:1rem 0; text-align:right;">
<button class="btn" onclick="try{document.getElementById('json-input').value = JSON.stringify(JSON.parse(document.getElementById('json-input').value), null, 4)}catch(e){alert('Invalid JSON')}">Format JSON</button>
</div>
`;
}
document.getElementById('tool-modal').classList.add('active');
}
</script>