5 * 1024 * 1024) { // 5MB limit header("Location: manage_documents.php?resident_id={$resident_id}&error=file_too_large"); exit; } if (move_uploaded_file($file['tmp_name'], $target_path)) { try { $pdo = db(); $partner_id = null; $stmt = $pdo->prepare("SELECT id FROM partners WHERE user_id = ?"); $stmt->execute([$_SESSION['user_id']]); $partner_id = $stmt->fetchColumn(); $sql = "INSERT INTO documents (resident_id, partner_id, file_name, file_path, description) VALUES (?, ?, ?, ?, ?)"; $stmt = $pdo->prepare($sql); $stmt->execute([$resident_id, $partner_id, $original_name, $target_path, $description]); header("Location: manage_documents.php?resident_id={$resident_id}&success=uploaded"); exit; } catch (PDOException $e) { // Clean up the uploaded file if DB insert fails unlink($target_path); header("Location: manage_documents.php?resident_id={$resident_id}&error=db_error"); exit; } } else { header("Location: manage_documents.php?resident_id={$resident_id}&error=upload_failed"); exit; }