query("SELECT id, name FROM properties ORDER BY name")->fetchAll(); $tenants = $db->query("SELECT id, name FROM tenants ORDER BY name")->fetchAll(); if ($_SERVER['REQUEST_METHOD'] === 'POST') { $property_id = $_POST['property_id']; $tenant_id = $_POST['tenant_id']; $amount = $_POST['amount']; $payment_date = $_POST['payment_date']; $notes = $_POST['notes']; $stmt = $db->prepare("INSERT INTO payments (property_id, tenant_id, amount, payment_date, notes) VALUES (?, ?, ?, ?, ?)"); try { $db->beginTransaction(); $stmt->execute([$property_id, $tenant_id, $amount, $payment_date, $notes]); $payment_id = $db->lastInsertId(); if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) { $upload_dir = 'uploads/'; $file_name = uniqid() . '_' . basename($_FILES['file']['name']); $target_file = $upload_dir . $file_name; if (move_uploaded_file($_FILES['file']['tmp_name'], $target_file)) { $stmt = $db->prepare("INSERT INTO files (file_name, file_path, payment_id) VALUES (?, ?, ?)"); $stmt->execute([$_FILES['file']['name'], $target_file, $payment_id]); } else { throw new Exception("Failed to upload file."); } } $db->commit(); header("Location: index.php?page=payments&success=1"); exit; } catch (Exception $e) { $db->rollBack(); $error = "Error adding payment: " . $e->getMessage(); } } ?>