query('SELECT id, name FROM users ORDER BY name'); $users = $user_stmt->fetchAll(); // Handle form submissions for adding/editing an account if ($_SERVER['REQUEST_METHOD'] === 'POST') { $name = trim($_POST['name']); $user_id = $_POST['user_id'] ?? null; $initial_balance = $_POST['initial_balance'] ?? 0; $currency = $_POST['currency'] ?? 'USD'; $id = $_POST['id'] ?? null; if (empty($name)) { $error = 'Account name is required.'; } else { try { if ($id) { // Update existing account $stmt = $pdo->prepare('UPDATE accounts SET name = ?, user_id = ?, initial_balance = ?, currency = ? WHERE id = ?'); $stmt->execute([$name, $user_id, $initial_balance, $currency, $id]); $message = 'Account updated successfully!'; } else { // Insert new account $stmt = $pdo->prepare('INSERT INTO accounts (name, user_id, initial_balance, currency) VALUES (?, ?, ?, ?)'); $stmt->execute([$name, $user_id, $initial_balance, $currency]); $message = 'Account added successfully!'; } } catch (PDOException $e) { $error = 'Database error: ' . $e->getMessage(); } } } // Handle deleting an account if (isset($_GET['delete'])) { $id = $_GET['delete']; try { $stmt = $pdo->prepare('DELETE FROM accounts WHERE id = ?'); $stmt->execute([$id]); $message = 'Account deleted successfully!'; } catch (PDOException $e) { $error = 'Error deleting account. It might be associated with expenses.'; } } // Handle fetching an account for editing if (isset($_GET['edit'])) { $id = $_GET['edit']; $stmt = $pdo->prepare('SELECT * FROM accounts WHERE id = ?'); $stmt->execute([$id]); $edit_account = $stmt->fetch(); } // Fetch all accounts to display $stmt = $pdo->query('SELECT a.*, u.name as user_name FROM accounts a LEFT JOIN users u ON a.user_id = u.id ORDER BY a.name'); $accounts = $stmt->fetchAll(); $currencies = ['USD', 'EUR', 'COP']; ?>