Deploy from Lumerel

This commit is contained in:
Lumerel Deploy
2026-02-18 03:36:11 +00:00
commit 618909f407
9 changed files with 1206 additions and 0 deletions

54
.docker/99-migrate.sh Normal file
View File

@@ -0,0 +1,54 @@
#!/bin/bash
# IMPORTANT: This script is sourced (not executed) by the webdevops entrypoint.
# Never use "exit" — it would kill the parent entrypoint and prevent supervisord from starting.
# Use "return" instead to leave this script without affecting the parent.
echo ">>> Waiting for database connection..."
echo ">>> DB_HOST=${DB_HOST:-NOT SET}"
echo ">>> DB_PORT=${DB_PORT:-NOT SET}"
echo ">>> DB_DATABASE=${DB_DATABASE:-NOT SET}"
echo ">>> DB_USERNAME=${DB_USERNAME:-NOT SET}"
echo ">>> DB_PASSWORD is $([ -n "$DB_PASSWORD" ] && echo 'set' || echo 'NOT SET')"
if [ -z "$DB_HOST" ] || [ -z "$DB_USERNAME" ]; then
echo ">>> ERROR: DB_HOST or DB_USERNAME not set. Skipping migrations."
return 0 2>/dev/null || true
fi
_migrate_max_retries=30
_migrate_count=0
_migrate_done=false
while [ $_migrate_count -lt $_migrate_max_retries ]; do
if php -r '
try {
$host = getenv("DB_HOST");
$port = getenv("DB_PORT") ?: "3306";
$user = getenv("DB_USERNAME");
$pass = getenv("DB_PASSWORD");
new PDO("mysql:host=$host;port=$port", $user, $pass, [PDO::ATTR_TIMEOUT => 3]);
exit(0);
} catch (Throwable $e) {
fwrite(STDERR, "PDO error: " . $e->getMessage() . "\n");
exit(1);
}
' 2>&1; then
echo ">>> Database is reachable. Running migrations..."
if php /app/migrate.php; then
echo ">>> Migrations completed successfully."
else
echo ">>> WARNING: migrate.php exited with code $?"
fi
_migrate_done=true
break
fi
_migrate_count=$((_migrate_count + 1))
echo ">>> Waiting for database... attempt $_migrate_count/$_migrate_max_retries"
sleep 2
done
if [ "$_migrate_done" = false ]; then
echo ">>> WARNING: Could not connect to database after $_migrate_max_retries attempts. Skipping migrations."
fi

3
.dockerignore Normal file
View File

@@ -0,0 +1,3 @@
.git
Dockerfile
.dockerignore

23
Dockerfile Normal file
View File

@@ -0,0 +1,23 @@
FROM webdevops/php-nginx:8.3-alpine
ENV WEB_DOCUMENT_ROOT=/app
ARG CACHE_BUST=1771385771
COPY . /app
RUN echo "index index.php index.html index.htm;" > /opt/docker/etc/nginx/vhost.common.d/01-index.conf \
&& echo "add_header Cache-Control 'no-cache, no-store, must-revalidate';" > /opt/docker/etc/nginx/vhost.common.d/02-no-cache.conf
RUN set -e; if [ -f /app/composer.json ]; then \
echo ">>> composer.json found, installing dependencies..."; \
curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer; \
cd /app && composer install --no-dev --no-interaction --optimize-autoloader; \
ls -la /app/vendor/autoload.php; \
else \
echo ">>> No composer.json found, skipping composer install"; \
fi
RUN set -e; if [ -f /app/package.json ]; then \
echo ">>> package.json found, installing node dependencies..."; \
apk add --no-cache nodejs npm; \
cd /app && npm install --production; \
else \
echo ">>> No package.json found, skipping npm install"; \
fi
COPY --chmod=755 .docker/99-migrate.sh /opt/docker/provision/entrypoint.d/99-migrate.sh
RUN chown -R application:application /app

208
api/todos.php Normal file
View File

