35603-vm/index.php
Flatlogic Bot 23eab8271d v2
2025-11-09 18:56:18 +00:00

172 lines
8.8 KiB
PHP

<?php
// This must be the very first line to ensure sessions work correctly.
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Check if the user is logged in. If not, redirect to the login page.
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
// --- CONFIG AND DB SETUP ---
require_once __DIR__ . '/db/config.php';
// The user ID is now securely retrieved from the session.
$user_id = $_SESSION['user_id'];
try {
$pdo = db();
// Idempotent table alteration to add user_id
// This is a one-time setup; it's safe to run multiple times due to 'ADD COLUMN IF NOT EXISTS' or similar logic in some DBs, or it will error harmlessly if the column exists.
// For broader compatibility, we'll wrap it in a try-catch that specifically ignores 'Duplicate column name' errors.
try {
$pdo->exec("ALTER TABLE tasks ADD COLUMN user_id INT NULL;");
} catch (PDOException $e) {
// Ignore error if the column already exists
if (strpos($e->getMessage(), 'Duplicate column name') === false) {
throw $e; // Re-throw if it's a different error
}
}
// --- HANDLE POST REQUESTS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$action = $_POST['action'] ?? '';
if ($action === 'add_task') {
$title = trim($_POST['title'] ?? '');
$description = trim($_POST['description'] ?? '');
if (!empty($title)) {
$stmt = $pdo->prepare("INSERT INTO tasks (title, description, user_id) VALUES (?, ?, ?)");
$stmt->execute([$title, $description, $user_id]);
$_SESSION['message'] = 'Task added successfully!';
$_SESSION['message_type'] = 'success';
} else {
$_SESSION['message'] = 'Task title cannot be empty.';
$_SESSION['message_type'] = 'danger';
}
} elseif ($action === 'update_status') {
$task_id = filter_var($_POST['task_id'] ?? 0, FILTER_VALIDATE_INT);
$status = $_POST['status'] ?? 'pending'; // Get current status to toggle
if ($task_id) {
// Correctly toggle between pending and completed
$new_status = ($status === 'completed') ? 'pending' : 'completed';
$stmt = $pdo->prepare("UPDATE tasks SET status = ? WHERE id = ? AND user_id = ?");
$stmt->execute([$new_status, $task_id, $user_id]);
$_SESSION['message'] = 'Task status updated!';
$_SESSION['message_type'] = 'success';
}
} elseif ($action === 'delete_task') {
$task_id = filter_var($_POST['task_id'] ?? 0, FILTER_VALIDATE_INT);
if ($task_id) {
$stmt = $pdo->prepare("DELETE FROM tasks WHERE id = ? AND user_id = ?");
$stmt->execute([$task_id, $user_id]);
$_SESSION['message'] = 'Task deleted successfully!';
$_SESSION['message_type'] = 'success';
}
}
// Redirect to self to prevent form resubmission
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
// --- FETCH TASKS FOR DISPLAY ---
// Ensure the 'status' column exists before querying, or handle its absence gracefully.
// For now, we assume it exists or the ALTER TABLE above would have created it.
$stmt = $pdo->prepare("SELECT id, title, description, status, created_at FROM tasks WHERE user_id = ? ORDER BY status ASC, created_at DESC");
$stmt->execute([$user_id]);
$tasks = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
// Log the error for debugging purposes
error_log("Database error: " . $e->getMessage());
// Provide a user-friendly error message
$error_message = "A database error occurred. Please try again later.";
$tasks = []; // Ensure tasks is empty on error
$_SESSION['message'] = $error_message;
$_SESSION['message_type'] = 'danger';
// If the error was specifically about a missing 'status' column, we might want to try fetching without it or prompt for migration.
// For this iteration, we'll assume the ALTER TABLE above handles it or the user will address it.
}
// The header is now included AFTER all the logic, ensuring it's only included if the script runs successfully.
require_once __DIR__ . '/includes/header.php';
?>
<!-- Add Task Form -->
<section id="add-task" class="mb-5">
<div class="card task-card">
<div class="card-body p-4">
<h2 class="card-title h4 mb-3">Add a New Task</h2>
<form action="index.php" method="POST">
<input type="hidden" name="action" value="add_task">
<div class="mb-3">
<label for="title" class="form-label">Task Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="e.g., Finish project report" required>
</div>
<div class="mb-3">
<label for="description" class="form-label">Description (Optional)</label>
<textarea class="form-control" id="description" name="description" rows="3" placeholder="Add more details about the task..."></textarea>
</div>
<button type="submit" class="btn btn-primary w-100 py-2">
<i class="bi bi-plus-lg"></i> Add Task
</button>
</form>
</div>
</div>
</section>
<!-- Task List -->
<section id="task-list">
<h2 class="h4 mb-4">Your Tasks</h2>
<?php if (empty($tasks)): ?>
<div class="text-center text-muted p-5 bg-light rounded-3">
<i class="bi bi-clipboard-check" style="font-size: 3rem;"></i>
<p class="mt-3 mb-0">You have no tasks yet. Add one above to get started!</p>
</div>
<?php else: ?>
<div class="list-group">
<?php foreach ($tasks as $task):
// Determine button class and icon based on task status
$button_class = ($task['status'] === 'completed') ? 'btn-warning' : 'btn-success';
$button_icon = ($task['status'] === 'completed') ? 'bi-arrow-counterclockwise' : 'bi-check-lg';
$button_title = ($task['status'] === 'completed') ? 'Mark as pending' : 'Mark as completed';
?>
<div class="list-group-item list-group-item-action task-card <?php echo $task['status'] === 'completed' ? 'completed' : ''; ?>">
<div class="d-flex w-100 justify-content-between">
<div>
<h5 class="mb-1"><?php echo htmlspecialchars($task['title']); ?></h5>
<p class="mb-1 small text-muted"><?php echo htmlspecialchars($task['description']); ?></p>
</div>
<div class="d-flex gap-2 align-items-center">
<form action="index.php" method="POST" class="d-inline">
<input type="hidden" name="action" value="update_status">
<input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
<input type="hidden" name="status" value="<?php echo $task['status']; ?>">
<button type="submit" class="btn btn-sm <?php echo $button_class; ?>" title="<?php echo $button_title; ?>">
<i class="bi <?php echo $button_icon; ?>"></i>
</button>
</form>
<form action="index.php" method="POST" class="d-inline delete-task-form">
<input type="hidden" name="action" value="delete_task">
<input type="hidden" name="task_id" value="<?php echo $task['id']; ?>">
<button type="submit" class="btn btn-sm btn-outline-danger" title="Delete task">
<i class="bi bi-trash"></i>
</button>
</form>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</section>
<?php require_once __DIR__ . '/includes/footer.php'; ?>