@@ -0,0 +1,208 @@
<?php
require_once __DIR__ . '/../db.php';
// Set JSON headers
header('Content-Type: application/json');
// Handle CORS
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit();
}
$method = $_SERVER['REQUEST_METHOD'];
try {
switch ($method) {
case 'GET':
// Get all todos ordered by created_at DESC
$stmt = $pdo->query("SELECT * FROM todos ORDER BY created_at DESC");
$todos = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Convert is_completed to boolean
foreach ($todos as &$todo) {
$todo['is_completed'] = (bool) $todo['is_completed'];
}
http_response_code(200);
echo json_encode([
'success' => true,
'data' => $todos
]);
break;
case 'POST':
// Create new todo
$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['title']) || trim($input['title']) === '') {
http_response_code(400);
echo json_encode([
'success' => false,
'error' => 'Title is required'
]);
break;
}
$title = trim($input['title']);
$description = isset($input['description']) ? trim($input['description']) : '';
$stmt = $pdo->prepare("INSERT INTO todos (title, description) VALUES (?, ?)");
$stmt->execute([$title, $description]);
$id = $pdo->lastInsertId();
// Fetch the created todo
$stmt = $pdo->prepare("SELECT * FROM todos WHERE id = ?");
$stmt->execute([$id]);
$todo = $stmt->fetch(PDO::FETCH_ASSOC);
$todo['is_completed'] = (bool) $todo['is_completed'];
http_response_code(201);
echo json_encode([
'success' => true,
'data' => $todo
]);
break;
case 'PUT':
// Update todo
$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['id'])) {
http_response_code(400);
echo json_encode([
'success' => false,
'error' => 'Todo ID is required'
]);
break;
}
$id = $input['id'];
// Check if todo exists
$stmt = $pdo->prepare("SELECT * FROM todos WHERE id = ?");
$stmt->execute([$id]);
$todo = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$todo) {
http_response_code(404);
echo json_encode([
'success' => false,
'error' => 'Todo not found'
]);
break;
}
// Build update query dynamically based on provided fields
$updates = [];
$params = [];
if (isset($input['title'])) {
$updates[] = "title = ?";
$params[] = trim($input['title']);
}
if (isset($input['description'])) {
$updates[] = "description = ?";
$params[] = trim($input['description']);
}
if (isset($input['is_completed'])) {
$updates[] = "is_completed = ?";
$params[] = $input['is_completed'] ? 1 : 0;
}
if (empty($updates)) {
http_response_code(400);
echo json_encode([
'success' => false,
'error' => 'No fields to update'
]);
break;
}
$params[] = $id;
$sql = "UPDATE todos SET " . implode(', ', $updates) . " WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
// Fetch updated todo
$stmt = $pdo->prepare("SELECT * FROM todos WHERE id = ?");
$stmt->execute([$id]);
$todo = $stmt->fetch(PDO::FETCH_ASSOC);
$todo['is_completed'] = (bool) $todo['is_completed'];
http_response_code(200);
echo json_encode([
'success' => true,
'data' => $todo
]);
break;
case 'DELETE':
// Delete todo
$input = json_decode(file_get_contents('php://input'), true);
if (!isset($input['id'])) {
http_response_code(400);
echo json_encode([
'success' => false,
'error' => 'Todo ID is required'
]);
break;
}
$id = $input['id'];
// Check if todo exists
$stmt = $pdo->prepare("SELECT * FROM todos WHERE id = ?");
$stmt->execute([$id]);
$todo = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$todo) {
http_response_code(404);
echo json_encode([
'success' => false,
'error' => 'Todo not found'
]);
break;
}
// Delete the todo
$stmt = $pdo->prepare("DELETE FROM todos WHERE id = ?");
$stmt->execute([$id]);
http_response_code(200);
echo json_encode([
'success' => true,
'message' => 'Todo deleted successfully'
]);
break;
default:
http_response_code(405);
echo json_encode([
'success' => false,
'error' => 'Method not allowed'
]);
break;
}
} catch (PDOException $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Database error: ' . $e->getMessage()
]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode([
'success' => false,
'error' => 'Server error: ' . $e->getMessage()
]);
}

18
composer.json Normal file
View File

@@ -0,0 +1,18 @@
{
"name": "project/app",
"description": "A minimal PHP project",
"type": "project",
"require": {},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

12
db.php Normal file
View File

@@ -0,0 +1,12 @@
<?php
// Shared database connection — require this file in any script that needs DB access.
$pdo = new PDO(
'mysql:host=' . getenv('DB_HOST') . ';port=' . getenv('DB_PORT') . ';dbname=' . getenv('DB_DATABASE') . ';charset=utf8mb4',
getenv('DB_USERNAME'),
getenv('DB_PASSWORD'),
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]
);

846
index.php Normal file
View File

@@ -0,0 +1,846 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo App - Manage Your Tasks</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
color: #333;
}
.container {
max-width: 800px;
margin: 0 auto;
}
header {
text-align: center;
color: white;
margin-bottom: 40px;
animation: fadeInDown 0.6s ease-out;
}
header h1 {
font-size: 3rem;
font-weight: 700;
margin-bottom: 10px;
text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}
header p {
font-size: 1.1rem;
opacity: 0.9;
}
.card {
background: white;
border-radius: 16px;
padding: 30px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
margin-bottom: 30px;
animation: fadeInUp 0.6s ease-out;
}
.add-todo-form {
display: flex;
flex-direction: column;
gap: 15px;
}
.form-group {
display: flex;
flex-direction: column;
gap: 8px;
}
.form-group label {
font-weight: 600;
color: #555;
font-size: 0.9rem;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.form-group input,
.form-group textarea {
padding: 12px 16px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 1rem;
font-family: inherit;
transition: all 0.3s ease;
}
.form-group input:focus,
.form-group textarea:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.form-group textarea {
resize: vertical;
min-height: 80px;
}
.btn {
padding: 12px 24px;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}
.btn-primary:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}
.btn-primary:active {
transform: translateY(0);
}
.btn-primary:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
.btn-small {
padding: 6px 12px;
font-size: 0.85rem;
}
.btn-success {
background: #10b981;
color: white;
}
.btn-success:hover {
background: #059669;
}
.btn-danger {
background: #ef4444;
color: white;
}
.btn-danger:hover {
background: #dc2626;
}
.btn-secondary {
background: #6b7280;
color: white;
}
.btn-secondary:hover {
background: #4b5563;
}
.todos-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.todos-header h2 {
color: #333;
font-size: 1.5rem;
}
.todos-count {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 6px 16px;
border-radius: 20px;
font-size: 0.9rem;
font-weight: 600;
}
.loading {
text-align: center;
padding: 40px;
color: #667eea;
font-size: 1.1rem;
}
.spinner {
border: 3px solid #f3f3f3;
border-top: 3px solid #667eea;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
margin: 0 auto 15px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.error-message {
background: #fee2e2;
color: #dc2626;
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
border-left: 4px solid #dc2626;
animation: shake 0.5s ease;
}
.success-message {
background: #d1fae5;
color: #059669;
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
border-left: 4px solid #059669;
animation: fadeIn 0.5s ease;
}
.empty-state {
text-align: center;
padding: 60px 20px;
color: #9ca3af;
}
.empty-state svg {
width: 80px;
height: 80px;
margin-bottom: 20px;
opacity: 0.5;
}
.empty-state h3 {
font-size: 1.3rem;
margin-bottom: 10px;
}
.todo-list {
display: flex;
flex-direction: column;
gap: 15px;
}
.todo-item {
background: #f9fafb;
border: 2px solid #e5e7eb;
border-radius: 12px;
padding: 20px;
transition: all 0.3s ease;
animation: fadeIn 0.3s ease;
}
.todo-item:hover {
border-color: #667eea;
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15);
transform: translateY(-2px);
}
.todo-item.completed {
opacity: 0.7;
background: #f3f4f6;
}
.todo-item.editing {
border-color: #10b981;
background: #ecfdf5;
}
.todo-header {
display: flex;
align-items: flex-start;
gap: 15px;
margin-bottom: 10px;
}
.todo-checkbox {
width: 24px;
height: 24px;
cursor: pointer;
margin-top: 2px;
accent-color: #667eea;
}
.todo-content {
flex: 1;
}
.todo-title {
font-size: 1.1rem;
font-weight: 600;
color: #1f2937;
margin-bottom: 8px;
word-wrap: break-word;
}
.todo-item.completed .todo-title {
text-decoration: line-through;
color: #9ca3af;
}
.todo-description {
color: #6b7280;
font-size: 0.95rem;
line-height: 1.5;
word-wrap: break-word;
}
.todo-item.completed .todo-description {
color: #9ca3af;
}
.todo-actions {
display: flex;
gap: 8px;
margin-top: 15px;
flex-wrap: wrap;
}
.edit-form {
display: flex;
flex-direction: column;
gap: 12px;
margin-top: 15px;
}
.edit-form input,
.edit-form textarea {
padding: 10px 12px;
border: 2px solid #10b981;
border-radius: 6px;
font-size: 0.95rem;
font-family: inherit;
}
.edit-form input:focus,
.edit-form textarea:focus {
outline: none;
box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}
.edit-form textarea {
resize: vertical;
min-height: 60px;
}
.edit-actions {
display: flex;
gap: 8px;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeInUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes fadeInDown {
from {
opacity: 0;
transform: translateY(-30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-10px); }
75% { transform: translateX(10px); }
}
@media (max-width: 768px) {
header h1 {
font-size: 2rem;
}
header p {
font-size: 1rem;
}
.card {
padding: 20px;
}
.todos-header {
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
.todo-actions {
flex-direction: column;
}
.btn-small {
width: 100%;
}
.edit-actions {
flex-direction: column;
}
.edit-actions .btn {
width: 100%;
}
}
@media (max-width: 480px) {
body {
padding: 10px;
}
header {
margin-bottom: 20px;
}
header h1 {
font-size: 1.5rem;
}
.card {
padding: 15px;
border-radius: 12px;
}
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>Todo App</h1>
<p>Organize your tasks beautifully</p>
</header>
<div class="card">
<form id="addTodoForm" class="add-todo-form">
<div class="form-group">
<label for="todoTitle">Task Title *</label>
<input
type="text"
id="todoTitle"
name="title"
placeholder="What needs to be done?"
required
>
</div>
<div class="form-group">
<label for="todoDescription">Description (Optional)</label>
<textarea
id="todoDescription"
name="description"
placeholder="Add more details about this task..."
></textarea>
</div>
<button type="submit" class="btn btn-primary" id="addBtn">
Add Todo
</button>
</form>
</div>
<div class="card">
<div class="todos-header">
<h2>Your Tasks</h2>
<span class="todos-count" id="todosCount">0 tasks</span>
</div>
<div id="messageContainer"></div>
<div id="loadingContainer" class="loading" style="display: none;">
<div class="spinner"></div>
<p>Loading your tasks...</p>
</div>
<div id="todoList" class="todo-list"></div>
<div id="emptyState" class="empty-state" style="display: none;">
<svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path>
</svg>
<h3>No tasks yet</h3>
<p>Add your first task to get started!</p>
</div>
</div>
</div>
<script>
const API_URL = 'api/todos.php';
let todos = [];
let editingId = null;
// DOM Elements
const addTodoForm = document.getElementById('addTodoForm');
const todoList = document.getElementById('todoList');
const loadingContainer = document.getElementById('loadingContainer');
const emptyState = document.getElementById('emptyState');
const messageContainer = document.getElementById('messageContainer');
const todosCount = document.getElementById('todosCount');
const addBtn = document.getElementById('addBtn');
// Initialize
document.addEventListener('DOMContentLoaded', () => {
loadTodos();
addTodoForm.addEventListener('submit', handleAddTodo);
});
// Show loading state
function showLoading() {
loadingContainer.style.display = 'block';
todoList.style.display = 'none';
emptyState.style.display = 'none';
}
// Hide loading state
function hideLoading() {
loadingContainer.style.display = 'none';
}
// Show message
function showMessage(message, type = 'error') {
const messageDiv = document.createElement('div');
messageDiv.className = type === 'error' ? 'error-message' : 'success-message';
messageDiv.textContent = message;
messageContainer.innerHTML = '';
messageContainer.appendChild(messageDiv);
setTimeout(() => {
messageDiv.style.animation = 'fadeOut 0.5s ease';
setTimeout(() => {
messageContainer.innerHTML = '';
}, 500);
}, 3000);
}
// Clear message
function clearMessage() {
messageContainer.innerHTML = '';
}
// Update todos count
function updateTodosCount() {
const total = todos.length;
const completed = todos.filter(todo => todo.completed).length;
todosCount.textContent = `${total} task${total !== 1 ? 's' : ''} (${completed} completed)`;
}
// Load todos from API
async function loadTodos() {
showLoading();
clearMessage();
try {
const response = await fetch(API_URL);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
if (data.success) {
todos = data.data || [];
renderTodos();
} else {
throw new Error(data.message || 'Failed to load todos');
}
} catch (error) {
console.error('Error loading todos:', error);
showMessage('Failed to load tasks. Please check your connection and try again.');
todoList.style.display = 'none';
emptyState.style.display = 'none';
} finally {
hideLoading();
}
}
// Render todos
function renderTodos() {
if (todos.length === 0) {
todoList.style.display = 'none';
emptyState.style.display = 'block';
updateTodosCount();
return;
}
todoList.style.display = 'flex';
emptyState.style.display = 'none';
todoList.innerHTML = '';
todos.forEach(todo => {
const todoElement = createTodoElement(todo);
todoList.appendChild(todoElement);
});
updateTodosCount();
}
// Create todo element
function createTodoElement(todo) {
const div = document.createElement('div');
div.className = `todo-item ${todo.completed ? 'completed' : ''} ${editingId === todo.id ? 'editing' : ''}`;
div.dataset.id = todo.id;
if (editingId === todo.id) {
div.innerHTML = `
<div class="todo-header">
<div class="todo-content" style="width: 100%;">
<form class="edit-form" onsubmit="handleUpdateTodo(event, ${todo.id})">
<input
type="text"
value="${escapeHtml(todo.title)}"
id="editTitle${todo.id}"
required
autofocus
>
<textarea
id="editDescription${todo.id}"
placeholder="Description (optional)"
>${escapeHtml(todo.description || '')}</textarea>
<div class="edit-actions">
<button type="submit" class="btn btn-small btn-success">Save</button>
<button type="button" class="btn btn-small btn-secondary" onclick="cancelEdit()">Cancel</button>
</div>
</form>
</div>
</div>
`;
} else {
div.innerHTML = `
<div class="todo-header">
<input
type="checkbox"
class="todo-checkbox"
${todo.is_completed ? 'checked' : ''}
onchange="toggleTodoStatus(${todo.id})"
>
<div class="todo-content">
<div class="todo-title">${escapeHtml(todo.title)}</div>
${todo.description ? `<div class="todo-description">${escapeHtml(todo.description)}</div>` : ''}
</div>
</div>
<div class="todo-actions">
<button class="btn btn-small btn-success" onclick="startEdit(${todo.id})">Edit</button>
<button class="btn btn-small btn-danger" onclick="deleteTodo(${todo.id})">Delete</button>
</div>
`;
}
return div;
}
// Escape HTML to prevent XSS
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Handle add todo
async function handleAddTodo(e) {
e.preventDefault();
clearMessage();
const formData = new FormData(addTodoForm);
const title = formData.get('title').trim();
const description = formData.get('description').trim();
if (!title) {
showMessage('Please enter a task title');
return;
}
addBtn.disabled = true;
addBtn.textContent = 'Adding...';
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ title, description }),
});
const data = await response.json();
if (data.success) {
showMessage('Task added successfully!', 'success');
addTodoForm.reset();
await loadTodos();
} else {
throw new Error(data.message || 'Failed to add task');
}
} catch (error) {
console.error('Error adding todo:', error);
showMessage('Failed to add task. Please try again.');
} finally {
addBtn.disabled = false;
addBtn.textContent = 'Add Todo';
}
}
// Toggle todo status
async function toggleTodoStatus(id) {
const todo = todos.find(t => t.id === id);
if (!todo) return;
console.log('todo', todo);
const newStatus = !todo.is_completed;
try {
const response = await fetch(API_URL, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
id,
is_completed: newStatus
}),
});
const data = await response.json();
if (data.success) {
await loadTodos();
} else {
throw new Error(data.message || 'Failed to update task');
}
} catch (error) {
console.error('Error updating todo:', error);
showMessage('Failed to update task. Please try again.');
await loadTodos();
}
}
// Start editing
function startEdit(id) {
editingId = id;
renderTodos();
}
// Cancel editing
function cancelEdit() {
editingId = null;
renderTodos();
}
// Handle update todo
async function handleUpdateTodo(e, id) {
e.preventDefault();
clearMessage();
const title = document.getElementById(`editTitle${id}`).value.trim();
const description = document.getElementById(`editDescription${id}`).value.trim();
if (!title) {
showMessage('Please enter a task title');
return;
}
try {
const response = await fetch(API_URL, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id, title, description }),
});
const data = await response.json();
if (data.success) {
showMessage('Task updated successfully!', 'success');
editingId = null;
await loadTodos();
} else {
throw new Error(data.message || 'Failed to update task');
}
} catch (error) {
console.error('Error updating todo:', error);
showMessage('Failed to update task. Please try again.');
}
}
// Delete todo
async function deleteTodo(id) {
if (!confirm('Are you sure you want to delete this task?')) {
return;
}
clearMessage();
try {
const response = await fetch(API_URL, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ id }),
});
const data = await response.json();
if (data.success) {
showMessage('Task deleted successfully!', 'success');
await loadTodos();
} else {
throw new Error(data.message || 'Failed to delete task');
}
} catch (error) {
console.error('Error deleting todo:', error);
showMessage('Failed to delete task. Please try again.');
}
}
// Make functions global
window.toggleTodoStatus = toggleTodoStatus;
window.startEdit = startEdit;
window.cancelEdit = cancelEdit;
window.handleUpdateTodo = handleUpdateTodo;
window.deleteTodo = deleteTodo;
</script>
</body>
</html>

29
migrate.php Normal file
View File

@@ -0,0 +1,29 @@
<?php
// Migration runner executed automatically on deploy. Do NOT require from application code.
require_once __DIR__ . '/db.php';
// Create migrations tracking table
$pdo->exec("CREATE TABLE IF NOT EXISTS migrations (
id INT AUTO_INCREMENT PRIMARY KEY,
migration VARCHAR(255) NOT NULL UNIQUE,
ran_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");
// Get already-run migrations
$ran = $pdo->query("SELECT migration FROM migrations")->fetchAll(PDO::FETCH_COLUMN);
// Run pending migrations
$files = glob(__DIR__ . '/migrations/*.php');
sort($files);
foreach ($files as $file) {
$name = basename($file);
if (!in_array($name, $ran)) {
require $file;
$pdo->prepare("INSERT INTO migrations (migration) VALUES (?)")->execute([$name]);
echo "Migrated: {$name}\n";
}
}
echo "Migration complete.\n";

View File

@@ -0,0 +1,13 @@
<?php
$pdo->exec("
CREATE TABLE IF NOT EXISTS todos (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
description TEXT,
is_completed BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
");